answer
stringlengths
15
1.25M
/* Basic */ body, input, select, textarea { font-size: 13pt; line-height: 1.75em; letter-spacing: 0.025em; } body { min-width: 1200px; } hr { margin: 2em 0 2em 0; } section, article { margin: 0 0 4em 0; } header.style1 { padding: 0 0 3em 0; } header.style1 h2 { font-size: 1.5em; letter-spacing: 0.075em; line-height: 1.5em; } header.style1 .byline { display: block; margin: 1.15em 0 0 0; font-size: 1.3em; letter-spacing: 0.075em; line-height: 1.5em; } form { } form label { margin: 0.25em 0 0.25em 0; } .button { padding: 0 2.25em 0 2.25em; font-size: 0.9em; min-width: 12em; height: 4em; line-height: 4em; } .button-big { font-size: 1em; min-width: 14em; } .actions { margin: 3em 0 0 0; } form .actions { margin-top: 1em; } .actions li { display: inline-block; margin: 0 0.75em 0 0.75em; } .actions li:first-child { margin-left: 0; } .actions li:last-child { margin-right: 0; } .actions-centered { text-align: center; } .feature-list { } .feature-list section { padding-top: 2em; border-top: solid 1px #eee; } .feature-list .row { } .feature-list .row:first-child { } .feature-list .row:first-child section { padding-top: 0; border-top: 0; } .feature-list h3 { margin: 0 0 0.75em 0; font-size: 1.15em; letter-spacing: 0.05em; margin-top: -0.35em; } .feature-list h3:before { width: 64px; height: 64px; line-height: 64px; margin-right: 0.75em; font-size: 32px; top: 0.2em; } .feature-list p { margin: 0 0 0 5em; } .feature-list-small { } .feature-list-small h3 { } .feature-list-small h3:before { font-size: 24px; line-height: 45px; width: 45px; height: 45px; margin-right: 1em; } .feature-list-small p { margin: 0 0 0 2em; } .is { } .is header { margin: 0 0 1.5em 0; } .is header.style1 { position: relative; margin: -0.5em 0 0 0; padding-top: 0; } .is h2 { margin: 0 0 0.75em 0; font-size: 1.15em; letter-spacing: 0.05em; color: #b30155 !important; } .is h3 { margin: 0 0 0.5em 0; font-size: 1em; font-weight: 600; letter-spacing: 0.05em; } .is-pair-one { padding-right: 1.5em; } .is-pair-two { padding-left: 1.5em; } .is-triple-one { padding-right: 1.5em; } .is-triple-two { padding-left: 0.75em; padding-right: 0.75em; } .is-triple-three { padding-left: 1.5em; } .is-post-excerpt { } .is-post-excerpt .image-left { position: relative; top: 0.5em; width: 5em; } .is-post-excerpt h3, .is-post-excerpt p { margin-left: 7em; } /* Wrappers */ .wrapper { padding: 6em 0 8em 0; } .wrapper .title { font-size: 1.3em; width: 39em; height: 3.25em; top: -3.25em; line-height: 3.25em; margin-bottom: -3.25em; margin-left: -19.5em; padding-top: 0.5em; } #header-wrapper { padding: 0; height: 500px; } .front #header-wrapper { height: 573px; } #intro-wrapper { padding-bottom: 8em; } /* Header */ #header { position: relative; height: 400px; } .front #header { height: 573px; } /* Logo */ #logo { position: absolute; height: 5em; top: 35%; left: 0; width: 100%; text-align: center; margin-top: -0.5em; } .front #logo { margin-top: -1em; } #logo h1 { font-size: 2em; letter-spacing: 0.25em; } #logo .byline { margin: 1.25em 0 0 0; display: block; letter-spacing: 0.2em; font-size: 0.9em; } /* Nav */ #nav { position: absolute; display: block; top: 2.5em; left: 0; width: 100%; text-align: center; } #nav > ul > li > ul { display: none; } #nav > ul { display: inline-block; border-radius: 0.35em; box-shadow: inset 0px 0px 1px 1px rgba(255,255,255,0.25); padding: 0 1.5em 0 1.5em; } #nav > ul > li { display: inline-block; text-align: center; padding: 0 1.5em 0 1.5em; } #nav > ul > li > a, #nav > ul > li > span { display: block; color: #eee; color: rgba(255,255,255,0.75); text-transform: uppercase; text-decoration: none; font-size: 0.7em; letter-spacing: 0.25em; height: 5em; line-height: 5em; -moz-transition: all .25s ease-in-out; -webkit-transition: all .25s ease-in-out; -o-transition: all .25s ease-in-out; -ms-transition: all .25s ease-in-out; transition: all .25s ease-in-out; outline: 0; } #nav > ul > li:hover > a, #nav > ul > li.active > a, #nav > ul > li.active > span { color: #fff; } .dropotron { background: #222835 url('images/overlay.png'); background-color: rgba(44,50,63,0.925); padding: 1.25em 1em 1.25em 1em; border-radius: 0.35em; box-shadow: inset 0px 0px 1px 1px rgba(255,255,255,0.25); min-width: 12em; text-align: left; } .dropotron.level-0 { margin-top: -1px; <API key>: 0; <API key>: 0; } .dropotron a, .dropotron span { display: block; color: #eee; color: rgba(255,255,255,0.75); text-transform: uppercase; text-decoration: none; font-size: 0.7em; letter-spacing: 0.25em; border-top: solid 1px rgba(255,255,255,0.15); line-height: 3em; -moz-transition: all .25s ease-in-out; -webkit-transition: all .25s ease-in-out; -o-transition: all .25s ease-in-out; -ms-transition: all .25s ease-in-out; transition: all .25s ease-in-out; } .dropotron li:first-child a, .dropotron li:first-child span { border-top: 0; } .dropotron li:hover > a, .dropotron li:hover > span { color: #fff; } /* Intro */ #intro { text-align: center; } #intro .style1 { font-size: 1.5em; letter-spacing: 0.075em; } #intro .style2 { font-size: 1.25em; letter-spacing: 0.075em; line-height: 1.35em; padding: 1em 0 1em 0; margin-bottom: 1em; } #intro .style3 { font-size: 1.1em; width: 48em; margin: 0 auto; } /* Features */ #features { padding: 0 6em 0 6em; } #features header.style1, #features .faces { padding-bottom: 5em; } #features .actions { margin-top: 5em; } /* Highlights */ #highlights { } #highlights .highlight { } #highlights .highlight h3 { margin: 0 0 0.75em 0; font-size: 1.35em; letter-spacing: 0.05em; } #highlights .highlight-one { padding-right: 2em; } #highlights .highlight-two { padding: 0 1em 0 1em; } #highlights .highlight-three { padding-left: 2em; } /* Main */ #main { margin: 1em 0 1em 0; } .front #main { margin: 0; } /* Content */ #content { } /* Sidebar */ #sidebar { } .left-sidebar #sidebar { padding-right: 3em; } .right-sidebar #sidebar { padding-left: 3em; } /* Footer */ #footer { } #footer header.style1 { padding-bottom: 0; } #footer hr { margin: 6em 0 6em 0; } #footer .footer-one { padding-right: 1.5em; } #footer .footer-two { padding-left: 1.5em; } { margin: 6em 0 0 0; } { padding: 1.5em 4em 1.5em 4em; line-height: 1em; font-size: 0.8em; } .<API key> #features, .node-type-project #features { padding: 0 3em 0 3em; } .<API key> .node-team-member, .node-type-project .project-parts { padding-left: 4em !important; }
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=3"> <link rel="stylesheet" type="text/css" href="lib/aos/aos.css"> <link rel="stylesheet" type="text/css" href="css/common.css"> <title>Fade Zoom In</title> </head> <body> <div class="container"> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> <div data-aos="fade-zoom-in" class="box box1"></div> <div data-aos="fade-zoom-in" class="box box2"></div> <div data-aos="fade-zoom-in" class="box box3"></div> <div data-aos="fade-zoom-in" class="box box4"></div> </div> <script src="lib/aos/aos.js"></script> <script> AOS.init({ offset: 200, duration: 600, easing: 'ease-in-sine', delay: 100, }); </script> </body> </html>
package utils; import com.github.lalyos.jfiglet.FigletFont; import function.external.base.DataManager; import global.Data; import java.io.*; import java.util.Date; import java.util.Properties; import java.util.concurrent.TimeUnit; /** * * @author nick */ public class LogManager { private static BufferedWriter userLog = null; private static String runTime; // users command log file path private static final String USERS_COMMAND_LOG = Data.ATAV_HOME + "log/users.command.log"; private static final String <API key> = Data.ATAV_HOME + "log/users.command.failed.log"; // program start date private static final Date date = new Date(); public static void run() { logRunTime(); <API key>(); close(); } public static void initPath() { try { userLog = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( CommonCommand.outputPath + "atav.log"))); } catch (<API key> ex) { ex.printStackTrace(); } try { <API key>(FigletFont.convertOneLine("ATAV")); writeAndPrint("Version: " + Data.VERSION); writeAndPrint("Start: " + date.toString()); writeAndPrint("Compute server: " + System.getenv("HOSTNAME")); writeLog("ATAV command:"); writeLog(CommandManager.command + "\n"); userLog.flush(); // email user job running EmailManager.sendEmailToUser("ATAV Job (" + LogManager.getJobID() + ") Running", CommandManager.command); } catch (Exception e) { ErrorManager.print("Error in writing log file: " + e.toString(), ErrorManager.UNEXPECTED_FAIL); } } public static void writeAndPrint(String str) { System.out.println(str + "\n"); writeLog(str + "\n"); } public static void <API key>(String str) { System.out.println(str); writeLog(str); } public static void writeLog(String str) { try { if (userLog != null) { userLog.write(str + "\n"); } } catch (Exception e) { } } public static void close() { try { if (userLog != null) { userLog.close(); } } catch (Exception e) { e.printStackTrace(); } } private static void logRunTime() { long elapsedTime = RunTimeManager.getElapsedTime(); long seconds = TimeUnit.MILLISECONDS.toSeconds(elapsedTime); long minutes = TimeUnit.MILLISECONDS.toMinutes(elapsedTime); long hours = TimeUnit.MILLISECONDS.toHours(elapsedTime); runTime = seconds + " seconds " + "(aka " + minutes + " minutes or " + hours + " hours)"; writeAndPrint("\n\nTotal runtime: " + runTime + "\n"); } private static void <API key>() { logUserCommand(USERS_COMMAND_LOG, ErrorManager.SUCCESS); <API key>("", ErrorManager.SUCCESS); } public static void <API key>(String error, int exit) { logUserCommand(<API key>, exit); <API key>(error, exit); } private static void logUserCommand(String logFilePath, int exit) { try { if (isBioinfoTeam()) { return; } File file = new File(logFilePath); FileWriter fileWritter = new FileWriter(file, true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); String cmdLogStr = getCommandLogStr(exit); bufferWritter.write(cmdLogStr); bufferWritter.newLine(); bufferWritter.close(); } catch (Exception e) { // not output error when writing to log file denied } } private static void <API key>(String error, int exit) { String cmdLogStr = getCommandLogStr(exit); String str = "Completed"; if (exit != ErrorManager.SUCCESS) { str = "Failed"; } // email user job complete EmailManager.sendEmailToUser("ATAV Job (" + LogManager.getJobID() + ") " + str, cmdLogStr + "\n\n" + error); } public static String getCommandLogStr(int exit) { long outputFolderSize = folderSize(new File(CommonCommand.realOutputPath)); return Data.userName + "\t" + date.toString() + "\t" + DBManager.getHost() + "\t" + System.getenv("HOSTNAME") + "\t" + CommandManager.command + "\t" + runTime + "\t" + outputFolderSize + " bytes" + "\t" + System.getenv("JOB_ID") + "\t" + exit; } public static String getJobID() { return System.getenv("JOB_ID"); } public static boolean isBioinfoTeam() { try { String configPath = Data.SYSTEM_CONFIG; if (CommonCommand.isDebug) { configPath = Data.<API key>; } InputStream input = new FileInputStream(configPath); Properties prop = new Properties(); prop.load(input); String members = prop.getProperty("bioinfo-team"); return members.contains(Data.userName); } catch (Exception e) { return false; } } private static long folderSize(File directory) { long length = 0; for (File file : directory.listFiles()) { if (file.isFile()) { length += file.length(); } else { length += folderSize(file); } } return length; } public static void <API key>() { String externalDataVersion = DataManager.getVersion(); if (!externalDataVersion.isEmpty()) { <API key>("External data version:"); <API key>(externalDataVersion); } } }
package com.example.ericliu.playdagger2; import android.app.Application; import android.test.ApplicationTestCase; public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
using System; using Cosmos.Logging.Core.Components; using Cosmos.Logging.Events; using Cosmos.Logging.Extensions.EntityFrameworkCore.Core; using EnumsNET; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; // ReSharper disable once CheckNamespace namespace Cosmos.Logging { public static class <API key> { public static DatabaseIntegration <API key>(this DatabaseIntegration integration, Action<EfCoreSinkOptions> settingAct = null, Action<IConfiguration, <API key>> configAction = null) { var settings = new EfCoreSinkOptions(); settingAct?.Invoke(settings); void InternalAction(IConfiguration conf, <API key> sink, <API key> configuration) { configAction?.Invoke(conf, sink); if (configuration?.LogLevel != null) { AddNamespace($"{typeof(DbContext).Namespace}.*", GetExpectLevelName()); AddNamespace($"{typeof(<API key>).FullName}", GetExpectLevelName()); AddNamespace(DbLoggerCategory.Database.Command.Name, GetExpectLevelName()); AddNamespace(DbLoggerCategory.Query.Name, GetExpectLevelName()); AddNamespace(DbLoggerCategory.Update.Name, GetExpectLevelName()); } void AddNamespace(string @namespace, string expectLevelName) { if (string.IsNullOrWhiteSpace(@namespace)) return; if (configuration.LogLevel.ContainsKey(@namespace)) { configuration.LogLevel[@namespace] = expectLevelName; } else { configuration.LogLevel.Add(@namespace, expectLevelName); } } string GetExpectLevelName() => settings.MinimumLevel.HasValue ? settings.MinimumLevel.Value.GetName() : LogEventLevel.Verbose.GetName(); } return <API key>(integration, Options.Create(settings), InternalAction); } private static DatabaseIntegration <API key>(DatabaseIntegration integration, IOptions<EfCoreSinkOptions> settings, Action<IConfiguration, <API key>, <API key>> config = null) { var serviceImpl = integration.<API key>; if (serviceImpl != null) { serviceImpl.<API key><EfCoreSinkOptions, <API key>>(settings.Value, (conf, sink, configuration) => config?.Invoke(conf, sink, configuration)); serviceImpl.AddDependency(s => s.TryAdd(ServiceDescriptor.Singleton(settings))); serviceImpl.AddDependency(s => s.TryAdd(ServiceDescriptor.Singleton(typeof(<API key>), provider => { var instance = new <API key>(provider.GetService<<API key>>(), settings); <API key>.Instance = instance; return instance; }))); <API key>(); } return integration; } private static void <API key>() { SinkComponentsTypes.SafeAddAppendType(new <API key>(typeof(IOptions<EfCoreSinkOptions>), false, ServiceLifetime.Singleton)); SinkComponentsTypes.SafeAddAppendType(new <API key>(typeof(<API key>), false, ServiceLifetime.Singleton)); } } }
using SlimDX.Direct3D9; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Litmus { public class <API key> : Form, ILitmus { private readonly IColorHelper _colorHelper; private readonly ISamplePointService _samplePointService; <summary> Handles the graphics device </summary> private static Device d; private static SamplePoints _samplePoints; private static Graphics _graphics; <summary> Ctor </summary> public <API key>() { _colorHelper = new ColorHelper(); _samplePointService = new SamplePointService(); PresentParameters present_params = new PresentParameters(); if (d == null) { d = new Device(new Direct3D(), 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.<API key>, present_params); } if (_samplePoints == null) { _samplePoints = _samplePointService.GetSamplePoints(.1f); } if (_graphics == null) { _graphics = this.CreateGraphics(); } } public LitmusColor GetMostCommonColor() { return this._colorHelper.<API key>(GetColors()); } public LitmusColor GetAverageColor() { return this._colorHelper.<API key>(GetColors()); } private IEnumerable<LitmusColor> GetColors() { var colors = new List<LitmusColor>(); using (var memoryImage = new Bitmap(_samplePoints.CenterBox.Width, _samplePoints.CenterBox.Height, _graphics)) { using (Graphics memoryGraphics = Graphics.FromImage(memoryImage)) { var size = new System.Drawing.Size { Width = _samplePoints.CenterBox.Width, Height = _samplePoints.CenterBox.Height }; memoryGraphics.CopyFromScreen(_samplePoints.CenterBox.X, _samplePoints.CenterBox.Y, 0, 0, size, CopyPixelOperation.SourceCopy); foreach (var point in _samplePoints.Points) { var pixel = memoryImage.GetPixel(point.X - _samplePoints.CenterBox.X, point.Y - _samplePoints.CenterBox.Y); var sampledColor = new LitmusColor { Red = pixel.R, Green = pixel.G, Blue = pixel.B }; colors.Add(sampledColor); } } } return colors; } } }
RightJS.Element.include({ appendTo: function(target) { return this.insertTo(target); }, prepend: function(content) { return this.insert(content, 'top'); }, before: function(content) { return this.insert(content, 'before'); }, after: function(content) { return this.insert(content, 'after'); }, insertBefore: function(target) { return this.insertTo(target, 'before'); }, attr: function(name, value) { return value === undefined ? this.get(name) : this.set(name, value); }, css: function(name, value) { return (typeof(name) === 'string' && value === undefined) ? this.getStyle(name) : this.setStyle(name, value); }, offset: function() { var position = this.position(); return { left: position.x, top: position.y }; }, width: function() { return this.size().x; }, height: function() { return this.size().y; }, scrollLeft: function() { return this.scrolls().x; }, scrollTop: function() { return this.scrolls().y; }, bind: function() { return this.on.apply(this, arguments); }, unbind: function() { return this.stopObserving.apply(this, arguments); }, trigger: function(name, options) { return this.fire(name, options); }, animate: function(style, time, finish) { return this.morph(style, {duration: time, onFinish: finish}); }, fadeIn: function() { return this.fade('in'); }, fadeOut: function() { return this.fade('out'); }, slideDown: function() { return this.slide('in'); }, slideUp: function() { return this.slide('out'); } });
from flask import Flask, request, abort import json from ReverseProxied import ReverseProxied app = Flask(__name__) app.wsgi_app = ReverseProxied(app.wsgi_app) with open("intervals.json") as b: data = json.load(b) def intersects(interval, min_age, max_age): if interval["lag"] <= min_age <= interval["eag"]: return True elif interval["lag"] <= max_age <= interval["eag"]: return True elif interval["lag"] >= min_age and max_age >= interval["eag"]: return True else: return False def <API key>(min_age, max_age): z = [interval for interval in data["records"] if intersects(interval, min_age, max_age)] z.sort(key=lambda x: x["lag"]) z.sort(key=lambda x: x["lvl"]) return json.dumps(z) def within(interval, min_age, max_age): return interval["lag"] <= min_age <= max_age <= interval["eag"] def <API key>(min_age, max_age): z = [interval for interval in data["records"] if within(interval, min_age, max_age)] if not z: return z z.sort(key=lambda x: x["lvl"], reverse=True) return json.dumps(z[0]) @app.route("/") def hello(): return json.dumps(data) def process_inputs(): min_age = request.args.get('min', None, type=float) max_age = request.args.get('max', None, type=float) if min_age is None or max_age is None: abort(400) return min_age, max_age @app.route("/resolve-within", methods=['GET']) def resolve_within(): min_age, max_age = process_inputs() return <API key>(min_age, max_age) @app.route("/resolve-intersects", methods=['GET']) def resolve_intersects(): min_age, max_age = process_inputs() return <API key>(min_age, max_age) if __name__ == "__main__": app.run()
# Merging Documents This advanced topic guide is waiting for more usage experience in order to get a handle on recommended practices. The basic idea of a merged document is that a page view will include one or more lookup results that can are useful to forms generated from the page. In order for the form to access the page-resident lookup results, it must be in the same document. In a merge situation, the framework acquires the form data as normal, but then copies the contents into the page document, tagging the merged elements to identify them for transformation and for being discarded when finished. This new method is being developed in the TestCase project, which may or not be available when reading this.
require 'spec_helper' require 'ghundle/command/install' module Ghundle module Command describe Install do let(:instance) { Install.new } before :each do FileUtils.mkdir_p '.git/hooks' end it "creates a git hook file if one does not exist" do create_script(hook_path('foo')) create_metadata(hook_path('foo'), 'types' => ['post-merge']) Install.call('foo') expect(File.exists?('.git/hooks/post-merge')).to be_truthy expect(File.executable?('.git/hooks/post-merge')).to be_truthy end it "can create multiple hooks" do create_script(hook_path('one')) create_metadata(hook_path('one'), 'types' => ['post-merge']) create_script(hook_path('two')) create_metadata(hook_path('two'), 'types' => ['post-checkout']) Install.call('one', 'two') expect(File.executable?('.git/hooks/post-merge')).to be_truthy expect(File.executable?('.git/hooks/post-checkout')).to be_truthy end it "adds the hooks to the relevant git hook files" do create_script(hook_path('foo')) create_metadata(hook_path('foo'), 'types' => ['post-merge', 'pre-receive']) Install.call('foo') expect(File.read('.git/hooks/post-merge')).to include 'ghundle run foo $*' expect(File.read('.git/hooks/pre-receive')).to include 'ghundle run foo $*' end end end end
<?php class Config { // DBTRUE // FALSE const USE_DATABASE = FALSE; private static $dataMethods; // OAuth private static $OAuth; private static $baseConfigs; public static function init(){ self::defineInfo(); self::requireFiles(); self::$dataMethods = new DataMethods(MethodsFactory::create(Config::USE_DATABASE)); } // $dataMethods public static function setDataMethods(DataMethods $dataMethods){ self::$dataMethods = $dataMethods; } public static function defineInfo(){ if(defined('DATA_DIR')){ return; } define('DATA_DIR', BASE_DIR . '/data'); define('MODE_DIR', BASE_DIR . '/modes'); define('METHOD_DIR', BASE_DIR . '/methods'); define('UTIL_DIR', BASE_DIR . '/utils'); define('TPL_DIR', BASE_DIR . '/templates'); define('TITLE', 'phpBotAdmin()'); define('URL', "{$_SERVER['SCRIPT_NAME']}"); define('PORT', "{$_SERVER['SERVER_PORT']}"); } public static function requireFiles(){ require_once BASE_DIR . '/Controller.php'; require_once BASE_DIR . '/Exceptions.php'; require_once BASE_DIR . '/Parameters.php'; require_once BASE_DIR . '/CheckLogin.php'; require_once BASE_DIR . '/twitteroauth/twitteroauth/twitteroauth.php'; require_once METHOD_DIR . '/DataMethods.php'; require_once METHOD_DIR . '/Methods.php'; require_once METHOD_DIR . '/MethodsFactory.php'; require_once METHOD_DIR . '/TwitterMethods.php'; require_once MODE_DIR . '/ModeBase.php'; require_once MODE_DIR . '/ReactionBase.php'; require_once UTIL_DIR . '/CheckUtils.php'; require_once UTIL_DIR . '/Utils.php'; } // OAuth public static function setOAuth(){ if(!isset(self::$dataMethods)){ self::setDataMethods(new DataMethods(MethodsFactory::create(Config::USE_DATABASE))); } $keys = self::$dataMethods->getMethods()->read('OAuth', array(DataMethods::CONSUMER_KEY_COL, DataMethods::CONSUMER_SECRET_COL, DataMethods::ACCESS_TOKEN_COL, DataMethods::<API key>)); $keys = $keys[0]; self::$OAuth['consumer_key'] = $keys[DataMethods::CONSUMER_KEY_COL]; self::$OAuth['consumer_secret'] = $keys[DataMethods::CONSUMER_SECRET_COL]; self::$OAuth['access_token'] = $keys[DataMethods::ACCESS_TOKEN_COL]; self::$OAuth['access_token_secret'] = $keys[DataMethods::<API key>]; } // OAuth public static function getOAuth(){ return self::$OAuth; } public static function setBaseConfigs(){ if(!isset(self::$dataMethods)){ self::setDataMethods(new DataMethods(MethodsFactory::create(Config::USE_DATABASE))); } $configs = self::$dataMethods->getMethods()->read('baseConfigs'); $configs = $configs[0]; self::$baseConfigs[DataMethods::AUTO_FOLLOW_COL] = (isset($configs[DataMethods::AUTO_FOLLOW_COL]) && $configs[DataMethods::AUTO_FOLLOW_COL] === '1') ? '1' : ''; self::$baseConfigs[DataMethods::CUT_COL] = (isset($configs[DataMethods::CUT_COL]) && $configs[DataMethods::AUTO_FOLLOW_COL] === '1') ? '1' : ''; } public function getBaseConfigs(){ return self::$baseConfigs; } }
.PHONY: infra plan apply tf-apply clean mrproper destroy help .DEFAULT_GOAL := help AWS_PROFILE ?= default NOW := $(shell date +"%Y%m%d-%H%M%S") RESOURCES := terraform TF_VARS ?= $(RESOURCES)/terraform.tfvars PLAN := plan.out export AWS_PROFILE infra: plan apply ## Do whatever's needed to bring the infra up to date plan: ## Plan, display and store that which would be needed to bring the infra up to date terraform plan -out $(PLAN) -var-file=$(TF_VARS) $(RESOURCES)/ apply: tf-apply clean ## Apply the current plan of operations to the infra, without replanning tf-apply: terraform apply $(PLAN) destroy: ## DANGER!!!! THIS DESTROYS THE WHOLE BOSH STACK!!!! BE SURE WHAT YOU ARE DOING!!!!! # bosh delete deployment --force concourse bosh-init delete bosh-director.yml terraform destroy -force -var-file=$(TF_VARS) $(RESOURCES)/ show: ## Print what the current plan of operations would do, without replanning terraform show $(PLAN) clean: ## Archive the last plan mv $(PLAN) .$(PLAN).$(NOW) help: ## Display this help @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
<!DOCTYPE html> <html> <head> <title>Membuat login dengan codeigniter </title> </head> <body> <h1>Login berhasil !</h1> <h2>Hai, <?php echo $this->session->userdata("nama"); ?></h2> <a href="<?php echo base_url('user_login/logout'); ?>">Logout</a> </body> </html>
ProcessTracking::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.<API key> = true config.action_controller.perform_caching = false config.eager_load = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.<API key> = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Print deprecation notices to the stderr config.active_support.deprecation = :stderr config.serve_static_files = true config.<API key> = 'public, max-age=3600' config.active_support.test_order = :random end
//| MachOKit - A Lightweight Mach-O Parsing Library //! @file data_model.h //! @author D.V. //| copy of this software and associated documentation files (the "Software"), //| to deal in the Software without restriction, including without limitation //| 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: //| in all copies or substantial portions of the Software. //| OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. //| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, //| TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE //| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //! @defgroup DATA_MODEL Data Model //! @ingroup CORE //! A data model contains basic information about how primative types are //! defined by an ABI. #ifndef _data_model_h #define _data_model_h //! @addtogroup DATA_MODEL #pragma mark - Types //! @name Types //! @internal struct mk_data_model_s { __MK_RUNTIME_BASE }; //! The Data Model polymorphic type. typedef union { struct mk_data_model_s *data_model; } mk_data_model_ref <API key>; //! The identifier for the Data Model type. _mk_export intptr_t mk_data_model_type; //! The identifier for the ILP32 Data Model type. _mk_export intptr_t <API key>; //! The identifier for the LP64 Data Model type. _mk_export intptr_t <API key>; #pragma mark - Retrieving The Standard Data Models //! @name Retrieving The Standard Data Models //! Returns the little-endian ILP32 data model used in Intel/ARM 32-bit //! Mach-O images. _mk_export mk_data_model_ref mk_data_model_ilp32(void); //! Returns the little-endian LP64 data model used in Intel/ARM 64-bit //! Mach-O images. _mk_export mk_data_model_ref mk_data_model_lp64(void); #pragma mark - Instance Methods //! @name Instance Methods //! Returns a \ref mk_byteorder_t for converting data between the endianness of //! data represented in the specified data model and the current process. _mk_export const mk_byteorder_t* <API key>(mk_data_model_ref data_model); //! Returns the size of a pointer, as defined by the specified data model. _mk_export size_t <API key>(mk_data_model_ref data_model); //! Returns the alignment of a pointer, as defined by the specified data model. _mk_export size_t <API key>(mk_data_model_ref data_model); //! @} DATA_MODEL !// #endif /* _data_model_h */
#include <globjects/VertexArray.h> #include <cassert> #include <glbinding/gl/functions.h> #include <glbinding/gl/enum.h> #include <globjects/<API key>.h> #include "registry/<API key>.h" #include "implementations/<API key>.h" #include "base/container_helpers.h" #include "registry/ObjectRegistry.h" #include <globjects/Resource.h> using namespace gl; namespace { globjects::<API key> & implementation() { return globjects::<API key>::current().<API key>(); } } // namespace namespace globjects { VertexArray::VertexArray() : Object(std::unique_ptr<IDResource>(new <API key>)) { } VertexArray::VertexArray(std::unique_ptr<IDResource> && resource) : Object(std::move(resource)) { } void VertexArray::<API key>(const <API key> impl) { <API key>::current().initialize(impl); } std::unique_ptr<VertexArray> VertexArray::fromId(const GLuint id) { return std::unique_ptr<VertexArray>(new VertexArray(std::unique_ptr<IDResource>(new ExternalResource(id)))); } std::unique_ptr<VertexArray> VertexArray::defaultVAO() { return VertexArray::fromId(0); } VertexArray::~VertexArray() { } void VertexArray::bind() const { glBindVertexArray(id()); } void VertexArray::unbind() { glBindVertexArray(0); } <API key> * VertexArray::binding(const GLuint bindingIndex) { const auto it = m_bindings.find(bindingIndex); if (it == m_bindings.end()) { const auto insertedIt = m_bindings.emplace(bindingIndex, <API key>::create(this, bindingIndex)); return insertedIt.first->second.get(); } return it->second.get(); } const <API key>* VertexArray::binding(const GLuint bindingIndex) const { const auto it = m_bindings.find(bindingIndex); if (it == m_bindings.end()) { return nullptr; } return it->second.get(); } void VertexArray::bindElementBuffer(const Buffer *buffer) { implementation().bindElementBuffer(this, buffer); } void VertexArray::enable(GLint attributeIndex) { implementation().enable(this, attributeIndex); } void VertexArray::disable(GLint attributeIndex) { implementation().disable(this, attributeIndex); } std::vector<<API key> *> VertexArray::bindings() { std::vector<<API key> *> bindings; bindings.reserve(m_bindings.size()); for (const auto & pair: m_bindings) bindings.push_back(pair.second.get()); return bindings; } std::vector<const <API key>*> VertexArray::bindings() const { std::vector<const <API key>*> bindings; bindings.reserve(m_bindings.size()); for (const auto & pair: m_bindings) { bindings.push_back(pair.second.get()); } return bindings; } void VertexArray::drawArrays(const GLenum mode, const GLint first, const GLsizei count) const { bind(); glDrawArrays(mode, first, count); } void VertexArray::drawArraysInstanced(const GLenum mode, const GLint first, const GLsizei count, const GLsizei instanceCount) const { bind(); <API key>(mode, first, count, instanceCount); } void VertexArray::<API key>(const GLenum mode, const GLint first, const GLsizei count, const GLsizei instanceCount, const GLuint baseInstance) const { bind(); <API key>(mode, first, count, instanceCount, baseInstance); } void VertexArray::drawArraysIndirect(const GLenum mode, const void* indirect) const { // Don't assert a non-null indirect pointer as it may be a zero offset into the indirection buffer in GPU memory bind(); <API key>(mode, indirect); } void VertexArray::multiDrawArrays(const GLenum mode, GLint* first, const GLsizei* count, const GLsizei drawCount) const { bind(); glMultiDrawArrays(mode, first, count, drawCount); } void VertexArray::<API key>(const GLenum mode, const void* indirect, const GLsizei drawCount, const GLsizei stride) const { bind(); <API key>(mode, indirect, drawCount, stride); } void VertexArray::drawElements(const GLenum mode, const GLsizei count, const GLenum type, const void * indices) const { bind(); glDrawElements(mode, count, type, indices); } void VertexArray::<API key>(const GLenum mode, const GLsizei count, const GLenum type, const void* indices, const GLint baseVertex) const { bind(); <API key>(mode, count, type, const_cast<void*>(indices), baseVertex); } void VertexArray::<API key>(const GLenum mode, const GLsizei count, const GLenum type, const void* indices, const GLsizei primitiveCount) const { bind(); <API key>(mode, count, type, indices, primitiveCount); } void VertexArray::<API key>(const GLenum mode, const GLsizei count, const GLenum type, const void* indices, const GLsizei instanceCount, const GLuint baseInstance) const { bind(); <API key>(mode, count, type, indices, instanceCount, baseInstance); } void VertexArray::<API key>(const GLenum mode, const GLsizei count, const GLenum type, const void* indices, const GLsizei instanceCount, const GLint baseVertex) const { bind(); <API key>(mode, count, type, indices, instanceCount, baseVertex); } void VertexArray::<API key>(const GLenum mode, const GLsizei count, const GLenum type, const void* indices, const GLsizei instanceCount, const GLint baseVertex, const GLuint baseInstance) const { bind(); <API key>(mode, count, type, indices, instanceCount, baseVertex, baseInstance); } void VertexArray::multiDrawElements(const GLenum mode, const GLsizei* count, const GLenum type, const void** indices, const GLsizei drawCount) const { bind(); glMultiDrawElements(mode, count, type, indices, drawCount); } void VertexArray::<API key>(const GLenum mode, const GLsizei* count, const GLenum type, const void** indices, const GLsizei drawCount, GLint* baseVertex) const { bind(); <API key>(mode, const_cast<GLsizei*>(count), type, const_cast<void**>(indices), drawCount, baseVertex); } void VertexArray::<API key>(const GLenum mode, const GLenum type, const void* indirect, const GLsizei drawCount, const GLsizei stride) const { bind(); <API key>(mode, type, indirect, drawCount, stride); } void VertexArray::drawRangeElements(const GLenum mode, const GLuint start, const GLuint end, const GLsizei count, const GLenum type, const void* indices) const { bind(); glDrawRangeElements(mode, start, end, count, type, indices); } void VertexArray::<API key>(const GLenum mode, const GLuint start, const GLuint end, const GLsizei count, const GLenum type, const void* indices, const GLint baseVertex) const { bind(); <API key>(mode, start, end, count, type, const_cast<void*>(indices), baseVertex); } void VertexArray::multiDrawArrays(const GLenum mode, const std::vector<VertexArray::<API key>> & ranges) const { std::vector<GLint> firsts = collect_member(ranges, &<API key>::first); std::vector<GLsizei> counts = collect_member(ranges, &<API key>::count); multiDrawArrays(mode, firsts.data(), counts.data(), static_cast<GLsizei>(ranges.size())); } void VertexArray::multiDrawElements(const GLenum mode, const GLenum type, const std::vector<VertexArray::<API key>> & ranges) const { std::vector<GLsizei> counts = collect_member(ranges, &<API key>::count); std::vector<const void*> indices = collect_type_member<const void*>(ranges, &<API key>::indices); multiDrawElements(mode, counts.data(), type, indices.data(), static_cast<GLsizei>(ranges.size())); } void VertexArray::<API key>(const GLenum mode, const GLenum type, const std::vector<VertexArray::<API key>> & ranges) const { std::vector<GLsizei> counts = collect_member(ranges, &<API key>::count); std::vector<const void*> indices = collect_type_member<const void*>(ranges, &<API key>::indices); std::vector<GLint> baseVertices = collect_member(ranges, &<API key>::baseVertex); <API key>(mode, counts.data(), type, indices.data(), static_cast<GLsizei>(ranges.size()), baseVertices.data()); } GLenum VertexArray::objectType() const { return GL_VERTEX_ARRAY; } } // namespace globjects
import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; import CachePage from './components/CachePage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('/http-cache', async () => <CachePage title="http-cache"/>); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
# This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support*.rb")].each {|f| require f} RSpec.configure do |config| # ## Mock Framework # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures #config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. #config.<API key> = true # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.<API key> = false # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = "random" end
<?php namespace Ipunkt\LaravelNotify; use Config; use Illuminate\Auth\UserInterface; use Illuminate\Support\Collection; use Ipunkt\LaravelNotify\Contracts\<API key>; use Ipunkt\LaravelNotify\Exceptions\<API key>; use Ipunkt\LaravelNotify\Models\Notification; use Ipunkt\LaravelNotify\Models\<API key>; use Ipunkt\LaravelNotify\Types\MessageNotification; use Redirect; use Symfony\Component\HttpFoundation\Response; /** * Class NotificationManager * @package Ipunkt\LaravelNotify */ class NotificationManager { /** @var string $context */ private $context = null; /** @var array $activities */ private $activities = []; /** * Create a new Notification for the user * * @param UserInterface|int $user * @param string|Notification|<API key> $notification */ public function user($user, $notification) { $this->users([$user], $notification); } /** * Create a new Notification for multiple users * @param array $users of UserInterface * @param string|Notification|<API key> $notification */ public function users($users, $notification) { /** @var Notification $notification */ $notification = $this->createNotification($notification); foreach ($users as $user) { $this->addActivity($notification, <API key>::CREATED, $user); } } /** * Create a payload string from the given job and data. * * @param <API key>|string|Notification $notification * @return Notification */ protected function createNotification($notification) { if ($notification instanceof <API key>) { return Notification::publish($notification); } if ($notification instanceof Notification) { return $notification; } return $this->createNotification(new MessageNotification($notification)); } /** * Add a new Activity to the Notification for the user * @param Notification $notification * @param string $activity * @param UserInterface $user * @return bool */ public function addActivity(Notification $notification, $activity, UserInterface $user) { /** * Aktuellen Status nicht erneut setzen */ if ($notification->currentState($user) === $activity) { return false; } /** @var <API key> $user_activity */ $user_activity = new <API key>(['activity' => $activity, 'user_id' => $user->getAuthIdentifier()]); return ($notification->activities()->save($user_activity) !== false); } /** * Get all Notifications for the user * @param UserInterface $user * @return <API key>[]|Collection */ public function get(UserInterface $user) { $query = $this->buildQuery($user); $notificationModels = $query->get(); return $this-><API key>($notificationModels, $user); } /** * builds a query by given flags * * @param UserInterface $user * @return \Illuminate\Database\Eloquent\Builder */ private function buildQuery(UserInterface $user) { $query = Notification::forUser($user); if (!empty($this->activities)) { $query->withActivities($this->activities); } if (!empty($this->context)) { $query->withContext($this->context); } $query->reverse(); return $query; } /** * instantiates notification types * * @param Notification[] $notificationModels * @param UserInterface $user * @return <API key>[]|Collection */ private function <API key>($notificationModels, UserInterface $user) { /** * Create NotificationTypes */ $notifies = new Collection(); /** @var Notification $notificationModel */ foreach ($notificationModels as $notificationModel) { $notifies->push($this-><API key>($notificationModel, $user)); } return $notifies; } /** * @param Notification $notification * @param UserInterface $user * @throws Exceptions\<API key> * @return <API key> */ protected function <API key>(Notification $notification, UserInterface $user) { $notification->setUser($user); $notifytype = unserialize($notification->data[0]); if ($notifytype instanceof <API key>) { return $notifytype->setModel($notification); } throw new <API key>; } /** * returns paginated list of Notifications for the given user * * @param UserInterface $user * @param int $itemsPerPage * @return array */ public function paginate(UserInterface $user, $itemsPerPage = 15) { $query = $this->buildQuery($user); $paginatorModels = $query->paginate($itemsPerPage); return [ 'items' => $this-><API key>($paginatorModels, $user), 'links' => $paginatorModels->links(), ]; } /** * set activities * * @param array $activities * @return $this */ public function withActivities(array $activities) { $this->activities = $activities; return $this; } /** * sets context * * @param string $context * for wildcard * @return $this */ public function inContext($context) { $this->context = $context; return $this; } /** * Do or undo actions * @param Notification $notification * @param string $action Name of the action (if starts with 'un' tries to undo the action) * @param UserInterface $user * @return Response Redirect::back() by default */ public function doAction(Notification $notification, $action, UserInterface $user) { /** @var <API key> $class */ $class = $this-><API key>($notification, $user); /** @var UserInterface[] $users */ $users = [$user]; /** * If action starts with 'un' and original method exists */ if (strpos($action, 'un') === 0) { /** * check Autobehavior of action to undo */ if (method_exists($class, $unaction = substr($action, 2)) && $class->isDoAutoLogActivity($unaction)) { /** * remove action from all users */ if ($class->isGrouped($unaction)) { $users = $notification->users; } foreach ($users as $currentUser) { $this->removeActivity($notification, $unaction, $currentUser); } } } /** * if action exists as method in NotificationType */ if (method_exists($class, $action)) { if ($class->isDoAutoLogActivity($action)) { /** * log grouped actions for all users */ if ($class->isGrouped($action)) { $users = $notification->users; } foreach ($users as $currentUser) { $this->addActivity($notification, $action, $currentUser); } } return $class->$action(); } return Redirect::back(); } /** * Remove / delete an activity from the Notification for the user * @param Notification $notification * @param string $activity * @param UserInterface $user * @return bool */ public function removeActivity(Notification $notification, $activity, UserInterface $user) { try { /** * using index */ $user_activity = $notification->activities()->where('user_id', $user->getAuthIdentifier())->where('activity', $activity)->firstOrFail(); if ($user_activity->delete()) { return true; } return false; } catch (\Exception $e) { return false; } } }
// Get the modal var modal = document.getElementById('myModal'); // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get the <span> element that closes the modal var span = document.<API key>("close")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }
package com.aol.spring.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.<API key>; import org.springframework.context.ApplicationContext; import java.util.Arrays; @<API key> public class <API key> { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(<API key>.class, args); System.out.println("List all beans: "); String[] beanNames = ctx.<API key>(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } } }
<div class="container-fluid"> Total Users registered: <span ng-bind="userCount"></span> * 100 = {{userCount * 100}} (Total Price Money)<br><br> Search: <input type="search" class="form-control" style="width: 140px; display: inline" ng-model="query"><br> <div style="height:525px; width: 380px; overflow:auto; background-color: rgba(240, 255, 255, 0.5); float: left"> <table style="width: auto"> <thead> <tr> <th> Rank </th> <th> Name </th> <th> Points </th> <th> Prize </th> </tr> </thead> <tbody> <tr ng-repeat="leader in leaders | filter:query"> <td style="width: 50px"> {{leader.rank}} </td> <td style="text-wrap: none; white-space: nowrap"> <a href="mailto:{{leader.email}}">{{leader.name}}</a> </td> <td style="width: 70px"> {{leader.points}} </td> <td style="width: 100px"> <span ng-show="leader.rank<4">{{getPrizeAmount(leader)}}</span> <span ng-show="leader.rank>=4"><img src="img/tongue.png" /></span> </td> </tr> </tbody> </table> </div> <div ng-show="hasProgress" style="height:565px; width: 830px; overflow:auto; background-color: rgba(240, 255, 255, 0.5); float: left"> <div data-ac-chart="'line'" data-ac-data="progressData" data-ac-config="config" style="height:525px; width: 830px; float: left"> </div> </div> </div>
package calculate; import java.util.ArrayList; public class EdgeList{ private ArrayList<Edge> edgeList = new ArrayList<>(); public EdgeList(){ } public synchronized ArrayList<Edge> getEdgeList() { boolean valueSet = true; while (!valueSet){ try { wait(); } catch (<API key> e) { System.out.println(e.getMessage()); } } valueSet = false; notify(); return edgeList; } public synchronized void setEdgeList(ArrayList<Edge> edgeList) { this.edgeList = edgeList; } public synchronized void addToEdgeList(Edge e){ boolean valueSet = true; while (!valueSet){ try { wait(); } catch (<API key> ex) { System.out.println(ex.getMessage()); } } valueSet = false; notify(); edgeList.add(e); } public synchronized void clearEdgeList(){ boolean valueSet = true; while (!valueSet){ try { wait(); } catch (<API key> ex) { System.out.println(ex.getMessage()); } } valueSet = false; notify(); edgeList.clear(); } }
<script> jQuery(document).ready(function ($) { var options = { $AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false $AutoPlaySteps: 4, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1 $AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000 $PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1 $ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false $SlideDuration: 160, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500 $<API key>: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20 $SlideWidth: 200, //[Optional] Width of every slide in pixels, default value is width of 'slides' container //$SlideHeight: 150, //[Optional] Height of every slide in pixels, default value is height of 'slides' container $SlideSpacing: 3, //[Optional] Space between each slide in pixels, default value is 0 $DisplayPieces: 4, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1 $ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0. $UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc). $PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1 $DragOrientation: 1, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0) $<API key>: { //[Optional] Options to specify and enable navigator or not $Class: $<API key>$, //[Required] Class to create navigator instance $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always $AutoCenter: 0, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0 $Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1 $Lanes: 1, //[Optional] Specify lanes to arrange items, default value is 1 $SpacingX: 0, //[Optional] Horizontal space between each item in pixel, default value is 0 $SpacingY: 0, //[Optional] Vertical space between each item in pixel, default value is 0 $Orientation: 1 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1 }, $<API key>: { $Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance $ChanceToShow: 1, //[Required] 0 Never, 1 Mouse Over, 2 Always $AutoCenter: 2, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0 $Steps: 4 //[Optional] Steps to go for each navigation request, default value is 1 } }; var jssor_slider1 = new $JssorSlider$("slider1_container", options); //responsive code begin //you can remove responsive code if you don't want the slider scales while window resizes function ScaleSlider() { var bodyWidth = document.body.clientWidth; if (bodyWidth) jssor_slider1.$ScaleWidth(Math.min(bodyWidth, 809)); else window.setTimeout(ScaleSlider, 30); } ScaleSlider(); $(window).bind("load", ScaleSlider); $(window).bind("resize", ScaleSlider); $(window).bind("orientationchange", ScaleSlider); //responsive code end }); </script> <!-- Jssor Slider Begin --> <!-- To move inline styles to css file/block, please specify a class name for each element. --> <div id="slider1_container" style="margin:auto;position: relative; top: 0px; left: 0px; width: 809px; height: 150px; overflow: hidden;"> <!-- Loading Screen --> <div u="loading" style="position: absolute; top: 0px; left: 0px;"> <div style="filter: alpha(opacity=70); opacity:0.7; position: absolute; display: block; background-color: #000; top: 0px; left: 0px;width: 100%;height:100%;"> </div> <div style="position: absolute; display: block; background: url(images/loading.gif) no-repeat center center; top: 0px; left: 0px;width: 100%;height:100%;"> </div> </div> <!-- Slides Container --> <div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 809px; height: 150px; overflow: hidden;"> <div><a href="./<API key>/" target="_blank"><img u="image" src="images/chuyen_de_tu_cung.png" width="200px" /></a></div> <div><a href="./bao-quy-dau/" target="_blank"><img u="image" src="images/chuyen_de_bqd.png" width="200px" /></a></div> <div><a href="./chuyen-de-benh-tri/" target="_blank"><img u="image" src="images/chuyen_de_benh_tri.png" width="200px" /></a></div> <div><a href="./<API key>/" target="_blank"><img u="image" src="images/chuyen_de_pha_thai.png" width="200px" /></a></div> <div><a href="./<API key>/" target="_blank"><img u="image" src="images/<API key>.png" width="200px" /></a></div> <div><a href="./bao-quy-dau/" target="_blank"><img u="image" src="images/chuyen_de_bqd.png" width="200px" /></a></div> </div> <!--#region Bullet Navigator Skin Begin --> <style> /* jssor slider bullet navigator skin 03 css */ /* .jssorb03 div (normal) .jssorb03 div:hover (normal mouseover) .jssorb03 .av (active) .jssorb03 .av:hover (active mouseover) .jssorb03 .dn (mousedown) */ .jssorb03 { position: absolute; } .jssorb03 div, .jssorb03 div:hover, .jssorb03 .av { position: absolute; /* size of bullet elment */ width: 21px; height: 21px; text-align: center; line-height: 21px; color: white; font-size: 12px; background: url(images/b03.png) no-repeat; overflow: hidden; cursor: pointer; } .jssorb03 div { background-position: -5px -4px; } .jssorb03 div:hover, .jssorb03 .av:hover { background-position: -35px -4px; } .jssorb03 .av { background-position: -65px -4px; } .jssorb03 .dn, .jssorb03 .dn:hover { background-position: -95px -4px; } </style> <!-- bullet navigator container --> <div u="navigator" class="jssorb03" style="bottom: 4px; right: 6px;"> <!-- bullet navigator item prototype --> <div u="prototype"><div u="numbertemplate"></div></div> </div> <!--#endregion Bullet Navigator Skin End --> <!--#region Arrow Navigator Skin Begin --> <style> /* jssor slider arrow navigator skin 03 css */ /* .jssora03l (normal) .jssora03r (normal) .jssora03l:hover (normal mouseover) .jssora03r:hover (normal mouseover) .jssora03l.jssora03ldn (mousedown) .jssora03r.jssora03rdn (mousedown) */ .jssora03l, .jssora03r { display: block; position: absolute; /* size of arrow element */ width: 55px; height: 55px; cursor: pointer; background: url(images/a03.png) no-repeat; overflow: hidden; } .jssora03l { background-position: -3px -33px; } .jssora03r { background-position: -63px -33px; } .jssora03l:hover { background-position: -123px -33px; } .jssora03r:hover { background-position: -183px -33px; } .jssora03l.jssora03ldn { background-position: -243px -33px; } .jssora03r.jssora03rdn { background-position: -303px -33px; } </style> <!-- Arrow Left --> <span u="arrowleft" class="jssora03l" style="top: 123px; left: 8px;"> </span> <!-- Arrow Right --> <span u="arrowright" class="jssora03r" style="top: 123px; right: 8px;"> </span> </div>
import random import time from Pyro5.api import expose, Daemon, locate_ns @expose class StockMarket(object): def __init__(self, marketname, symbols): self._name = marketname self._symbols = symbols def quotes(self): while True: symbol = random.choice(self.symbols) yield symbol, round(random.uniform(5, 150), 2) time.sleep(random.random()/2.0) @property def name(self): return self._name @property def symbols(self): return self._symbols if __name__ == "__main__": nasdaq = StockMarket("NASDAQ", ["AAPL", "CSCO", "MSFT", "GOOG"]) newyork = StockMarket("NYSE", ["IBM", "HPQ", "BP"]) # for example purposes we will access the daemon and name server ourselves with Daemon() as daemon: nasdaq_uri = daemon.register(nasdaq) newyork_uri = daemon.register(newyork) with locate_ns() as ns: ns.register("example.stockmarket.nasdaq", nasdaq_uri) ns.register("example.stockmarket.newyork", newyork_uri) print("Stockmarkets available.") daemon.requestLoop()
# @Last Modified time: 2018-01-29 14:24:25 module Parameter require_relative '../string/string' # Parameter repository storing the valid parameter of the script. # {#initialize} gets the provided parameters and fills a hash which # grants access on the provided parameters and their arguments class ParameterRepository # @return [Hash] Hash of valid parameters and their values attr_reader :parameters # initialization # @param [Array] argv Array of input parameters # @raise [ArgumentError] if parameters occur after reading the filepath # @raise [ArgumentError] for an invalid combination of script parameters def initialize(argv) @parameters = Hash.new() unflagged_arguments = Array.new() argv.each { |arg| process_argument(arg, unflagged_arguments) } <API key>(unflagged_arguments.size) end private # method to read the given argument and process it depending on its content # @param [String] arg the given argument # @param [Array] unflagged_arguments the argument array # @return [boolean] if the size of the argument array is zero or not def process_argument(arg, unflagged_arguments) case arg when '-h', '--help' then <API key> when '-v', '--version' then @parameters[:version] = true when /-[a-z]|--[a-z]+/ then <API key>(arg) else <API key>(unflagged_arguments.shift, arg) end return (unflagged_arguments.size == 0) end # check if a parameter holds one or more arguments and adds the argument # depending on the check # @param [Symbol] arg_key the symbol referencing a parameter # @param [String] arg the argument from the input array def <API key>(arg_key, arg) if (arg_key != nil) if(@parameters[arg_key] != nil) @parameters[arg_key] << arg else @parameters[arg_key] = arg end else raise ArgumentError, ' Error: invalid combination of parameters.'.red end end # checks if the help parameter was entered with a parameter of if the # general help information is requested def <API key> if(@parameters.keys.last != nil) # help in context to a parameter @parameters[:help] = @parameters.keys.last else # help without parameter => global help @parameters[:help] = true end end # checks if all parameters have been handled correctly # only with -h and -v should be the :file element left # @param [Fixnum] size size of the argument array # @raise [ArgumentError] if parameter combination not valid def <API key>(size) if (size > 0 && !(@parameters[:help] || @parameters[:version])) raise ArgumentError, ' Error: invalid combination of parameters.'.red end end # error message in the case of an invalid argument # @param [String] arg invalid parameter string # @raise [ArgumentError] if an invalid argument is provided def <API key>(arg) raise ArgumentError, " Error: invalid argument: #{arg}".red end end end
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct $_TypeDescriptor$_extraBytes_176 { const void *pVFTable; void *spare; char name[176]; }; END_ATF_NAMESPACE
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebSite.Services { public interface ISmsSender { Task SendSmsAsync(string number, string message); } }
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="layoutclass_pic"><div class="<API key>"><table class="ztable"><tr><th class="ztd1"><b>&nbsp;</b></th><td class="ztd2"></td></tr> <tr><th class="ztd1"><b>&nbsp;</b></th><td class="ztd2"> <a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000000468%22.%26v%3D-1" class="clink" target=_blank></a></font> <font class="dianuan_mark"></font><font size=-2 color=" <div class="Rulediv"><font class="english_word">(1)</font> <font class="dianuan_mark"><font class="dianuan_mark"></font></font></font></div> <div class="Rulediv"><font class="english_word">(2)</font> <font class="english_word"></font><font class="english_word"></font><font class="english_word"></font><font class="english_word">∼</font><font class="english_word"></font><font class="english_word"></font><font class="english_word"></font></font></div> <div class="Rulediv"><font class="english_word">(3)</font> </font><font size=4 ></div><br><font class="dianuan_mark2"></font><br></font> <font class="dianuan_mark"><font class="dianuan_mark"></font></font><br><font class="dianuan_mark"></font></font></td></tr> </td></tr></table></div> <!-- <API key> --><div class="<API key>"></div> <!-- <API key> --></div> <!-- layoutclass_pic --></td></tr></table>
import sys def ruler_algorithm(n1, n2): """ Ruler Algorithm yani Cetvel Algoritmasi. Verilen aralik ikiye bolundugunde her alt parca da devamli olarak ikiye bolunmekte. Alt parcalarin uzunlugu onceden verilen degere erisinceye kadar devam edilir. """ dot = (n1+n2)/2 if abs((n2-n1)) < 2: return print("[%s]" % dot, end=' ') ruler_algorithm(n1, dot) ruler_algorithm(dot, n2) def <API key>(): sys.stdout.write("Ruler Algorithm: ") ruler_algorithm(0,20000) <API key>() # profiling result for 20.000 numbers # profile: python -m profile ruler_algorithm.py """ 147457 func tion calls (114691 primitive calls) in 0.998 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 32767 0.125 0.000 0.125 0.000 :0(abs) 32767 0.125 0.000 0.125 0.000 :0(charmap_encode) 1 0.000 0.000 0.998 0.998 :0(exec) 16383 0.265 0.000 0.484 0.000 :0(print) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 :0(write) 32767 0.094 0.000 0.218 0.000 cp857.py:18(encode) 1 0.000 0.000 0.998 0.998 profile:0(<code object <module> at 0x01E1C2A0, file "ruler_algorithm.py", line 1>) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 0.998 0.998 ruler_algorithm.py:1(<module>) 1 0.000 0.000 0.998 0.998 ruler_algorithm.py:16(ruler_algori thm_main) 32767/1 0.390 0.000 0.998 0.998 ruler_algorithm.py:3(ruler_algorit hm) """
#include "ros/ros.h" #include <termios.h> #include <ecl/threads.hpp> #include <std_msgs/UInt8.h> #include <sstream> bool quit_requested; int key_file_descriptor; struct termios <API key>; ecl::Thread thread; ecl::Mutex key_mutex; char key_getch_data; int key_new; void Key_InputLoop( void ); int main( int argc, char **argv ) { ros::init(argc, argv, "Rover5_key_getch"); ros::NodeHandle n; ros::Publisher key_pub = n.advertise<std_msgs::UInt8>("key_getch", 1000); ros::Rate loop_rate(10); std_msgs::UInt8 key_msg; quit_requested = 0; tcgetattr(key_file_descriptor, &<API key>); key_new = false; thread.start(&Key_InputLoop); while( ros::ok() ) { key_msg.data = key_getch_data; if( key_new == true ) { key_pub.publish(key_msg); key_mutex.lock(); key_new = false; key_mutex.unlock(); } else { //key_msg.data = 0; //key_pub.publish(key_msg); } ros::spinOnce(); loop_rate.sleep(); } key_msg.data = 0; key_pub.publish(key_msg); quit_requested = true; thread.cancel(); thread.join(); tcsetattr(key_file_descriptor, TCSANOW, &<API key>); } void Key_InputLoop( void ) { struct termios raw; memcpy(&raw, &<API key>, sizeof(struct termios)); raw.c_lflag &= ~(ICANON | ECHO); // Setting a new line, then end of file raw.c_cc[VEOL] = 1; raw.c_cc[VEOF] = 2; tcsetattr(key_file_descriptor, TCSANOW, &raw); char c; while (!quit_requested) { if (read(key_file_descriptor, &c, 1) < 0) { perror("read char failed():"); exit(-1); } else { ROS_INFO("Key Input : [%x]", c); key_getch_data = c; key_mutex.lock(); key_new = true; key_mutex.unlock(); } } }
<?php App::uses('Edexml', 'Edexml.Model'); class TestEdexml extends Edexml { public function schoolClasses($schoolClasses) { $this->_schoolClasses = $schoolClasses; } /** * Test double of `parent::_convertKey`. * */ public function convertKey($key) { return $this->_convertKey($key); } /** * Test double of `parent::_convertNames`. * */ public function convertNames($user) { return $this->_convertNames($user); } /** * Test double of `parent::_convertSchool`. * */ public function convertSchool($school) { return $this->_convertSchool($school); } /** * Test double of `parent::_convertSchoolClass`. * */ public function convertSchoolClass($schoolClass) { return $this->_convertSchoolClass($schoolClass); } /** * Test double of `parent::<API key>`. * */ public function <API key>($schoolClasses) { return $this-><API key>($schoolClasses); } /** * Test double of `parent::_convertStudent`. * */ public function convertStudent($data) { return $this->_convertStudent($data); } /** * Test double of `parent::_convertTeacher`. * */ public function convertTeacher($data) { return $this->_convertTeacher($data); } /** * Test double of `parent::_parse`. * */ public function parse($filename) { return $this->_parse($filename); } } /** * Edexml Test. * * @property TestEdexml $Edexml */ class EdexmlTest extends CakeTestCase { /** * Fixtures. * * @var array */ public $fixtures = []; /** * setUp method. * * @return void */ public function setUp() { parent::setUp(); $this->Edexml = ClassRegistry::init('TestEdexml', true); } /** * tearDown method. * * @return void */ public function tearDown() { unset($this->Edexml); parent::tearDown(); } /** * Tests `convertKey`. * * @return void */ public function testConvertKey() { $this->assertNull($this->Edexml->convertKey('#001')); $this->assertEquals('1', $this->Edexml->convertKey('1')); $this->assertEquals('key', $this->Edexml->convertKey('key')); } /** * Tests `convertNames`. * * @return void */ public function testConvertNames() { $data = [ 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam' ]; $expected = [ 'last_name' => $data['achternaam'], 'first_name' => $data['roepnaam'], ]; $this->assertEquals($expected, $this->Edexml->convertNames($data)); $data = [ 'achternaam' => 'Achternaam', 'voorvoegsel' => 'Voorvoegsel', 'roepnaam' => 'Roepnaam' ]; $expected = [ 'last_name' => $data['voorvoegsel'] . ' ' . $data['achternaam'], 'first_name' => $data['roepnaam'], ]; $this->assertEquals($expected, $this->Edexml->convertNames($data)); } /** * Tests `convertSchool`. * * @return void */ public function testConvertSchool() { $data = [ 'schoolkey' => 'schoolkey', ]; $expected = [ 'key' => $data['schoolkey'] ]; $this->assertEquals($expected, $this->Edexml->convertSchool($data)); $data = [ 'schoolkey' => '#001', ]; $expected = [ 'key' => null ]; $this->assertEquals($expected, $this->Edexml->convertSchool($data)); $data = []; $expected = [ 'key' => null ]; $this->assertEquals($expected, $this->Edexml->convertSchool($data)); } /** * Tests `convertSchoolClass`. * * @return void */ public function <API key>() { $data = [ '@key' => 'key', 'naam' => 'naam', 'jaargroep' => '0' ]; $expected = [ 'key' => $data['@key'], 'name' => 'naam', 'grade' => '1' ]; $this->assertEquals($expected, $this->Edexml->convertSchoolClass($data)); } /** * Tests `convertSchoolClass`. * * Yeargroup S. * * @return void */ public function <API key>() { $data = [ '@key' => 'key', 'naam' => 'naam', 'jaargroep' => 'S' ]; $expected = [ 'key' => $data['@key'], 'name' => 'naam', 'grade' => '19' ]; $this->assertEquals($expected, $this->Edexml->convertSchoolClass($data)); } /** * Tests `<API key>`. * * @return void */ public function <API key>() { $data = [ 0 => [ '@key' => 'key', 'naam' => 'naam', 'jaargroep' => '0' ] ]; $expected = [ 'key' => [ 'key' => 'key', 'name' => 'naam', 'grade' => '1' ] ]; $this->assertEquals($expected, $this->Edexml-><API key>($data)); } /** * Tests `convertStudent`. * * @return void */ public function testConvertStudent() { $data = [ '@key' => 'key', 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'geboortedatum' => '2005-07-19', 'geslacht' => '0' ]; $expected = [ 'key' => 'key', 'last_name' => 'Achternaam', 'first_name' => 'Roepnaam', 'date_of_birth' => '2005-07-19', 'gender' => null, 'grade' => null, 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertStudent($data)); $data = [ '@key' => 'key', '@eckid' => 'https://id.school/<API key>!@ 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'geboortedatum' => '2005-07-19', 'geslacht' => '0' ]; $expected = [ 'key' => 'key', 'eckid' => 'https://id.school/<API key>!@ 'last_name' => 'Achternaam', 'first_name' => 'Roepnaam', 'date_of_birth' => '2005-07-19', 'gender' => null, 'grade' => null, 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertStudent($data)); $data = [ '@key' => 'key', 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'geboortedatum' => '2005-07-19', 'geslacht' => '0', 'groep' => [ '@key' => 'key' ] ]; $expected = [ 'key' => 'key', 'last_name' => 'Achternaam', 'first_name' => 'Roepnaam', 'date_of_birth' => '2005-07-19', 'gender' => null, 'grade' => 10, 'SchoolClass' => [ 'key' => [ 'grade' => 10 ] ] ]; $schoolClasses = [ 'key' => [ 'grade' => 10 ] ]; $this->Edexml->schoolClasses($schoolClasses); $this->assertEquals($expected, $this->Edexml->convertStudent($data)); $data = [ 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'geslacht' => '1' ]; $expected = [ 'key' => null, 'first_name' => 'Roepnaam', 'last_name' => 'Achternaam', 'gender' => 'm', 'date_of_birth' => null, 'grade' => null, 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertStudent($data)); $data = [ 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'geslacht' => '2' ]; $actual = $this->Edexml->convertStudent($data); $this->assertEquals('Achternaam', $actual['last_name']); $this->assertEquals('f', $actual['gender']); $data = [ 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'geslacht' => '9' ]; $actual = $this->Edexml->convertStudent($data); $this->assertEquals('Achternaam', $actual['last_name']); $this->assertNull($actual['gender']); $data = [ 'achternaam' => 'Achternaam', 'voorvoegsel' => 'Voorvoegsel', 'roepnaam' => 'Roepnaam' ]; $actual = $this->Edexml->convertStudent($data); $this->assertEquals('Voorvoegsel Achternaam', $actual['last_name']); $this->assertEquals('Roepnaam', $actual['first_name']); $data = [ 'achternaam' => 'Achternaam', 'voorletters-1' => 'KLM', ]; $actual = $this->Edexml->convertStudent($data); $this->assertEquals('KLM', $actual['first_name']); $data = [ 'achternaam' => 'Achternaam', 'voornamen' => 'Voornaam1 Voornaam2', ]; $actual = $this->Edexml->convertStudent($data); $this->assertEquals('Voornaam1 Voornaam2', $actual['first_name']); $data = [ 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'voornamen' => 'Voornaam1 Voornaam2', 'voorletters-1' => 'KLM', ]; $actual = $this->Edexml->convertStudent($data); $this->assertEquals('Roepnaam', $actual['first_name']); // Check dummy key for example #001 // TODO: what to do when there are no identifiers? $data = [ '@key' => '#001', 'achternaam' => 'Achternaam', 'voorvoegsel' => 'Voorvoegsel', 'roepnaam' => 'Roepnaam' ]; $actual = $this->Edexml->convertStudent($data); $this->assertNull($actual['key']); } /** * Tests `convertTeacher`. * * @return void */ public function testConvertTeacher() { $data = [ '@key' => 'key', 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', ]; $expected = [ 'key' => 'key', 'last_name' => 'Achternaam', 'first_name' => 'Roepnaam', 'date_of_birth' => null, 'gender' => null, 'grade' => null, 'email_address' => null, 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertTeacher($data)); $data = [ '@key' => 'key', '@eckid' => 'https://id.school/<API key>!@ 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', ]; $expected = [ 'key' => 'key', 'eckid' => 'https://id.school/<API key>!@ 'last_name' => 'Achternaam', 'first_name' => 'Roepnaam', 'date_of_birth' => null, 'gender' => null, 'grade' => null, 'email_address' => null, 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertTeacher($data)); $data = [ '@key' => 'key', 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'emailadres' => 'roepnaam@achternaam.com', ]; $expected = [ 'key' => 'key', 'last_name' => 'Achternaam', 'first_name' => 'Roepnaam', 'date_of_birth' => null, 'gender' => null, 'grade' => null, 'email_address' => 'roepnaam@achternaam.com', 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertTeacher($data)); $data = [ '@key' => 'key', 'achternaam' => 'Achternaam', 'voorletters-1' => 'KLM', 'emailadres' => 'roepnaam@achternaam.com', ]; $expected = [ 'key' => 'key', 'last_name' => 'Achternaam', 'first_name' => 'KLM', 'date_of_birth' => null, 'gender' => null, 'grade' => null, 'email_address' => 'roepnaam@achternaam.com', 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertTeacher($data)); $data = [ '@key' => 'key', 'achternaam' => 'Achternaam', 'voornamen' => 'Roepnaam1 Roepnaam2', 'emailadres' => 'roepnaam@achternaam.com', ]; $expected = [ 'key' => 'key', 'last_name' => 'Achternaam', 'first_name' => 'Roepnaam1 Roepnaam2', 'date_of_birth' => null, 'gender' => null, 'grade' => null, 'email_address' => 'roepnaam@achternaam.com', 'SchoolClass' => [] ]; $this->assertEquals($expected, $this->Edexml->convertTeacher($data)); } /** * Tests `parseToArray`. * * @return void */ public function testParseToArray() { $filename = CakePlugin::path('Edexml') . 'Test' . DS . 'File' . DS . 'EDEXML-1.0.3' . DS . 'sample-invalid.xml'; $this->assertFalse($this->Edexml->parseToArray($filename)); $filename = CakePlugin::path('Edexml') . 'Test' . DS . 'File' . DS . 'EDEXML-1.0.3' . DS . 'sample.xml'; $data = $this->Edexml->parseToArray($filename); $this->assertTrue((bool)$data); $actual = $this->Edexml->convert($data); $this->assertTrue((bool)$actual); $this->assertEquals(count($data['EDEX']['leerlingen']['leerling']), count($actual['Student'])); $this->assertEquals(count($data['EDEX']['groepen']['groep']), count($actual['SchoolClass'])); $this->assertEquals(count($data['EDEX']['leerkrachten']['leerkracht']), count($actual['Teacher'])); } /** * Tests `parseToArray`. * * Edex 2.0. * * @return void */ public function <API key>() { $filename = CakePlugin::path('Edexml') . 'Test' . DS . 'File' . DS . 'EDEXML-2.0' . DS . 'EDEXML.Voorbeeld.2.0.xml'; $data = $this->Edexml->parseToArray($filename); $this->assertTrue((bool)$data); $actual = $this->Edexml->convert($data); $this->assertTrue((bool)$actual); } /** * Tests `parseToArray`. * * Edex 2.0. * * @return void */ public function <API key>() { $filename = CakePlugin::path('Edexml') . 'Test' . DS . 'File' . DS . 'EDEXML-2.0' . DS . 'EDEXML.Voorbeeld.2.0-Vla.xml'; $data = $this->Edexml->parseToArray($filename); $this->assertTrue((bool)$data); $actual = $this->Edexml->convert($data); $this->assertTrue((bool)$actual); } /** * Tests `parseToArray`. * * Edex 2.1. * * @return void */ public function <API key>() { $filename = CakePlugin::path('Edexml') . 'Test' . DS . 'File' . DS . 'EDEXML-2.1' . DS . 'EDEXML.Voorbeeld.2.1.xml'; $data = $this->Edexml->parseToArray($filename); $this->assertTrue((bool)$data); $actual = $this->Edexml->convert($data); $this->assertTrue((bool)$actual); } /** * Tests `parseToArray`. * * Edex 2.1. * * @return void */ public function <API key>() { $filename = CakePlugin::path('Edexml') . 'Test' . DS . 'File' . DS . 'EDEXML-2.1' . DS . 'EDEXML.Voorbeeld.2.1-Vla.xml'; $data = $this->Edexml->parseToArray($filename); $this->assertTrue((bool)$data); $actual = $this->Edexml->convert($data); $this->assertTrue((bool)$actual); } /** * Tests `convert`. * * @return void */ public function <API key>() { $data = [ 'EDEX' => [ 'school' => [ 'schooljaar' => '2012-2013', 'brincode' => '99XX', 'dependancecode' => '99', 'schoolkey' => '99999', 'aanmaakdatum' => '2013-03-27T12:43:06', 'auteur' => 'Cito LeerlingVolgSysteem versie 4.6', 'xsdversie' => '1.03' ], 'groepen' => [ 'groep' => [ '@key' => '49', 'naam' => '1A', 'jaargroep' => '1', 'mutatiedatum' => '2005-08-29T22:19:18' ] ], 'leerlingen' => [ 'leerling' => [ '@key' => '3580', 'achternaam' => 'Achternaam', 'voorvoegsel' => 'v. d.', 'roepnaam' => 'Roepnaam', 'geboortedatum' => '2009-08-07', 'geslacht' => '2', 'jaargroep' => '4', 'etniciteit' => '9', 'land' => '?', 'land_vader' => '?', 'land_moeder' => '?', 'gewicht_nieuw' => '?', 'gewicht' => '?', 'mutatiedatum' => '2011-01-24T15:33:29' ] ], 'leerkrachten' => [ 'leerkracht' => [ '@key' => '75', 'achternaam' => 'Achternaam', 'roepnaam' => 'Roepnaam', 'groepen' => [ 'groep' => [ '@key' => '49' ] ], 'mutatiedatum' => '2004-02-07T14:03:18' ] ], '@xsi:<API key>' => 'EDEXML.structuur.xsd' ] ]; $actual = $this->Edexml->convert($data); $this->assertTrue(Hash::numeric(array_keys($actual['SchoolClass']))); $this->assertTrue(Hash::numeric(array_keys($actual['Student']))); $this->assertTrue(Hash::numeric(array_keys($actual['Teacher']))); } }
#include <ctime> #include "../net/client.h" #include "../util/util.h" #include "account.h" namespace twitpp { namespace oauth { account::account(const std::string& ck, const std::string& cs, const std::string& ot, const std::string& os) : consumer_key_(ck), consumer_secret_(cs), oauth_token_(ot), oauth_token_secret_(os) {} int account::get_authorize_url() { auto auth_param = make_auth_param(); // generate signature_base std::string signature_base("POST&" + util::url_encode("https://api.twitter.com/oauth/request_token") + "&" + util::url_encode(make_query_str(auth_param))); // generate signing key std::string signing_key(util::url_encode(consumer_secret_) + "&"); // set oauth_signature auth_param["oauth_signature"] = util::hmac_sha1_encode(signing_key, signature_base); // post try { net::client client(net::method::POST, "https://api.twitter.com/oauth/request_token", make_auth_header(auth_param), ""); client.run(); auto token = util::parse_query_str(client.response().body); if (!token.count("oauth_token") || !token.count("oauth_token_secret")) { authorize_url_.clear(); return -1; } oauth_token_ = token["oauth_token"]; oauth_token_secret_ = token["oauth_token_secret"]; authorize_url_ = "https://api.twitter.com/oauth/authorize\?oauth_token=" + oauth_token_; return 0; } catch (std::exception& e) { throw; } } int account::get_oauth_token(const std::string& pin) { auto auth_param = make_auth_param(); auth_param["oauth_verifier"] = pin; // generate signature_base std::string signature_base("POST&" + util::url_encode("https://api.twitter.com/oauth/access_token") + "&" + util::url_encode(make_query_str(auth_param))); // generate signing key std::string signing_key(util::url_encode(consumer_secret_) + "&" + util::url_encode(oauth_token_secret_)); // set oauth_signature auth_param["oauth_signature"] = util::hmac_sha1_encode(signing_key, signature_base); // post try { net::client client(net::method::POST, "https://api.twitter.com/oauth/access_token", make_auth_header(auth_param), ""); client.run(); auto token = util::parse_query_str(client.response().body); if (!token.count("oauth_token") || !token.count("oauth_token_secret")) { oauth_token_.clear(); oauth_token_secret_.clear(); return -1; } oauth_token_ = token["oauth_token"]; oauth_token_secret_ = token["oauth_token_secret"]; return 0; } catch (std::exception& e) { throw; } } std::string account::authorize_url() { return authorize_url_; } std::string account::consumer_key() const { return consumer_key_; } std::string account::consumer_secret() const { return consumer_secret_; } std::string account::oauth_token() const { return oauth_token_; } std::string account::oauth_token_secret() const { return oauth_token_secret_; } std::string account::make_query_str(const std::map<std::string, std::string>& param) { std::string s; for (const auto& p : param) { s.append(p.first + "=" + util::url_encode(p.second) + "&"); } return s.erase(s.length() - 1); } std::string account::make_auth_header(const std::map<std::string, std::string>& param) { std::string s("Authorization: OAuth "); for (const auto& p : param) { s.append(p.first + "=\"" + util::url_encode(p.second) + "\", "); } return s.erase(s.length() - 2); } inline std::map<std::string, std::string> account::make_auth_param() { std::map<std::string, std::string> auth_param{ {"oauth_callback" , "oob"}, {"oauth_consumer_key" , consumer_key_}, {"oauth_nonce" , util::random_str(32)}, {"o<API key> , "HMAC-SHA1"}, {"oauth_timestamp" , std::to_string(std::time(0))}, {"oauth_version" , "1.0"} }; if (!oauth_token_.empty()) { auth_param["oauth_token"] = oauth_token_; } return auth_param; } } // namespace oauth } // namespace twitpp
import {PutIoHelper} from '../helpers/PutIoHelper'; export class Events extends PutIoHelper { public getEventsList(): Promise<string> { return this.requestData('GET', 'events/list', []); } }
import { Config } from '@pnpm/config' import defaultReporter from '@pnpm/default-reporter' import { LogLevel, streamParser, writeToConsole } from '@pnpm/logger' import silentReporter from './silentReporter' export type ReporterType = 'default' | 'ndjson' | 'silent' | 'append-only' export default ( reporterType: ReporterType, opts: { cmd: string | null config: Config } ) => { switch (reporterType) { case 'default': defaultReporter({ useStderr: opts.config.useStderr, context: { argv: opts.cmd ? [opts.cmd] : [], config: opts.config, }, reportingOptions: { appendOnly: false, logLevel: opts.config.loglevel as LogLevel, <API key>: opts.config.stream, throttleProgress: 200, }, streamParser, }) return case 'append-only': defaultReporter({ useStderr: opts.config.useStderr, context: { argv: opts.cmd ? [opts.cmd] : [], config: opts.config, }, reportingOptions: { appendOnly: true, logLevel: opts.config.loglevel as LogLevel, throttleProgress: 1000, }, streamParser, }) return case 'ndjson': writeToConsole() return case 'silent': silentReporter(streamParser) } }
module Resque module Plugins module RestashLogger # Executed on the Resque worker def <API key>(*args) @resque_job_uuid = SecureRandom.uuid @job_start_time = Time.now log 'Executing', args, :debug end def <API key>(*args) @job_end_time = Time.now log 'Finished', args, :debug end def <API key>(*args) @job_end_time = Time.now log 'Failed', args, :error end # Executed on the enqueueing instance def <API key>(*args) log 'Enqueued', args, :debug end def <API key>(*args) log 'Scheduled', args, :debug end def log(log_message, args, severity = :info) extra_data = args.is_a?(Array) ? args.last : args log_arguments = { log_message: log_message, extra_data: extra_data, class: self.name, log_tag: :resque_hooks } if args.is_a?(Array) && args.first.is_a?(Exception) exception = args.first log_arguments[:exception] = { class: exception.class.to_s, message: exception.message.to_s, backtrace: exception.backtrace } end log_arguments[:exec_run_time] = @job_end_time - @job_start_time if @job_start_time.present? && @job_end_time.present? log_arguments[:resque_job_uuid] = @resque_job_uuid if @resque_job_uuid.present? Rails.logger.send(severity, log_arguments) end end end end
function $img(src) { var m = new Image(); m.src = src; return m; } if (top == window) { qwp.loadingImg = $img('img/loading_small.gif'); } if (typeof String.prototype.format != 'function') { String.prototype.format = function() { var s = this; if (arguments.length === 0) return s; if ($.isPlainObject(arguments[0])) { for (var p in arguments[0]) { s = s.replace(new RegExp("\\{" + p + "\\}", "g"), arguments[0][p]); } return s; } for (var i = 0, cnt = arguments.length; i < cnt; ++i) { s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]); } return s; }; } if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function(str) { return this.slice(0, str.length) == str; }; } if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function (suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } if (typeof String.prototype.trim != 'function') { String.prototype.trim = function() { return this.replace(/(^\s+)|(\s+$)/g, ""); }; } if (typeof String.prototype.ltrim != 'function') { String.prototype.ltrim = function() { return this.replace(/(^\s+)/g, ""); }; } if (typeof String.prototype.rtrim != 'function') { String.prototype.rtrim = function() { return this.replace(/(\s+$)/g, ""); }; } if (typeof Date.prototype.toLocalTime != 'function') { Date.prototype.toLocalTime = function(fmt) { var d = this; var o = { "M+" : d.getMonth()+1, "d+" : d.getDate(), "h+" : d.getHours(), "m+" : d.getMinutes(), "s+" : d.getSeconds(), "q+" : Math.floor((d.getMonth()+3)/3), "S" : d.getMilliseconds() }; if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (d.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o) { if(new RegExp("("+ k +")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); } return fmt; } } // return function name if it's global function qwp.$fn = function(fn) { var t = $.type(fn); if (t == 'string') return fn; if (t != 'function') return false; var s = fn.toString().substr(8); t = s.indexOf('{'); if (t == -1) return false; s = s.substr(0, t - 1).trim(); t = s.indexOf('('); if (t != -1) s = s.substr(0, t); if (!s.length || s == 'anonymous') return false; return window[s] ? s : false; }; function $noop() {} function $false() {return false;} function $L(txt) { if (_LANG && _LANG[txt]) txt = _LANG[txt]; if (arguments.length == 1) return txt; for (var i = 1, cnt = arguments.length; i < cnt; ++i) { var idx = i - 1; txt = txt.replace(new RegExp("\\{" + idx + "\\}", "gm"), arguments[i]); } return txt; } $h = {}; (function($, $h){ $h.anonymousIndex = 1; $h.anon = function(fn, prefix) { if (!prefix) prefix = 'anon'; prefix = 'qwp_' + prefix + '_' + $h.anonymousIndex; ++$h.anonymousIndex; window[prefix] = fn; return prefix; }; $h.attr = function(attrs, sep, eq, vtag) { if (!attrs) { return ''; } sep = sep || ' '; eq = eq || '='; if ($.type(vtag) == 'undefined') vtag = '"'; var at = ' ', preSep = ''; for (var k in attrs) { var v = attrs[k]; if (v === true) { at += preSep + k; continue; } var t = $.type(v), d; if (t == 'function') { if (k != 'onclick') { continue; } } if (t == 'object') { var t1 = ';', t2 = ':', t3 = '', vt = {}; $.extend(vt, v); if (vt._sep) { t1 = vt._sep; delete vt._sep; } if (vt._eq) { t2 = vt._eq; delete vt._eq; } if (vt._vtag) { t3 = vt._vtag; delete vt._vtag; } d = $h.attr(vt, t1, t2, t3); } else { if (k == 'onclick') { d = qwp.$fn(v); if (d) { if (d.indexOf('(') == -1) d += '()'; } else { d = $h.anon(v) + '()'; } } else { d = '' + v; } } at += preSep + k + eq + vtag + d + vtag; preSep = sep; } return at; }; $h.ele = function(tag, txt, attrs) { return txt ? "<" + tag + $h.attr(attrs) + ">" + txt + "</" + tag + ">" : "<" + tag + $h.attr(attrs) + " />"; }; $h.tagStart = function(tag, attrs) { return "<" + tag + $h.attr(attrs) + ">"; }; function fn1(tag) { return function(txt, attrs) { return $h.ele(tag, txt, attrs); } } function fn2(tag) { return function(attrs) { return $h.ele(tag, false, attrs); } } function fn3(tag, type) { return function(attrs) { attrs = attrs || {}; attrs.type = type; return $h.ele(tag, false, attrs); } } function fn4(tag) { return function(attrs) { return $h.tagStart(tag, attrs); } } var tag, htmlElements = ['p', 'h1', 'h2', 'h3', 'h4', 'ul', 'li', 'b', 'div', 'option', 'select', 'thead', 'label', 'span', 'em', 'table', 'tbody', 'th', 'tr', 'td', 'pre', 'code', 'option', 'i', 'a', 'nav', 'textarea', 'button', 'form', 'colgroup']; for (var i = 0, cnt = htmlElements.length; i < cnt; ++i) { tag = htmlElements[i]; $h[tag] = fn1(tag) } htmlElements = ['img', 'br', 'input', 'col']; for (i = 0, cnt = htmlElements.length; i < cnt; ++i) { tag = htmlElements[i]; $h[tag] = fn2(tag); } htmlElements = ['radio', 'checkbox', 'text', 'submit', 'hidden', 'reset', 'file', 'password']; for (i = 0, cnt = htmlElements.length; i < cnt; ++i) { tag = htmlElements[i]; $h[tag] = fn3('input', tag); } htmlElements = ['table']; for (i = 0, cnt = htmlElements.length; i < cnt; ++i) { tag = htmlElements[i]; $h[tag + 'Start'] = fn4(tag); $h[tag + 'End'] = '</' + htmlElements[i] + '>'; } $h.options = function (arr) { var h = ''; for (var i = 0, cnt = arr.length; i < cnt; ++i) { h += $h.option(arr[i][0], {value: arr[i][1]}); } return h; }; $h.imgBase64Src = function (data, type) { if (!type) type = 'jpeg'; return 'data:image/' + type + ';base64,' + data; }; $h.imgBase64 = function (data, type) { if (!type) type = 'jpeg'; return $h.img({src:'data:image/' + type + ';base64,' + data}); }; $h.spacer = function(attr) { var opt = {border:'0', src:'img/spacer.gif', height:'1px'}; $.extend(opt, attr); return $h.img(opt); }; $.extend(qwp, { _:'&nbsp', br:'<br>', jsvoid: 'javascript:void(0)', $: function(s, p) { if (qwp.isString(s)) { if (p) return p.find(s); else return $(s); } return s; }, isString: function(v) { return $.type(v) == 'string'; }, isUndefined: function(v) { return $.type(v) == 'undefined'; }, toJson: function(d, v) { var j = false; if (v) j = v; if (d) { try { j = $.parseJSON(d); } catch (e) {} } return j; }, convertLineBreak: function(t) { return t.replaceAll('\r\n', '\r').replaceAll('\r', '<br>').replaceAll('\n', '<br>'); }, in: function(v, arr) { if (!arr) return false; for (var i = 0, cnt = arr.length; i < cnt; ++i) { if (v == arr[i]) return true; } return false; }, fn: function(f) { if ($.isFunction(f)) return f; if (qwp.isString(f)) return window[f]; return false; }, id: function(id) { return ' }, cls: function(cls) { return '.' + cls; }, to: function(url, isTopOrP, p) { if (!url) url = qwp.uri.curUrl; var isTop = false; if (isTopOrP === true) isTop = true; else if (isTopOrP) p = isTopOrP; if (p) { if (url.indexOf('?') == -1) url += '?'; else url += '&'; if (qwp.isString(p)) url += p; else url += $.param(p); } (isTop ? top : window).location = url; }, reload: function() { window.location.reload(); }, once: function(f, timeout) { return setTimeout(f, timeout); }, camelCase: function(s) { if (!s) return s; return s.substr(0, 1).toUpperCase() + s.substr(1); }, isCorrectExt: function(fileName, exts) { fileName = fileName.toLowerCase(); if (!$.isArray(exts)) exts = exts.split(','); for (var i = 0, cnt = exts.length; i < cnt; ++i) { if (fileName.endsWith('.' + exts[i])) { return true; } } return false; }, createOpsHandler: function(actionHandler, option) { var opt = {}, fn = $noop, formParams = null; if (actionHandler) { var ft = $.type(actionHandler); if (ft == 'string') { fn = window[actionHandler]; } else if (ft == 'function') { fn = actionHandler; } } if (option.form) { formParams = $(option.form).data('qwp-params'); delete option.form; } if (option) $.extend(opt, option); return function(res) { if (opt.confirmDialog) $('#' + opt.confirmDialog).data('clicked', false); if (res.ret && opt.formParentDialog) $('#' + opt.formParentDialog).modal('hide'); var data = res.data || {}, timeout = res.ret ? 3 : 5; if (opt.<API key>) timeout = opt.<API key>; if (!res.ret && data.toLogin) { qwp.notice(res.msg, { timeout: timeout, type: 'error', image: 'img/loading_small.gif', fn: function () { qwp.to(data.toLogin, true); } }); return; } if (opt.quiet) { fn(res, data, formParams); if (res.ret && opt.reload) qwp.reload(); return; } if (res.ret && opt.reload) { fn(res, data, formParams); qwp.notice(res.msg + "<br />" + $L("Prepare to refresh page..."), { timeout: timeout, type: res.msg_type, image: 'img/loading_small.gif', fn: function () {qwp.reload();} }); return; } fn(res, data, formParams); if (res.ret && (data.to || data.topTo)) { qwp.notice(res.msg + "<br />" + $L("Prepare to relocation..."), { timeout: timeout, type: res.msg_type, image: 'img/loading_small.gif', fn: function () { if (data.to) qwp.to(data.to); else if (data.topTo) qwp.to(data.topTo, true); } }); return; } if (res.msg && res.msg.length > 0) { qwp.notice(res.msg, { timeout: timeout, type: res.msg_type }); } else { qwp.removeNotice(); } } }, ajax: function(options) { if (!options.quiet) { qwp.notice(options.text || $L('Operation is in processing, please wait...'),{ timeout:4, image:'img/loading_small.gif' }); } var fn = qwp.createOpsHandler(options.fn, options); $.ajax({ url: options.url, data: options.params ? options.params : "", type: options.type, dataType: options.dataType || 'json', async:true, success: fn, timeout: options.timeout || 60000, error: function() { fn({ret:false, msg: $L('Operation failed')}); } }); }, post: function(options) { options.type = "POST"; qwp.ajax(options); }, get: function(options) { options.type = "GET"; qwp.ajax(options); }, copy: function(dst, src, attr) { if (!attr) { $.extend(dst, src); return; } if (qwp.isString(attr)) attr = [attr]; for (var i = 0, cnt = attr.length; i < cnt; ++i) { var k = attr[i]; if (src[k]) dst[k] = src[k]; } }, copyWhenEmpty: function(dst, src, attr) { if (qwp.isString(attr)) attr = [attr]; for (var i = 0, cnt = attr.length; i < cnt; ++i) { var k = attr[i]; if (!dst[k] && src[k]) dst[k] = src[k]; } }, isValidInput: function(v, ruleName) { if (!qwp.page.inputRules || !qwp.page.inputRules[ruleName]) return false; var re, r = qwp.page.inputRules[ruleName]; if (qwp.isString(r)) { re = new RegExp(r); return re.test(v); } else if (qwp.isString(r[0])) { re = new RegExp(r[0], r[1]); return re.test(v); } var sub = r[0]; for (var i = 0, cnt = sub.length; i < cnt; ++i) { if (r[1][i]) { re = new RegExp(sub[i], r[1][i]); } else { re = new RegExp(sub[i]); } if (!re.test(v)) { return false; } } return true; }, _lastNotice: false, //title, notice, timeout, type, position, image, callbacks, css notice: function(notice, opt) { var t = parseInt((new Date()).getTime() / 1000); if (qwp._lastNotice && qwp._lastNotice.txt == notice && (qwp._lastNotice.t + 3) > t) { qwp._lastNotice.t = t; return; } qwp.removeNotice(); var option = {}; if (qwp.isString(opt)) opt = {type: opt}; if (opt) $.extend(option, opt); var title = option.title || $L("Operation notification"); var timeout = option.timeout || ((option.type && (option.type == 'error' || option.type == 'warning')) ? 6 : 3); timeout *= 1000; if (option.fn) qwp.once(option.fn, timeout); toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: timeout }; var type = option.type || 'info'; qwp._lastNotice = {id:toastr[type](notice, title), t:t, txt: notice}; return qwp._lastNotice; }, topNotice: function (notice, opt) { (parent ? parent.qwp : qwp).notice(notice, opt); }, removeNotice: function() { if (qwp._lastNotice) { toastr.clear(qwp._lastNotice.id); qwp._lastGritter = false; } }, parseProps: function(p) { var o = {}; if (!p || p.length === 0) return o; p = p.split('|'); for (var i = 0, cnt = p.length; i < cnt; ++i) { var a = p[i]; var d = a.indexOf('='); if (d == -1) continue; o[a.substr(0, d)] = a.substr(d + 1); } return o; }, sortData: function (option, data, sortf, sort, fn) { if (!sortf) sortf = option.sortf; if (!sortf) return; if (!sort) sort = option.sort; if (!sort) sort = 'desc'; sort = sort == 'asc'; data.data = data.data.sort($.isFunction(fn) ? fn : function (a, b) { if (sort) { if (a[sortf] > b[sortf]) return 1; else if (a[sortf] == b[sortf]) return 0; return -1; } if (a[sortf] > b[sortf]) return -1; else if (a[sortf] == b[sortf]) return 0; return 1; }); } }); qwp.ui = { defaultIcon: 'glyphicon', input: { number: function(s, props, parent, params) { s = qwp.$(s, parent); s.unbind('blur').unbind('keypress'); if (props.enter) s.unbind('keyup'); if (props.disablePaste) s.unbind('paste').on('paste', $false); s.keypress(function(e){ if (e.keyCode < 48 || e.keyCode > 57) return false; }); if (props.enter) { s.keyup(function(e){ if (e.keyCode == 13) { if (window[props.enter]) window[props.enter](e.delegateTarget, params); else eval(props.enter); } }); } s.blur(function(e){ var o = $(e.delegateTarget); var isDefinedValue = typeof(props.defaultValue) !== 'undefined', v = o.val(), isValid; if (v.length === 0) { if (isDefinedValue) { o.val(props.defaultValue); o.trigger('change', e); } return; } isValid = /^\d+$/.test(v); if (isValid && props.regExp) { var re = new RegExp(props.regExp); isValid = re.test(v); } if (!isValid) { if (isDefinedValue) o.val(props.defaultValue); else o.val(''); o.trigger('change', e); return; } v = parseInt(v); if (props.minValue) { if (v < parseInt(props.minValue)) { o.val(props.minValue); o.trigger('change', e); return; } } if (props.maxValue) { if (v > parseInt(props.maxValue)) { o.val(props.maxValue); o.trigger('change', e); } } }); return s; }, createUIComponents: function(p) { var t; if (p) t = p.find('input[qwp=number]'); else t = $('input[qwp=number]'); t.each(function(i, o){ o = $(o); var props = qwp.parseProps(o.attr('props')); qwp.ui.input.number(o, props, p); }); } }, icon: function(cls, full) { cls = qwp.ui.defaultIcon + '-' + cls; return full ? qwp.ui.defaultIcon + ' ' + cls : cls; }, init: function() { qwp.ui._createFns(); }, _createFns: function() { if (qwp.ui._inited) return; qwp.ui._inited = true; var e4 = ['padding', 'margin']; for (var i = 0, cnt = e4.length; i < cnt; ++i) { qwp.ui._createFn4(e4[i]); } qwp.ui._createFn4('border', 'width'); }, _createFn4: function(n, suffix) { var inside = ''; if (suffix) inside = '-' + suffix; qwp.ui[n] = function(o) { if (qwp.isString(o)) o = $(o); return { left: parseInt(o.css(n + '-left' + inside)), right: parseInt(o.css(n + '-right' + inside)), top: parseInt(o.css(n + '-top' + inside)), bottom: parseInt(o.css(n + '-bottom' + inside)) }; }; qwp.ui['set' + qwp.camelCase(n)] = function(o, v) { if (qwp.isString(o)) o = $(o); o.css(n, v); }; var e4 = ['left', 'right', 'top', 'bottom']; for (var i = 0, cnt = e4.length; i < cnt; ++i) { qwp.ui._createFn(n, e4[i], suffix); } qwp.ui._createFn2(n, e4[0], e4[1], suffix); qwp.ui._createFn2(n, e4[2], e4[3], suffix); }, _createFn: function(n, side, suffix) { var inside = ''; if (!suffix) suffix = ''; else inside = '-' + suffix; var tmp = qwp.camelCase(side); qwp.ui[n + tmp + qwp.camelCase(suffix)] = function(o) { if (qwp.isString(o)) o = $(o); return parseInt(o.css(n + '-' + side + inside)); }; qwp.ui['set' + qwp.camelCase(n) + tmp] = function(o, v) { if (qwp.isString(o)) o = $(o); o.css(n, v); }; }, _createFn2: function(n, side1, side2, suffix) { var inside = ''; if (!suffix) suffix = ''; else inside = '-' + suffix; var tmp = qwp.camelCase(side1) + qwp.camelCase(side2); qwp.ui[n + tmp + qwp.camelCase(suffix)] = function(o) { if (qwp.isString(o)) o = $(o); return parseInt(o.css(n + '-' + side1 + inside)) + parseInt(o.css(n + '-' + side2 + inside)); }; }, _fns: [], push: function(f) { qwp.ui._fns.push(f); }, createUIComponents: function(p) { qwp.ui.input.createUIComponents(p); var t; if (p) t = p.find('[data-rel=tooltip]'); else t = $('[data-rel=tooltip]'); t.each(function(i, o){ e = $(o); if (!e.hasClass('tooltip-info')) e.addClass('tooltip-info'); e.tooltip(); }); if (p) p.find('[data-rel=popover]').popover(); else $('[data-rel=popover]').popover(); for (var i = 0; i < qwp.ui._fns.length; ++i) { qwp.ui._fns[i](p); } }, resize: function(f, timer, p, params) { if (!timer) { $(window).resize(f); return; } var inResize = false; var resize = function () { f(params); inResize = false; }, resizeTimer = function () { if (p) qwp.ui.whenVisible(p, resize); else resize(); }; $(window).resize(function () { if (inResize) return; inResize = true; setTimeout(resizeTimer, 200); }); setTimeout(resizeTimer, 200); }, autoHeight: function (s, delta) { var o = $(s), pos = o.offset(); var h = $(window).height() - pos.top - qwp.ui.paddingTopBottom(o) - qwp.ui.<API key>(o) - qwp.ui.marginBottom(o); if (delta) { if ($.isNumeric(delta)) delta = parseInt(delta); else delta = qwp.fn(delta)(); } else { delta = 0; } h -= delta; o.css({height:h+'px'}); }, e: function(s) { s = $(s); return s && s.length > 0 ? s[0] : !!0; }, tmpl: function(id, noRemove) { var o = $("qwp[tmpl='" + id + "']"); var h = o.html(); if (!noRemove) o.remove(); return h; }, toggleClass: function(o, cls1, cls2) { if (qwp.isString(o)) o = $(o); if (o.hasClass(cls1)) { o.removeClass(cls1); o.addClass(cls2); } else { o.removeClass(cls2); o.addClass(cls1); } }, addTooltip: function(attr) { if (!attr) attr = {}; var tip = { 'data-rel': 'tooltip', 'data-placement': 'bottom' }; $.extend(tip, attr); if (!tip['data-original-title'] && tip['title']) { tip['data-original-title'] = tip['title']; delete tip['title']; } return tip; }, frame: function(name) { return document.all ? window.frames[name] : $("#"+name)[0].contentWindow; }, loadingFrame: function(frameId, page, reloadWhenSrcIsSame) { var frame = $("#"+frameId); if (frame.length == 0) return; var ifm = qwp.isString(frameId) ? qwp.ui.frame(frameId) : frameId; var oldPage = frame.attr("src"); if (qwp.isEmpty(oldPage) && qwp.isEmpty(page)){ return; } if (qwp.isEmpty(page)) { page = frame.attr("src"); } if (!reloadWhenSrcIsSame && !qwp.isEmpty(oldPage) && oldPage == page){ return; } var imgUrl = top.qwp.loadingImg.src; frame.attr("src", "about:blank"); if (ifm.window && ifm.window.document && ifm.window.document.body) { ifm.window.document.body.style.backgroundColor = "white"; ifm.window.document.body.style.fontSize = "12px"; ifm.window.document.body.innerHTML = "&nbsp;<br>" + $h.div($h.img({border:'0', src:imgUrl}) + "<br>" + $L("Loading page..."), {align:'center'}); } frame.attr("src", page); }, overlay: function(show, txt, parent, transparent, notShowLoading, top) { var p = $(parent ? parent : 'body'), zIndex = parent ? '1' : '999999', id = qwp.ui._ols.length + 1; qwp.ui._ols.push(id); if (p.find('> div[qwp=overlay]').length === 0) { var bk = transparent ? 'rgba(255, 255, 255, 0.7)' : 'white'; p.append('<div id="overlay-'+id+'" qwp="overlay" style="margin:0;padding:0;text-align: center;display:none;z-index: '+zIndex+';position: absolute;background-color: '+bk+';">{0}<span mtag="txt"></span></b></div>'.format(notShowLoading ? '' : '<img src="img/loading_small.gif"><br>')); } var o = p.find('> div[qwp=overlay]'); if (txt) o.find('> span[mtag=txt]').html(txt); o.css({left: '0', top: top ? top : '0'}); if (show) { qwp.ui.sameSize(o, p); o.show(); } else { o.hide(); } }, sameSize: function(o, p) { var padding = qwp.ui.padding(p), border = qwp.ui.border(p), margin = qwp.ui.margin(p); var w = p.width() + padding.left + padding.right + border.left + border.right + margin.left + margin.right; var h = p.height() + padding.top + padding.bottom + border.top + border.bottom + margin.top + margin.bottom; o.width(w).height(h); }, _ols: [], _timer: function() { for (var i = 0, cnt = qwp.ui._ols.length; i < cnt; ++i) { if (!qwp.ui._ols[i]) continue; var o = $('#overlay-' + qwp.ui._ols[i] + ':visible'); if (o.length > 0) qwp.ui.sameSize(o, o.parent()); } }, whenVisible: function(p, f, params) { if ($(p).is(':visible')) { f(params); return false; } return setTimeout(function () { qwp.ui.whenVisible(p, f, params); }, 200); } }; qwp.uri = { root: './', blank: 'about:blank', currentPage: function(p, params) { return qwp.uri.page(p ? p : qwp.page.p, params); }, currentOps: function(ops, params) { return qwp.uri.ops(ops, qwp.page.p, params); }, currentHome: function(params) { return qwp.uri.module(qwp.page.m, params); }, defaultModule: function(params) { return qwp.uri.module(qwp.page.m, params); }, <API key>: function(params, mp) { var p = false; if (params) p = qwp.isString(params) ? params : $.param(params); if (!p) return qwp.uri.curUrlNoSort; var u = qwp.uri.curUrlNoSort; if (qwp.isString(mp)) { if (mp.length === 0) u = u.replace(/p=(\w+)/, ''); else u = u.replace(/p=(\w+)/, 'p='+mp); } return u + (qwp.uri.<API key> ? '&' : '') + p; }, join: function() { var p = '', sep = ''; for (var i = 0, cnt = arguments.length; i < cnt; ++i) { if (arguments[i].length) { p += sep + arguments[i]; sep = '&'; } } return p; }, module: function(m, params) { var p = ''; if (m) p = 'm=' + m; if (params) { if (!qwp.isString(params)) { params = $.param(params); } p = qwp.uri.join(p, params); } if (p.length) return qwp.uri.root + '?' + p; return qwp.uri.root; }, page: function(p, params, m) { if (!m) { m = qwp.page.m; } var s = ''; if (m) s = 'm=' + m; if (p) s = qwp.uri.join(s, 'p=' + p); if (params) { if (!qwp.isString(params)) { params = $.param(params); } s = qwp.uri.join(s, params); } if (s.length) return qwp.uri.root + '?' + s; return qwp.uri.root; }, ops: function(ops, p, params, m) { if (!m) { m = qwp.page.m; } var s = ''; if (m) s = 'm=' + m; if (p) s = qwp.uri.join(s, 'p=' + p); s = qwp.uri.join(s, 'op=' + ops); if (params) { if (!qwp.isString(params)) { params = $.param(params); } s = qwp.uri.join(s, params); } if (s.length) return qwp.uri.root + '?' + s; return qwp.uri.root; }, logout: function() { return qwp.uri.ops('logout', false, false, 'passport'); }, createPagerParams: function(page, psize, sortf, sort) { var p = {}; if (page) p.page = page; if (psize) p.psize = psize; if (sortf) p.sortf = sortf; if (sort) p.sort = sort; return p; }, clearSortParams: function(url) { return url.replace(/&sortf=[\w-]+/ig, ''). replace(/&sort=[\w-]+/ig, ''). replace(/&sort=[\w-]+/ig, ''). replace(/&sort=[\w-]+/ig, ''); }, init: function() { var tmp = location.search ? location.search.replace(/(&s\[.+\]=[%|\w|\+\-\.\+]+)|(&s%5b.+%5d=[%|\w|\+\-\.\+]+)/i, '').replace(/(&s\[.+\]=)|(&s%5b.+%5d=)/i, '') : ''; var base = './'; qwp.uri.baseUrl = base + (tmp ? tmp : '?'); qwp.uri.baseUrlHasParams = tmp && tmp.indexOf('=') != -1; qwp.uri.curUrl = (location.search ? './' + location.search : qwp.uri.baseUrl); tmp = qwp.uri.clearSortParams(qwp.uri.curUrl); qwp.uri.curUrlNoSort = tmp; qwp.uri.<API key> = tmp && tmp.indexOf('=') != -1; qwp.uri.hasParams = location.search ? true : false; } }; })(jQuery, $h); function $READY() { qwp.uri.init(); qwp.ui.init(); $.each(['table', 'dialog', 'form', 'search', 'list'], function(i, v){ if (qwp[v]) qwp[v].init(); }); if ($.isFunction(window['initPage'])) qwp.r(initPage); for (var i = 0; i < qwp._r.length; ++i) { qwp._r[i](); } qwp.ui.createUIComponents(); setInterval(function(){qwp.ui._timer();}, 300); }
import _ from 'lodash'; import React, { Component } from 'react'; import { View, Text, Image } from 'react-native'; import { connect } from 'react-redux'; import { clearLikedJobs } from '../actions'; import FBLoginView from '../components/FBLoginView'; import {FBLogin, FBLoginManager} from '<API key>'; import { AsyncStorage } from 'react-native'; import { Button,Icon } from '<API key>'; class SettingsScreen extends Component { static navigationOptions =({ navigation }) => ({ title: 'Settings', tabBarIcon: ({ tintColor }) => { return <Icon name="settings" size={25} color={tintColor} />; } }); render() { return( <View> <Button title="Reset Liked Jobs" icon={{ name: 'delete-forever' }} backgroundColor="crimson" buttonStyle={{ marginTop:30 }} onPress= { this.props.clearLikedJobs }/> <FBLogin buttonView={<FBLoginView />} onLogout={() => {AsyncStorage.removeItem('fb_token')}} /> </View> ); }; } export default connect(null, { clearLikedJobs })(SettingsScreen);
define(function () { // matches polyfill this.Element && function(ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || ElementPrototype.<API key> || ElementPrototype.msMatchesSelector || function(selector) { var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1; while (nodes[++i] && nodes[i] != node); return !!nodes[i]; } }(Element.prototype); // closest polyfill this.Element && function(ElementPrototype) { ElementPrototype.closest = ElementPrototype.closest || function(selector) { var el = this; while (el.matches && !el.matches(selector)) el = el.parentNode; return el.matches ? el : null; } }(Element.prototype); });
using System; using System.Collections.Generic; using WhetStone.SystemExtensions; namespace WhetStone.Comparison { <summary> A comparer that maps a value from one type to another, for either equality comparison or order comparison. </summary> <typeparam name="T">The original type to be compared.</typeparam> <typeparam name="G">The mapped type to compare.</typeparam> public class FunctionComparer<T, G> : IComparer<T>, IEqualityComparer<T> { private readonly Func<T, G> _f; private readonly IEqualityComparer<G> _e; private readonly IComparer<G> _c; <summary> Constructor. </summary> <param name="f">The mapper function to map from <typeparamref name="T"/> to <typeparamref name="G"/>.</param> <param name="c">The internal <see cref="IComparer{T}"/> to compare mapped elements with. <see langword="null"/> for default.</param> <param name="e">the internal <see cref="IEqualityComparer{T}"/> to hash and compare equality of mapped elements with. <see langword="null"/> for <paramref name="c"/> to compare equality and default hasher.</param> public FunctionComparer(Func<T, G> f, IComparer<G> c = null, IEqualityComparer<G> e = null) { f.ThrowIfNull(nameof(f)); _f = f; _c = c ?? Comparer<G>.Default; _e = e; } <inheritdoc /> public int Compare(T x, T y) { return _c.Compare(_f(x), _f(y)); } <inheritdoc /> public bool Equals(T x, T y) { if (_e == null) { return Compare(x, y) == 0; } return _e.Equals(_f(x), _f(y)); } <inheritdoc /> public int GetHashCode(T obj) { var tohash = _f(obj); return (_e ?? EqualityComparer<G>.Default).GetHashCode(tohash); } } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.15"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>psl1ght: _camera_info_ex Struct Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">psl1ght </div> <div id="projectbrief">A free SDK for Sony&#39;s PS3 console</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.15 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-attribs">Data Fields</a> </div> <div class="headertitle"> <div class="title">_camera_info_ex Struct Reference</div> </div> </div><!--header <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Data Fields</h2></td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> cameraFormat&#160;</td><td class="memItemRight" valign="bottom"><b>format</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> cameraResolution&#160;</td><td class="memItemRight" valign="bottom"><b>resolution</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>framerate</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> u32&#160;</td><td class="memItemRight" valign="bottom"><b>buffer</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>bytesize</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>width</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>height</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>dev_num</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>guid</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>info_ver</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> sys_mem_container_t&#160;</td><td class="memItemRight" valign="bottom"><b>container</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> s32&#160;</td><td class="memItemRight" valign="bottom"><b>readmode</b></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a> u32&#160;</td><td class="memItemRight" valign="bottom"><b>pbuf</b> [2]</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this struct was generated from the following file:<ul> <li>ppu/include/io/<a class="el" href="camera_8h_source.html">camera.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Aug 7 2019 09:58:39 for psl1ght by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.15 </small></address> </body> </html>
'use strict'; const nami = require('nami'); const post = require('../../../lib/post'); const optsComm = require('../../../cfg/commonOpts/post'); module.exports.desc = 'Get SIP registry info.'; module.exports.opts = optsComm; module.exports.impl = (opts = {}) => { const optsParsed = opts; optsParsed.proto = 'ami'; const action = new nami.Actions.SipShowRegistry(); return post(optsParsed.rhost, action, optsParsed); };
<?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Models\Club; use App\Models\User; use Faker\Generator as Faker; use Illuminate\Support\Str; $factory->define(Club::class, function (Faker $faker) { $faker->addProvider(new FakerSchoolId($faker)); return [ 'leader_id' => function () { return factory(User::class)->create()->id; }, 'name' => Str::title($faker->company), 'city' => $faker->city, 'location' => 'US-' . $faker->stateAbbr, 'school_id' => $faker->school->school_id, ]; });
import {Response} from 'ember-cli-mirage'; import {dasherize} from '@ember/string'; import {isBlank} from '@ember/utils'; import {paginateModelArray} from '../utils'; export default function mockPosts(server) { server.post('/posts', function ({posts}) { let attrs = this.<API key>(); // mirage expects `author` to be a reference but we only have an ID attrs.authorId = attrs.author; delete attrs.author; if (isBlank(attrs.slug) && !isBlank(attrs.title)) { attrs.slug = dasherize(attrs.title); } return posts.create(attrs); }); // TODO: handle author filter server.get('/posts/', function ({posts}, {queryParams}) { let page = +queryParams.page || 1; let limit = +queryParams.limit || 15; let {status, staticPages} = queryParams; let query = {}; let models; if (status && status !== 'all') { query.status = status; } if (staticPages === 'false') { query.page = false; } if (staticPages === 'true') { query.page = true; } models = posts.where(query).models; return paginateModelArray('posts', models, page, limit); }); server.get('/posts/:id/', function ({posts}, {params}) { let {id} = params; let post = posts.find(id); return post || new Response(404, {}, { errors: [{ errorType: 'NotFoundError', message: 'Post not found.' }] }); }); // Handle embedded author in post server.put('/posts/:id/', function ({posts}, request) { let post = this.<API key>(); let {author} = post; delete post.author; let savedPost = posts.find(request.params.id).update(post); savedPost.authorId = author; savedPost.save(); return savedPost; }); server.del('/posts/:id/'); }
import angular from 'angular'; // angular modules import constants from './constants'; import onConfig from './on_config'; import onRun from './on_run'; //import 'angular-bootstrap'; import 'angular-resource'; import 'angular-route'; import 'angular-morris'; import 'angular-cookies'; import 'angular-messages'; import '<API key>'; import 'angular-animate'; import 'angular-acl'; import 'sweetalert'; import '<API key>'; //import 'ngcsv'; import './templates'; import './filters'; import './controllers'; import './services'; import './directives'; import './factories'; // create and bootstrap application const requires = [ 'ngResource', //Resource for petitions 'ngRoute', //Route URLS 'angular.morris',//Graphs 'ngCookies',//Store in cookies 'ngMessages', //Messages in forms 'ui.bootstrap', //UI Bootstrap 'ui.bootstrap.tpls', //UI Bootstrap Templates 'ui-notification', //Alert notifications 'ngAnimate', //Animations 'mm.acl', //Access Control Lists 'templates', //Auto created 'app.filters', 'app.controllers', 'app.services', 'app.directives', 'app.factories' ]; // mount on window for testing window.app = angular.module('troyApp', requires); angular.module('troyApp').constant('AppSettings', constants); angular.module('troyApp').config(onConfig); angular.module('troyApp').run(onRun); angular.bootstrap(document, ['troyApp'], { strictDi: true });
var body = document.querySelector('body'), qunitEl = document.createElement('div'), qunitFixtEl = document.createElement('div'); qunitEl.id = 'qunit'; qunitFixtEl.id = 'qunit-fixture'; body.appendChild(qunitEl); body.appendChild(qunitFixtEl); /* $('body').append( '<div id="qunit"></div>' + '<div id="qunit-fixture"></div>' );*/
<?php /** * @package WordPress * @subpackage Cleanfrog */ ?> <div id="sidebar"> <ul> <?php if ( function_exists('dynamic_sidebar') && dynamic_sidebar(1) ) : else : ?> <li id="archives" class="widget"> <h2 class="widgettitle"><?php _e( 'Archives', 'cleanfrog' ); ?></h2> <ul> <?php wp_get_archives( 'type=monthly' ); ?> </ul> </li> <li id="meta" class="widget"> <h2 class="widgettitle"><?php _e( 'Meta', 'cleanfrog' ); ?></h2> <ul> <?php wp_register(); ?> <li><?php wp_loginout(); ?></li> <?php wp_meta(); ?> </ul> </li> <?php endif; ?> </ul> </div>
require 'generators/oauth_inflections' class O<API key> < Rails::Generators::NamedBase source_root File.expand_path("../templates", __FILE__) argument :name, :type => :string, :default => 'Oauth' desc 'This creates an OAuth Provider controller as well as the requisite models.' hook_for :orm def <API key> # Check for class naming collisions. class_collisions class_path, "#{class_name}Controller", # Oauth Controller "#{class_name}Helper", "#{class_name}ClientsController", "#{class_name}ClientsHelper" end def <API key> template 'controller.rb', File.join('app/controllers', class_path, "#{file_name}_controller.rb") template 'clients_controller.rb', File.join('app/controllers', class_path, "#{file_name}_clients_controller.rb") end hook_for :test_framework, :template_engine def add_routes route "match '/oauth', :to => 'oauth#index', :as => :oauth" route "match '/oauth/authorize', :to => 'oauth#authorize', :as => :authorize" route "match '/oauth/request_token', :to => 'oauth#request_token', :as => :request_token" route "match '/oauth/access_token', :to => 'oauth#access_token', :as => :access_token" route "match '/oauth/token', :to => 'oauth#token', :as => :token" route "match '/oauth/test_request', :to => 'oauth#test_request', :as => :test_request" route "resources :#{file_name}_clients" end def add_routes route "match '/oauth', :to => 'oauth#index', :as => :oauth" route "match '/oauth/authorize', :to => 'oauth#authorize', :as => :authorize" route "match '/oauth/request_token', :to => 'oauth#request_token', :as => :request_token" route "match '/oauth/access_token', :to => 'oauth#access_token', :as => :access_token" route "match '/oauth/token', :to => 'oauth#token', :as => :token" route "match '/oauth/test_request', :to => 'oauth#test_request', :as => :test_request" route "resources :#{file_name}_clients" end end
# <API key>: true # == Schema Information # Table name: plugins_surveys # id :integer not null, primary key # active :boolean default(FALSE) # auto_advance :boolean default(TRUE) # ref :string # created_at :datetime # updated_at :datetime # page_id :integer # Indexes # <API key> (page_id) class Plugins::Survey < ApplicationRecord has_many :forms, -> { order(position: :asc, created_at: :asc) }, as: :formable, dependent: :destroy belongs_to :page, touch: true after_create :<API key> DEFAULTS = {}.freeze REQUIRED_FIELDS = [:email].freeze def liquid_data(_supplemental_data = {}) attributes.merge(forms: forms.includes(:form_elements).map { |form| form_liquid_data(form) }) end def name self.class.name.demodulize end def <API key> REQUIRED_FIELDS.map do |field| relevant = fields_with_name(field) relevant.size == 1 ? relevant[0].id : nil end.compact end def <API key> ensure_has_a_form REQUIRED_FIELDS.each do |field| next unless fields_with_name(field).empty? language = page.try(:language).try(:code) || I18n.default_locale data_type = FormElement::VALID_TYPES.include?(field.to_s) ? field : 'text' FormElement.create(name: field, data_type: data_type, form: forms.first, required: true, label: I18n.t("form.default.#{field}", locale: language)) forms.first.reload end end def ensure_has_a_form return forms if forms.size >= 1 Form.create(name: "survey_form_#{id}", master: false, formable: self) forms.reload end def form_liquid_data(form) { form_id: form.try(:id), fields: form.form_elements.map(&:liquid_data), outstanding_fields: form.form_elements.map(&:name), skippable: form.form_elements.map(&:required).none? } end private def fields_with_name(name) forms.map(&:form_elements).flatten.select { |el| el.name.to_sym == name } end end
// Package options provides ways to extract the task-related options from a Flux script. package options import ( "context" "errors" "fmt" "strings" "time" "github.com/influxdata/cron" "github.com/influxdata/flux" "github.com/influxdata/flux/ast" "github.com/influxdata/flux/ast/edit" "github.com/influxdata/flux/interpreter" "github.com/influxdata/flux/semantic" "github.com/influxdata/flux/values" "github.com/influxdata/influxdb/v2/pkg/pointer" ) const maxConcurrency = 100 const maxRetry = 10 // Options are the task-related options that can be specified in a Flux script. type Options struct { // Name is a non optional name designator for each task. Name string `json:"name,omitempty"` // Cron is a cron style time schedule that can be used in place of Every. Cron string `json:"cron,omitempty"` // Every represents a fixed period to repeat execution. // this can be unmarshaled from json as a string i.e.: "1d" will unmarshal as 1 day Every Duration `json:"every,omitempty"` // Offset represents a delay before execution. // this can be unmarshaled from json as a string i.e.: "1d" will unmarshal as 1 day Offset *Duration `json:"offset,omitempty"` Concurrency *int64 `json:"concurrency,omitempty"` Retry *int64 `json:"retry,omitempty"` } // Duration is a time span that supports the same units as the flux parser's time duration, as well as negative length time spans. type Duration struct { Node ast.DurationLiteral } func (a Duration) String() string { return ast.Format(&a.Node) } // Parse parses a string into a Duration. func (a *Duration) Parse(s string) error { q, err := ParseSignedDuration(s) if err != nil { return <API key>(err) } a.Node = *q return nil } // MustParseDuration parses a string and returns a duration. It panics if there is an error. func MustParseDuration(s string) (dur *Duration) { dur = &Duration{} if err := dur.Parse(s); err != nil { panic(err) } return dur } // UnmarshalText unmarshals text into a Duration. func (a *Duration) UnmarshalText(text []byte) error { q, err := ParseSignedDuration(string(text)) if err != nil { return err } a.Node = *q return nil } // MarshalText marshals text into a Duration. func (a Duration) MarshalText() ([]byte, error) { return []byte(a.String()), nil } // IsZero checks if each segment of the duration is zero, it doesn't check if the Duration sums to zero, just if each internal duration is zero. func (a *Duration) IsZero() bool { for i := range a.Node.Values { if a.Node.Values[i].Magnitude != 0 { return false } } return true } // DurationFrom gives us a time.Duration from a time. // Currently because of how flux works, this is just an approfimation for any time unit larger than hours. func (a *Duration) DurationFrom(t time.Time) (time.Duration, error) { return ast.DurationFrom(&a.Node, t) } // Add adds the duration to a time. func (a *Duration) Add(t time.Time) (time.Time, error) { d, err := ast.DurationFrom(&a.Node, t) if err != nil { return time.Time{}, err } return t.Add(d), nil } // Clear clears out all options in the options struct, it us useful if you wish to reuse it. func (o *Options) Clear() { o.Name = "" o.Cron = "" o.Every = Duration{} o.Offset = nil o.Concurrency = nil o.Retry = nil } // IsZero tells us if the options has been zeroed out. func (o *Options) IsZero() bool { return o.Name == "" && o.Cron == "" && o.Every.IsZero() && (o.Offset == nil || o.Offset.IsZero()) && o.Concurrency == nil && o.Retry == nil } // All the task option names we accept. const ( optName = "name" optCron = "cron" optEvery = "every" optOffset = "offset" optConcurrency = "concurrency" optRetry = "retry" ) // contains is a helper function to see if an array of strings contains a string func contains(s []string, e string) bool { for i := range s { if s[i] == e { return true } } return false } func grabTaskOptionAST(p *ast.Package, keys ...string) map[string]ast.Expression { res := make(map[string]ast.Expression, 2) // we preallocate two keys for the map, as that is how many we will use at maximum (offset and every) for i := range p.Files { for j := range p.Files[i].Body { if p.Files[i].Body[j].Type() != "OptionStatement" { continue } opt := (p.Files[i].Body[j]).(*ast.OptionStatement) if opt.Assignment.Type() != "VariableAssignment" { continue } asmt, ok := opt.Assignment.(*ast.VariableAssignment) if !ok { continue } if asmt.ID.Key() != "task" { continue } ae, ok := asmt.Init.(*ast.ObjectExpression) if !ok { continue } for k := range ae.Properties { prop := ae.Properties[k] if prop != nil { if key := prop.Key.Key(); contains(keys, key) { res[key] = prop.Value } } } return res } } return res } func newDeps() flux.Dependencies { deps := flux.<API key>() deps.Deps.HTTPClient = httpClient{} deps.Deps.URLValidator = urlValidator{} deps.Deps.SecretService = secretService{} deps.Deps.FilesystemService = fileSystem{} return deps } // FluxLanguageService is a service for interacting with flux code. type FluxLanguageService interface { // Parse will take flux source code and produce a package. // If there are errors when parsing, the first error is returned. // An ast.Package may be returned when a parsing error occurs, // but it may be null if parsing didn't even occur. Parse(source string) (*ast.Package, error) // EvalAST will evaluate and run an AST. EvalAST(ctx context.Context, astPkg *ast.Package) ([]interpreter.SideEffect, values.Scope, error) } // FromScriptAST extracts Task options from a Flux script using only the AST (no // evaluation of the script). Using AST here allows us to avoid having to // contend with functions that aren't available in some parsing contexts (within // Gateway for example). func FromScriptAST(lang FluxLanguageService, script string) (Options, error) { opts := Options{ Retry: pointer.Int64(1), Concurrency: pointer.Int64(1), } fluxAST, err := parse(lang, script) if err != nil { return opts, err } if len(fluxAST.Files) == 0 { return opts, ErrNoASTFile } file := fluxAST.Files[0] if hasDuplicateOptions(file, "task") { return opts, <API key> } obj, err := edit.GetOption(file, "task") if err != nil { return opts, <API key> } objExpr, ok := obj.(*ast.ObjectExpression) if !ok { return opts, <API key>(objExpr.Type()) } for _, fn := range <API key> { if err := fn(&opts, objExpr); err != nil { return opts, err } } if err := opts.Validate(); err != nil { return opts, err } return opts, nil } // hasDuplicateOptions determines whether or not there are multiple assignments // to the same option variable. // TODO(brett): This will be superceded by edit.HasDuplicateOptions once its available. func hasDuplicateOptions(file *ast.File, name string) bool { var n int for _, st := range file.Body { if val, ok := st.(*ast.OptionStatement); ok { assign := val.Assignment if va, ok := assign.(*ast.VariableAssignment); ok { if va.ID.Name == name { n++ } } } } return n > 1 } type extractFn func(*Options, *ast.ObjectExpression) error var <API key> = []extractFn{ extractNameOption, <API key>, extractOffsetOption, <API key>, extractRetryOption, } func extractNameOption(opts *Options, objExpr *ast.ObjectExpression) error { nameExpr, err := edit.GetProperty(objExpr, optName) if err != nil { return <API key>(optName) } nameStr, ok := nameExpr.(*ast.StringLiteral) if !ok { return <API key>(optName) } opts.Name = ast.StringFromLiteral(nameStr) return nil } func <API key>(opts *Options, objExpr *ast.ObjectExpression) error { cronExpr, cronErr := edit.GetProperty(objExpr, optCron) everyExpr, everyErr := edit.GetProperty(objExpr, optEvery) if cronErr == nil && everyErr == nil { return <API key> } if cronErr != nil && everyErr != nil { return <API key>("cron or every") } if cronErr == nil { cronExprStr, ok := cronExpr.(*ast.StringLiteral) if !ok { return <API key>(optCron) } opts.Cron = ast.StringFromLiteral(cronExprStr) } if everyErr == nil { everyDur, ok := everyExpr.(*ast.DurationLiteral) if !ok { return <API key>(optEvery) } opts.Every = Duration{Node: *everyDur} } return nil } func extractOffsetOption(opts *Options, objExpr *ast.ObjectExpression) error { offsetExpr, offsetErr := edit.GetProperty(objExpr, optOffset) if offsetErr != nil { return nil } switch offsetExprV := offsetExpr.(type) { case *ast.UnaryExpression: offsetDur, err := ParseSignedDuration(offsetExprV.Loc.Source) if err != nil { return err } opts.Offset = &Duration{Node: *offsetDur} case *ast.DurationLiteral: opts.Offset = &Duration{Node: *offsetExprV} default: return <API key>(optOffset) } return nil } func <API key>(opts *Options, objExpr *ast.ObjectExpression) error { concurExpr, err := edit.GetProperty(objExpr, optConcurrency) if err != nil { return nil } concurInt, ok := concurExpr.(*ast.IntegerLiteral) if !ok { return <API key>(optConcurrency) } val := ast.IntegerFromLiteral(concurInt) opts.Concurrency = &val return nil } func extractRetryOption(opts *Options, objExpr *ast.ObjectExpression) error { retryExpr, err := edit.GetProperty(objExpr, optRetry) if err != nil { return nil } retryInt, ok := retryExpr.(*ast.IntegerLiteral) if !ok { return <API key>(optRetry) } val := ast.IntegerFromLiteral(retryInt) opts.Retry = &val return nil } // FromScript extracts Options from a Flux script. func FromScript(lang FluxLanguageService, script string) (Options, error) { opt := Options{Retry: pointer.Int64(1), Concurrency: pointer.Int64(1)} fluxAST, err := parse(lang, script) if err != nil { return opt, err } durTypes := grabTaskOptionAST(fluxAST, optEvery, optOffset) // TODO(desa): should be dependencies.NewEmpty(), but for now we'll hack things together ctx := newDeps().Inject(context.Background()) _, scope, err := evalAST(ctx, lang, fluxAST) if err != nil { return opt, err } // pull options from the program scope task, ok := scope.Lookup("task") if !ok { return opt, <API key>("task") } // check to make sure task is an object if err := checkNature(task.Type().Nature(), semantic.Object); err != nil { return opt, err } optObject := task.Object() if err := validateOptionNames(optObject); err != nil { return opt, err } nameVal, ok := optObject.Get(optName) if !ok { return opt, <API key>("name") } if err := checkNature(nameVal.Type().Nature(), semantic.String); err != nil { return opt, err } opt.Name = nameVal.Str() crVal, cronOK := optObject.Get(optCron) everyVal, everyOK := optObject.Get(optEvery) if cronOK && everyOK { return opt, <API key> } if !cronOK && !everyOK { return opt, <API key>("cron or every is required") } if cronOK { if err := checkNature(crVal.Type().Nature(), semantic.String); err != nil { return opt, err } opt.Cron = crVal.Str() } if everyOK { if err := checkNature(everyVal.Type().Nature(), semantic.Duration); err != nil { return opt, err } dur, ok := durTypes["every"] if !ok || dur == nil { return opt, <API key>("every") } durNode, err := ParseSignedDuration(dur.Location().Source) if err != nil { return opt, err } if !ok || durNode == nil { return opt, <API key>("every") } durNode.BaseNode = ast.BaseNode{} opt.Every.Node = *durNode } if offsetVal, ok := optObject.Get(optOffset); ok { if err := checkNature(offsetVal.Type().Nature(), semantic.Duration); err != nil { return opt, err } dur, ok := durTypes["offset"] if !ok || dur == nil { return opt, <API key>("offset") } durNode, err := ParseSignedDuration(dur.Location().Source) if err != nil { return opt, err } if !ok || durNode == nil { return opt, <API key>("offset") } durNode.BaseNode = ast.BaseNode{} opt.Offset = &Duration{} opt.Offset.Node = *durNode } if concurrencyVal, ok := optObject.Get(optConcurrency); ok { if err := checkNature(concurrencyVal.Type().Nature(), semantic.Int); err != nil { return opt, err } opt.Concurrency = pointer.Int64(concurrencyVal.Int()) } if retryVal, ok := optObject.Get(optRetry); ok { if err := checkNature(retryVal.Type().Nature(), semantic.Int); err != nil { return opt, err } opt.Retry = pointer.Int64(retryVal.Int()) } if err := opt.Validate(); err != nil { return opt, err } return opt, nil } // Validate returns an error if the options aren't valid. func (o *Options) Validate() error { now := time.Now() var errs []string if o.Name == "" { errs = append(errs, "name required") } cronPresent := o.Cron != "" everyPresent := !o.Every.IsZero() if cronPresent == everyPresent { // They're both present or both missing. errs = append(errs, "must specify exactly one of either cron or every") } else if cronPresent { _, err := cron.ParseUTC(o.Cron) if err != nil { errs = append(errs, "cron invalid: "+err.Error()) } } else if everyPresent { every, err := o.Every.DurationFrom(now) if err != nil { return err } if every < time.Second { errs = append(errs, "every option must be at least 1 second") } else if every.Truncate(time.Second) != every { errs = append(errs, "every option must be expressible as whole seconds") } } if o.Offset != nil { offset, err := o.Offset.DurationFrom(now) if err != nil { return err } if offset.Truncate(time.Second) != offset { // For now, allowing negative offset delays. Maybe they're useful for forecasting? errs = append(errs, "offset option must be expressible as whole seconds") } } if o.Concurrency != nil { if *o.Concurrency < 1 { errs = append(errs, "concurrency must be at least 1") } else if *o.Concurrency > maxConcurrency { errs = append(errs, fmt.Sprintf("concurrency exceeded max of %d", maxConcurrency)) } } if o.Retry != nil { if *o.Retry < 1 { errs = append(errs, "retry must be at least 1") } else if *o.Retry > maxRetry { errs = append(errs, fmt.Sprintf("retry exceeded max of %d", maxRetry)) } } if len(errs) == 0 { return nil } return fmt.Errorf("invalid options: %s", strings.Join(errs, ", ")) } // EffectiveCronString returns the effective cron string of the options. // If the cron option was specified, it is returned. // If the every option was specified, it is converted into a cron string using "@every". // Otherwise, the empty string is returned. // The value of the offset option is not considered. // TODO(docmerlin): create an <API key>(t time.Time) string, // that works from a unit of time. // Do not use this if you haven't checked for validity already. func (o *Options) EffectiveCronString() string { if o.Cron != "" { return o.Cron } every, _ := o.Every.DurationFrom(time.Now()) // we can ignore errors here because we have alreach checked for validity. if every > 0 { return "@every " + o.Every.String() } return "" } // checkNature returns a clean error of got and expected dont match. func checkNature(got, exp semantic.Nature) error { if got != exp { return fmt.Errorf("unexpected kind: got %q expected %q", got, exp) } return nil } // validateOptionNames returns an error if any keys in the option object o // do not match an expected option name. func validateOptionNames(o values.Object) error { var unexpected []string o.Range(func(name string, _ values.Value) { switch name { case optName, optCron, optEvery, optOffset, optConcurrency, optRetry: // Known option. Nothing to do. default: unexpected = append(unexpected, name) } }) if len(unexpected) > 0 { u := strings.Join(unexpected, ", ") v := strings.Join([]string{optName, optCron, optEvery, optOffset, optConcurrency, optRetry}, ", ") return fmt.Errorf("unknown task option(s): %s. valid options are %s", u, v) } return nil } // parse will take flux source code and produce a package. // If there are errors when parsing, the first error is returned. // An ast.Package may be returned when a parsing error occurs, // but it may be null if parsing didn't even occur. // This will return an error if the FluxLanguageService is nil. func parse(lang FluxLanguageService, source string) (*ast.Package, error) { if lang == nil { return nil, errors.New("flux is not configured; cannot parse") } return lang.Parse(source) } // EvalAST will evaluate and run an AST. // This will return an error if the FluxLanguageService is nil. func evalAST(ctx context.Context, lang FluxLanguageService, astPkg *ast.Package) ([]interpreter.SideEffect, values.Scope, error) { if lang == nil { return nil, nil, errors.New("flux is not configured; cannot evaluate") } return lang.EvalAST(ctx, astPkg) }
package com.swfarm.biz.chain.dto; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import com.swfarm.pub.framework.OrderItem; import com.swfarm.pub.utils.DateUtils; public class <API key> implements Serializable { private String productManagerNo; private String vendorName; private String articleNumber; private String vendorOrderNo; private String shippingOrderNo; private List articleNumbers = new ArrayList(); private Date startDate; private Date endDate; private Date submitStartDate; private Date submitEndDate; private String purchaseTaskNo; private List<String> purchaseTaskNos = new ArrayList<String>(); private List purchaseTaskIds; private String[] <API key>; private String <API key>; private Double lowerTotalPrice; private Double higherTotalPrice; private Long warehouseId; private Boolean hasDevelopingSku; private Boolean hasIssues; private Boolean isIssuesResolved; private String[] tagNames; private Boolean isPrinted; private String <API key>; private Boolean hasShippingOrderNo; private List orderItemList = new ArrayList(); private Long vendorId; public String getProductManagerNo() { return productManagerNo; } public void setProductManagerNo(String productManagerNo) { this.productManagerNo = productManagerNo; } public String getVendorName() { return vendorName; } public void setVendorName(String customerName) { this.vendorName = customerName; } public String getArticleNumber() { return articleNumber; } public void setArticleNumber(String articleNumber) { this.articleNumber = articleNumber; } public List getArticleNumbers() { if (articleNumbers == null) { articleNumbers = new ArrayList(); } return articleNumbers; } public void setArticleNumbers(List articleNumbers) { this.articleNumbers = articleNumbers; } public Date getStartDate() { return startDate; } public String getStartDateString() { if (startDate != null) { return DateUtils.dateToString(startDate, "yyyy/MM/dd"); } else { return StringUtils.EMPTY; } } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public String getEndDateString() { if (endDate != null) { return DateUtils.dateToString(endDate, "yyyy/MM/dd"); } else { return StringUtils.EMPTY; } } public Date getSubmitStartDate() { return submitStartDate; } public String <API key>() { if (submitStartDate != null) { return DateUtils.dateToString(submitStartDate, "yyyy/MM/dd"); } else { return StringUtils.EMPTY; } } public void setSubmitStartDate(Date submitStartDate) { this.submitStartDate = submitStartDate; } public Date getSubmitEndDate() { return submitEndDate; } public String <API key>() { if (submitEndDate != null) { return DateUtils.dateToString(submitEndDate, "yyyy/MM/dd"); } else { return StringUtils.EMPTY; } } public void setSubmitEndDate(Date submitEndDate) { this.submitEndDate = submitEndDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getPurchaseTaskNo() { return purchaseTaskNo; } public void setPurchaseTaskNo(String customerOrderNo) { this.purchaseTaskNo = customerOrderNo; } public List getPurchaseTaskIds() { if (purchaseTaskIds == null) { purchaseTaskIds = new ArrayList(); } return purchaseTaskIds; } public void setPurchaseTaskIds(List purchaseTaskIds) { this.purchaseTaskIds = purchaseTaskIds; } public String[] <API key>() { return <API key>; } public String <API key>() { StringBuffer jsBuffer = new StringBuffer(); jsBuffer.append("["); if (this.<API key> != null && this.<API key>.length > 0) { for (int i = 0; i < this.<API key>.length; i++) { jsBuffer.append("'"); jsBuffer.append(this.<API key>[i]); jsBuffer.append("'"); if (i < this.<API key>.length - 1) { jsBuffer.append(","); } } } jsBuffer.append("]"); return jsBuffer.toString(); } public void <API key>(String[] <API key>) { this.<API key> = <API key>; } public String <API key>() { return <API key>; } public void <API key>(String <API key>) { this.<API key> = <API key>; } public Double getLowerTotalPrice() { return lowerTotalPrice; } public void setLowerTotalPrice(Double lowerTotalPrice) { this.lowerTotalPrice = lowerTotalPrice; } public Double getHigherTotalPrice() { return higherTotalPrice; } public void setHigherTotalPrice(Double higherTotalPrice) { this.higherTotalPrice = higherTotalPrice; } public Long getWarehouseId() { return warehouseId; } public void setWarehouseId(Long warehouseId) { this.warehouseId = warehouseId; } public Boolean getHasDevelopingSku() { return hasDevelopingSku; } public void setHasDevelopingSku(Boolean hasDevelopingSku) { this.hasDevelopingSku = hasDevelopingSku; } public Boolean getHasIssues() { return hasIssues; } public void setHasIssues(Boolean hasIssues) { this.hasIssues = hasIssues; } public Boolean getIsIssuesResolved() { return isIssuesResolved; } public void setIsIssuesResolved(Boolean isIssuesResolved) { this.isIssuesResolved = isIssuesResolved; } public String getVendorOrderNo() { return vendorOrderNo; } public void setVendorOrderNo(String vendorOrderNo) { this.vendorOrderNo = vendorOrderNo; } public String getShippingOrderNo() { return shippingOrderNo; } public void setShippingOrderNo(String shippingOrderNo) { this.shippingOrderNo = shippingOrderNo; } public String[] getTagNames() { return tagNames; } public String getTagNameJsArr() { if (tagNames != null && tagNames.length > 0) { StringBuffer buffer = new StringBuffer(); buffer.append("["); for (int i = 0; i < tagNames.length; i++) { buffer.append("'"); buffer.append(tagNames[i]); buffer.append("'"); if (i < tagNames.length - 1) { buffer.append(","); } } buffer.append("]"); return buffer.toString(); } return null; } public void setTagNames(String[] tagNames) { this.tagNames = tagNames; } public List getOrderItemList() { if (orderItemList == null) { orderItemList = new ArrayList(); } Collections.sort(orderItemList, new Comparator() { public int compare(Object o1, Object o2) { OrderItem orderItem1 = (OrderItem) o1; OrderItem orderItem2 = (OrderItem) o2; return orderItem1.getIndex().compareTo(orderItem2.getIndex()); } }); return orderItemList; } public void addOrderItem(OrderItem orderItem) { List orderItemList = getOrderItemList(); if (!orderItemList.contains(orderItem)) { orderItemList.add(orderItem); } } public void removeOrderItem(OrderItem orderItem) { List orderItemList = getOrderItemList(); if (orderItemList.contains(orderItem)) { orderItemList.remove(orderItem); } } public String <API key>() { getOrderItemList(); StringBuffer sb = new StringBuffer(); sb.append("["); for (Iterator iter = orderItemList.iterator(); iter.hasNext();) { OrderItem orderItem = (OrderItem) iter.next(); sb.append("["); sb.append("'" + orderItem.getField() + "'"); sb.append(","); sb.append("'" + orderItem.getStatus() + "'"); sb.append(","); sb.append("'" + orderItem.getIndex() + "'"); sb.append("]"); if (iter.hasNext()) { sb.append(","); } } sb.append("]"); return sb.toString(); } public void setOrderItemList(List orderItemList) { this.orderItemList = orderItemList; } public void setIsPrinted(Boolean isPrinted) { this.isPrinted = isPrinted; } public Boolean getIsPrinted() { return isPrinted; } public String <API key>() { return <API key>; } public void <API key>(String <API key>) { this.<API key> = <API key>; } public void setPurchaseTaskNos(List<String> purchaseTaskNos) { this.purchaseTaskNos = purchaseTaskNos; } public List<String> getPurchaseTaskNos() { return purchaseTaskNos; } public Long getVendorId() { return vendorId; } public void setVendorId(Long vendorId) { this.vendorId = vendorId; } public Boolean <API key>() { return hasShippingOrderNo; } public void <API key>(Boolean hasShippingOrderNo) { this.hasShippingOrderNo = hasShippingOrderNo; } }
'use strict'; let async = require('./../utils/async'); let errors = require('./../utils/errors'); let fs = require('./promisedFs'); let path = require('path'); let patternUtils = require('./../testing/patterns'); /** * @param {Object} settings * @returns {Array.<String>} all found test files */ exports.findAll = function* (settings) { let testDir = path.resolve(process.env.BASE_DIR, settings.pathToTests); return yield* _readDirRecursively(testDir, settings.testFiles); }; /** * @param {Object} settings * @param {Array.<Object>} patterns * @returns {Array.<String>} all test files matching specified patterns */ exports.find = function* (settings, patterns) { let testDir = path.resolve(process.env.BASE_DIR, settings.pathToTests); let isDirExisting = yield fs.exists(testDir); if (!isDirExisting) { throw new errors.FileSystemError( `Test directory doesn't exists: ${testDir}` ); } let files = yield* _readDirRecursively(testDir, settings.testFiles); let testFiles = yield async(_filterValidFiles, files, patterns); patterns.forEach(function (pattern) { if (!pattern.used) { let err = `No matching tests found by pattern: ${pattern.pattern}`; throw new errors.UserInputError(err); } }); return testFiles; }; let _readDirRecursively = function* (directory, testFiles) { let testFilesPattern = new RegExp(testFiles); let files = []; for (let item of yield fs.readdir(directory)) { let filePath = path.join(directory, item); let fileInfo = yield fs.stat(filePath); if (fileInfo.isDirectory()) { let dirFiles = yield* _readDirRecursively(filePath, testFiles); files = files.concat(dirFiles); } else { let pathToFile = path.resolve(directory, item); if (pathToFile.match(testFilesPattern)) files.push(pathToFile); } } return files; }; let _filterValidFiles = async(function*(files, patterns) { let noOfPatterns = patterns.length; let filterFiles = function* (file) { let loadedFile = null; try { loadedFile = require(file); } catch (e) { throw new errors.FileSystemError( `Error while examining test file: ${e.stack}` ); } for (let i = 0; i < noOfPatterns; i++) { let pattern = patterns[i]; let isValid = yield* patternUtils.isMatching(file, loadedFile, pattern); if (isValid) { pattern.used = true; return file; } } return false; }; return Promise.all(files.map((file) => async(filterFiles, file))) .then(function (filteredFiles) { return filteredFiles.filter((value) => value !== false); }); });
# xiongmai-cam-api Xiongmai IP Camera Simple API in Python. Ported from @667bdrm's Gist (Perl script at https://gist.github.com/667bdrm/<API key>).
#include "Arduino.h" #include "vmgps.h" #include "vmlog.h" #include "GPS.h" #include "LGPS.h" typedef void (*vm_gps_handler_t)(<API key>* info); vm_gps_handler_t _gps_handle = NULL; static void _gps_callback(VMINT msg, void* data) { switch(msg) { case VM_GPS_OPEN_CNF: { VMINT result = (VMINT)data; if(result == true) { vm_log_info((char*)"open success"); } else { vm_log_warn((char*)"open failed"); } } break; case VM_GPS_CLOSE_CNF: // app cannot receive this msg now, ignore this. break; case VM_GPS_SET_MODE_CNF: { VMINT result = (VMINT)data; if(result == true) { vm_log_info((char*)"set mode success"); } else { vm_log_warn((char*)"set mode failed"); } } break; case <API key>: { LGPS.setData((<API key>*)data); } break; } } boolean gpsPowerOn(void* user_data) { VMINT result; vm_gps_type_enum* type = (vm_gps_type_enum*)user_data; result = vm_gps_open( 1, *type, _gps_callback); if(result == VM_GPS_OPEN_SUCCESS) { // this is first time to open GPS, need to get the message VM_GPS_OPEN_CNF vm_log_info((char*)"gps open success"); } else if(result == <API key>) { // GPS had been opened before, can get data, no need to wait VM_GPS_OPEN_CNF // if need you can set mode // vm_gps_set_mode(); vm_log_info((char*)"gps already open"); } else { // open failed vm_log_info((char*)"gps open failed"); } return true; } boolean gpsPowerOff(void* user_data) { vm_gps_close(); return true; } boolean gpsSetMode(void* user_data) { vm_gps_mode_enum* mode = (vm_gps_mode_enum*)user_data; vm_gps_set_mode(*mode); return true; }
package hiddenargs class count { @hiddenargs def count[T](xs: List[T], @hidden acc: Int = 0): Int = xs match { case Nil => acc case _ :: tl => count(tl, acc + 1) } assert(count(List(1, 2, 3)) == 3) assert(count(List.empty[Char]) == 0) val aToZ = 'a' to 'z' assert(count(aToZ.toList) == 26) }
<div class="static-content block-<?= $block->block_key ?>"> <div class="container"> <?= $content ?> </div> </div>
package mobi.checkapp.epoc; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import mobi.checkapp.epoc.db.DbFunctions; import mobi.checkapp.epoc.entities.Exercises; import mobi.checkapp.epoc.utils.Constants; public class <API key> extends AppCompatActivity { private final String TAG = this.getClass().getName(); //activitiesDB definitions private DbFunctions dbFunctions; private long resultDb; private Exercises exercises = null; //extra private Bundle extra; Intent returnIntent; //define variables names private Button btnDeleteExerciseOk; private Button <API key>; private TextView <API key>; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.<API key>); //Toolbar toolbar = (Toolbar) findViewById(R.id.<API key>); //setSupportActionBar(toolbar); dbFunctions = new DbFunctions(this); //variables setup btnDeleteExerciseOk = (Button) findViewById(R.id.btnDeleteExerciseOk); <API key> = (Button) findViewById(R.id.<API key>); <API key> = (TextView) findViewById(R.id.<API key>); //get information returnIntent = new Intent(); extra = this.getIntent().getBundleExtra(Constants.LISTEXERCISEBUNDLE); if(extra != null) { exercises = (Exercises) extra.getSerializable(Constants.LISTEXERCISEDATA); } //fill information if(exercises == null) {exercises = new Exercises();} else{ //put variables data <API key>.setText("¿Confirma que desea eliminar el ejercício '"+ exercises.getTitle() +"'?"); } //set actions btnDeleteExerciseOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //set intent //returnIntent = new Intent(<API key>(), <API key>.class); returnIntent = new Intent(); int result = 0; if(exercises != null) { //TODO: change deleteExercise item. Instead of deleteExercise, hide result = dbFunctions.deleteExercise(exercises); if(result > 0) { returnIntent.putExtra(Constants.EXERCISEDATA, exercises); setResult(Activity.RESULT_OK, returnIntent); } } if (result == 0 || exercises == null){ setResult(Activity.RESULT_CANCELED, returnIntent); } finish(); } }); //set actions <API key>.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_CANCELED, returnIntent); finish(); } }); } @Override public boolean <API key>(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { Log.d(TAG, "Back button clicked"); super.onBackPressed(); setResult(Activity.RESULT_CANCELED, returnIntent); finish(); } return super.<API key>(item); } @Override public void onBackPressed() { super.onBackPressed(); setResult(Activity.RESULT_CANCELED, returnIntent); finish(); } }
/* Texas Instruments. */ #include "stlport_prefix.h" #include <cstdio> #include <locale> #include <istream> #include "c_locale.h" #include "acquire_release.h" <API key> <API key> // default "C" values for month and day names const char default_dayname[][14] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; const char default_monthname[][24] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; #ifndef _STLP_NO_WCHAR_T const wchar_t default_wdayname[][14] = { L"Sun", L"Mon", L"Tue", L"Wed", L"Thu", L"Fri", L"Sat", L"Sunday", L"Monday", L"Tuesday", L"Wednesday", L"Thursday", L"Friday", L"Saturday"}; const wchar_t default_wmonthname[][24] = { L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun", L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec", L"January", L"February", L"March", L"April", L"May", L"June", L"July", L"August", L"September", L"October", L"November", L"December"}; #endif // _Init_time_info: initialize table with // "C" values (note these are not defined in the C standard, so this // is somewhat arbitrary). static void _Init_timeinfo_base(_Time_Info_Base& table) { table._M_time_format = "%H:%M:%S"; table._M_date_format = "%m/%d/%y"; table._M_date_time_format = "%m/%d/%y"; } static void _Init_timeinfo(_Time_Info& table) { int i; for (i = 0; i < 14; ++i) table._M_dayname[i] = default_dayname[i]; for (i = 0; i < 24; ++i) table._M_monthname[i] = default_monthname[i]; table._M_am_pm[0] = "AM"; table._M_am_pm[1] = "PM"; _Init_timeinfo_base(table); } #ifndef _STLP_NO_WCHAR_T static void _Init_timeinfo(_WTime_Info& table) { int i; for (i = 0; i < 14; ++i) table._M_dayname[i] = default_wdayname[i]; for (i = 0; i < 24; ++i) table._M_monthname[i] = default_wmonthname[i]; table._M_am_pm[0] = L"AM"; table._M_am_pm[1] = L"PM"; _Init_timeinfo_base(table); } #endif static void _Init_timeinfo_base(_Time_Info_Base& table, _Locale_time * time) { table._M_time_format = _Locale_t_fmt(time); if ( table._M_time_format == "%T" ) { table._M_time_format = "%H:%M:%S"; } else if ( table._M_time_format == "%r" ) { table._M_time_format = "%I:%M:%S %p"; } else if ( table._M_time_format == "%R" ) { table._M_time_format = "%H:%M"; } table._M_date_format = _Locale_d_fmt(time); table._M_date_time_format = _Locale_d_t_fmt(time); table._M_long_date_format = _Locale_long_d_fmt(time); table.<API key> = <API key>(time); } static void _Init_timeinfo(_Time_Info& table, _Locale_time * time) { int i; for (i = 0; i < 7; ++i) table._M_dayname[i] = <API key>(time, i); for (i = 0; i < 7; ++i) table._M_dayname[i+7] = <API key>(time, i); for (i = 0; i < 12; ++i) table._M_monthname[i] = <API key>(time, i); for (i = 0; i < 12; ++i) table._M_monthname[i+12] = <API key>(time, i); table._M_am_pm[0] = _Locale_am_str(time); table._M_am_pm[1] = _Locale_pm_str(time); _Init_timeinfo_base(table, time); } #ifndef _STLP_NO_WCHAR_T static void _Init_timeinfo(_WTime_Info& table, _Locale_time * time) { wchar_t buf[128]; int i; for (i = 0; i < 7; ++i) table._M_dayname[i] = <API key>(time, i, <API key>(buf)); for (i = 0; i < 7; ++i) table._M_dayname[i+7] = <API key>(time, i, <API key>(buf)); for (i = 0; i < 12; ++i) table._M_monthname[i] = <API key>(time, i, <API key>(buf)); for (i = 0; i < 12; ++i) table._M_monthname[i+12] = <API key>(time, i, <API key>(buf)); table._M_am_pm[0] = _WLocale_am_str(time, <API key>(buf)); table._M_am_pm[1] = _WLocale_pm_str(time, <API key>(buf)); _Init_timeinfo_base(table, time); } #endif template <class _Ch, class _TimeInfo> void __subformat(<API key>(_Ch) &buf, const ctype<_Ch>& ct, const string& format, const _TimeInfo& table, const tm* t) { const char * cp = format.data(); const char * cp_end = cp + format.size(); while (cp != cp_end) { if (*cp == '%') { char mod = 0; ++cp; if (*cp == ' mod = *cp; ++cp; } <API key>(buf, ct, *cp++, mod, table, t); } else buf.append(1, *cp++); } } static void __append(__iostring &buf, const string& name) { buf.append(name.data(), name.data() + name.size()); } static void __append(__iowstring &buf, const wstring& name) { buf.append(name.data(), name.data() + name.size()); } static void __append(__iostring &buf, char *first, char *last, const ctype<char>& ) { buf.append(first, last); } static void __append(__iowstring &buf, char *first, char *last, const ctype<wchar_t>& ct) { wchar_t _wbuf[64]; ct.widen(first, last, _wbuf); buf.append(_wbuf, _wbuf + (last - first)); } #define __hour12(hour) \ (((hour) % 12 == 0) ? (12) : (hour) % 12) #if !defined (<API key>) # define _STLP_SPRINTF sprintf #else # define _STLP_SPRINTF sprintf_s #endif template <class _Ch, class _TimeInfo> void _STLP_CALL <API key>(<API key>(_Ch) &buf, const ctype<_Ch>& ct, char format, char modifier, const _TimeInfo& table, const tm* t) { char _buf[64]; char *_bend; switch (format) { case 'a': __append(buf, table._M_dayname[t->tm_wday]); break; case 'A': __append(buf, table._M_dayname[t->tm_wday + 7]); break; case 'b': __append(buf, table._M_monthname[t->tm_mon]); break; case 'B': __append(buf, table._M_monthname[t->tm_mon + 12]); break; case 'c': __subformat(buf, ct, (modifier != '#') ? table._M_date_time_format : table.<API key>, table, t); break; case 'd': _STLP_SPRINTF(_buf, (modifier != '#') ? "%.2ld" : "%ld", (long)t->tm_mday); __append(buf, _buf, ((long)t->tm_mday < 10L && modifier == '#') ? _buf + 1 : _buf + 2, ct); break; case 'e': _STLP_SPRINTF(_buf, "%2ld", (long)t->tm_mday); __append(buf, _buf, _buf + 2, ct); break; case 'H': _STLP_SPRINTF(_buf, (modifier != '#') ? "%.2ld" : "%ld", (long)t->tm_hour); __append(buf, _buf, ((long)t->tm_hour < 10L && modifier == '#') ? _buf + 1 : _buf + 2, ct); break; case 'I': _STLP_SPRINTF(_buf, (modifier != '#') ? "%.2ld" : "%ld", (long)__hour12(t->tm_hour)); __append(buf, _buf, ((long)__hour12(t->tm_hour) < 10L && modifier == '#') ? _buf + 1 : _buf + 2, ct); break; case 'j': _bend = __write_integer(_buf, 0, (long)((long)t->tm_yday + 1)); __append(buf, _buf, _bend, ct); break; case 'm': _STLP_SPRINTF(_buf, (modifier != '#') ? "%.2ld" : "%ld", (long)t->tm_mon + 1); __append(buf, _buf, ((long)(t->tm_mon + 1) < 10L && modifier == '#') ? _buf + 1 : _buf + 2, ct); break; case 'M': _STLP_SPRINTF(_buf, (modifier != '#') ? "%.2ld" : "%ld", (long)t->tm_min); __append(buf, _buf, ((long)t->tm_min < 10L && modifier == '#') ? _buf + 1 : _buf + 2, ct); break; case 'p': __append(buf, table._M_am_pm[t->tm_hour / 12]); break; case 'S': // pad with zeros _STLP_SPRINTF(_buf, (modifier != '#') ? "%.2ld" : "%ld", (long)t->tm_sec); __append(buf, _buf, ((long)t->tm_sec < 10L && modifier == '#') ? _buf + 1 : _buf + 2, ct); break; case 'U': _bend = __write_integer(_buf, 0, long((t->tm_yday - t->tm_wday + 7) / 7)); __append(buf, _buf, _bend, ct); break; case 'w': _bend = __write_integer(_buf, 0, (long)t->tm_wday); __append(buf, _buf, _bend, ct); break; case 'W': _bend = __write_integer(_buf, 0, (long)(t->tm_wday == 0 ? (t->tm_yday + 1) / 7 : (t->tm_yday + 8 - t->tm_wday) / 7)); __append(buf, _buf, _bend, ct); break; case'x': __subformat(buf, ct, (modifier != '#') ? table._M_date_format : table._M_long_date_format, table, t); break; case 'X': __subformat(buf, ct, table._M_time_format, table, t); break; case 'y': _bend = __write_integer(_buf, 0, (long)((long)(t->tm_year + 1900) % 100)); __append(buf, _buf, _bend, ct); break; case 'Y': _bend = __write_integer(_buf, 0, (long)((long)t->tm_year + 1900)); __append(buf, _buf, _bend, ct); break; case '%': buf.append(1, ct.widen('%')); break; default: break; } } void _STLP_CALL <API key>(__iostring &buf, const ctype<char>& ct, char format, char modifier, const _Time_Info& table, const tm* t) { <API key>(buf, ct, format, modifier, table, t); } void _STLP_CALL <API key>(__iowstring &buf, const ctype<wchar_t>& ct, char format, char modifier, const _WTime_Info& table, const tm* t) { <API key>(buf, ct, format, modifier, table, t); } static time_base::dateorder __get_date_order(_Locale_time* time) { const char * fmt = _Locale_d_fmt(time); char first, second, third; while (*fmt != 0 && *fmt != '%') ++fmt; if (*fmt == 0) return time_base::no_order; first = *++fmt; while (*fmt != 0 && *fmt != '%') ++fmt; if (*fmt == 0) return time_base::no_order; second = *++fmt; while (*fmt != 0 && *fmt != '%') ++fmt; if (*fmt == 0) return time_base::no_order; third = *++fmt; switch (first) { case 'd': return (second == 'm' && third == 'y') ? time_base::dmy : time_base::no_order; case 'm': return (second == 'd' && third == 'y') ? time_base::mdy : time_base::no_order; case 'y': switch (second) { case 'd': return third == 'm' ? time_base::ydm : time_base::no_order; case 'm': return third == 'd' ? time_base::ymd : time_base::no_order; default: return time_base::no_order; } default: return time_base::no_order; } } time_init<char>::time_init() : _M_dateorder(time_base::no_order) { _Init_timeinfo(_M_timeinfo); } time_init<char>::time_init(const char* __name) { if (!__name) locale::<API key>(); int __err_code; char buf[<API key>]; _Locale_time *__time = __acquire_time(__name, buf, 0, &__err_code); if (!__time) locale::<API key>(__err_code, __name, "time"); _Init_timeinfo(this->_M_timeinfo, __time); _M_dateorder = __get_date_order(__time); __release_time(__time); } time_init<char>::time_init(_Locale_time *__time) { _Init_timeinfo(this->_M_timeinfo, __time); _M_dateorder = __get_date_order(__time); } #ifndef _STLP_NO_WCHAR_T time_init<wchar_t>::time_init() : _M_dateorder(time_base::no_order) { _Init_timeinfo(_M_timeinfo); } time_init<wchar_t>::time_init(const char* __name) { if (!__name) locale::<API key>(); int __err_code; char buf[<API key>]; _Locale_time *__time = __acquire_time(__name, buf, 0, &__err_code); if (!__time) locale::<API key>(__err_code, __name, "time"); _Init_timeinfo(this->_M_timeinfo, __time); _M_dateorder = __get_date_order(__time); __release_time(__time); } time_init<wchar_t>::time_init(_Locale_time *__time) { _Init_timeinfo(this->_M_timeinfo, __time); _M_dateorder = __get_date_order(__time); } #endif <API key> #if !defined (<API key>) template class time_get<char, istreambuf_iterator<char, char_traits<char> > >; template class time_put<char, ostreambuf_iterator<char, char_traits<char> > >; # ifndef _STLP_NO_WCHAR_T template class time_get<wchar_t, istreambuf_iterator<wchar_t, char_traits<wchar_t> > >; template class time_put<wchar_t, ostreambuf_iterator<wchar_t, char_traits<wchar_t> > >; # endif #endif _STLP_END_NAMESPACE
<section class="m-list m-list--article"> <h4>Other Articles</h4> {{> article-list}} </section>
interface IHttpRequest { send(options: HttpRequestOptions, onSuccessCallback: () => void, onErrorCallback: (statusCode: number) => void); } class HttpRequest implements IHttpRequest { send(options: HttpRequestOptions, onSuccessCallback:()=>void, onErrorCallback:(statusCode:number)=>void) { var request = new XMLHttpRequest(); request.onerror = function(e) { onErrorCallback(0); } request.onload = function(e) { if (request.status == 200) { // success! onSuccessCallback(); } else { onErrorCallback(request.status); } } request.open(options.method, options.url, true); for (var header in options.headers) { request.setRequestHeader(header, options.headers[header]); } if (options.isOnline) { request.send(JSON.stringify(options.data)); } else { onErrorCallback(-1); } } } class HttpRequestOptions { method: string; url: string; headers: any; data: any; isOnline: boolean; }
package pl.lubcode.<API key>.<API key>; import java.io.IOException; import java.util.<API key>; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import pl.lubcode.<API key>.<API key>.Account; import pl.lubcode.<API key>.<API key>.Assessment; import pl.lubcode.<API key>.<API key>.Identificator; abstract class ApplicationServlet extends HttpServlet { private static final long serialVersionUID = -<API key>; private final ViewFactory viewFactory; ApplicationServlet (ViewFactory viewFactory) { this.viewFactory = viewFactory; } ApplicationServlet ( ) { this(ViewFactory.getInstance( )); } protected final ViewFactory getViewFactory ( ) { return this.viewFactory; } protected final Account getUserAccount (HttpServletRequest request) { Account loggedInUser = null; HttpSession session = request.getSession(false); if (session == null) { return null; } try { loggedInUser = Account.getInstance(Identificator.<Account>valueOf((String)session.getAttribute(Account.class.getName( ) + ".id"))); } catch (<API key> e) { return null; } catch (<API key> e) { return null; } return loggedInUser; } protected final Assessment <API key> (HttpServletRequest request) { Assessment currentAssessment = null; HttpSession session = request.getSession(false); if (session == null) { return null; } try { currentAssessment = Assessment.getInstance(Identificator.<Assessment>valueOf((String)session.getAttribute(Assessment.class.getName( ) + ".id"))); } catch (<API key> e) { return null; } catch (<API key> e) { return null; } return currentAssessment; } @Override public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { getViewFactory( ).process(request, response); } @Override public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }
#pragma once #ifndef _JOBJECT_H #define _JOBJECT_H 1 #ifndef <API key> #ifndef _UNORDERED_MAP_ #include <unordered_map> #endif #endif #ifndef _JVALUE_H #include "jvalue.h" #endif #ifndef _JBASE_H #include "jbase.h" #endif namespace std { namespace json { class jobject : public jbase { private: unordered_map<string, jvalue> _fields; public: bool is_null(); bool contains(const string &key); void add(const string &key, const jvalue &value); void remove(const string &key); bool operator==(const nullptr_t &); bool operator!=(const nullptr_t &); jvalue &operator[](const string &key); protected: virtual string &load(string json); public: virtual string to_string(); }; } } #endif
package com.drillster.api2.general; import java.util.Date; public class Session implements Response { private String id; private Date created; private Location location; private String ipAddress; private String userAgent; private String locale; private Login login; public Session setId(String id) { this.id = id; return this; } public Session setCreated(Date created) { this.created = created; return this; } public Session setLocation(Location location) { this.location = location; return this; } public Session setIpAddress(String ipAddress) { this.ipAddress = ipAddress; return this; } public Session setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } public Session setLocale(String locale) { this.locale = locale; return this; } public Session setLogin(Login login) { this.login = login; return this; } public String getId() { return this.id; } public Date getCreated() { return this.created; } public Location getLocation() { return this.location; } public String getIpAddress() { return this.ipAddress; } public String getUserAgent() { return this.userAgent; } public String getLocale() { return this.locale; } public Login getLogin() { return this.login; } }
package com.ideaknow.api.client.forms.tpv; import android.os.Parcel; import android.os.Parcelable; import com.ideaknow.api.client.model.CompanyModel; import com.ideaknow.api.client.model.tpv.MerchantModel; public class TerminalListForm implements Parcelable { private CompanyModel company; private MerchantModel merchant; public TerminalListForm() { } public CompanyModel getCompany() { return company; } public void setCompany(CompanyModel company) { this.company = company; } public MerchantModel getMerchant() { return merchant; } public void setMerchant(MerchantModel merchant) { this.merchant = merchant; } @Override public String toString() { return "TerminalListForm{" + "company=" + company + ", merchant=" + merchant + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(this.company, 0); dest.writeParcelable(this.merchant, 0); } private TerminalListForm(Parcel in) { this.company = in.readParcelable(CompanyModel.class.getClassLoader()); this.merchant = in.readParcelable(MerchantModel.class.getClassLoader()); } public static final Parcelable.Creator<TerminalListForm> CREATOR = new Parcelable.Creator<TerminalListForm>() { public TerminalListForm createFromParcel(Parcel source) { return new TerminalListForm(source); } public TerminalListForm[] newArray(int size) { return new TerminalListForm[size]; } }; }
import React, {Component, PropTypes} from 'react' export default class SQLEditor extends Component { constructor(props) { super(props) this.updateSQL = this.updateSQL.bind(this) } updateSQL() { this.props.updateSQL(this.refs.sql.value); } render() { const {sql} = this.props return ( <div> <textarea ref="sql" defaultValue={sql} autoComplete="off" className="textEditor"/> <button className='ui button primary' onClick={this.updateSQL}>Update</button> </div> ) } }
require 'rails_helper' RSpec.describe ErrorsController, type: :controller do describe "GET #error_404" do it "returns http success" do get :error_404 expect(response).to have_http_status(404) end end describe "GET #error_500" do it "returns http success" do get :error_500 expect(response).to have_http_status(500) end end end
package net.cal.sjforms; import java.util.Arrays; public class Basics { private static final Field<Integer> LIMIT_FIELD = Field.intField("limit").withDefault(10).clampMin(0).clampMax(100); public static void main(String[] args) { for (String input : Arrays.asList("0", "50", "-10", "1000", "x", null)) { String output; try { Integer out = LIMIT_FIELD.validate(input); output = out == null ? null : out.toString(); } catch (ValidationException e) { output = "ERROR: " + e.getMessage(); } System.out.println("Validation for '" + input + "' = " + output); } } }
package android.matija.com.nerdlauncher; import android.content.Context; import android.support.test.<API key>; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; @RunWith(AndroidJUnit4.class) public class <API key> { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = <API key>.getTargetContext(); assertEquals("android.matija.com.nerdlauncher", appContext.getPackageName()); } }
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-forms', templateUrl: './forms.component.html', styleUrls: ['./forms.component.css'] }) export class FormsComponent implements OnInit { constructor() { } ngOnInit() { } }
package view.experiment.folderWatch; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import model.measurement.Diffusivity; public class JTDiffLabelSet extends JPanel { private static final long serialVersionUID = -<API key>; final private JPanel argumentPanel = new JPanel(); final private JLabel argumentLabel = new JLabel("Здесь будет угол"); final private JPanel kappaPanel = new JPanel(); final private JLabel kappaLabel = new JLabel("Здесь будет каппа"); final private JPanel amplitudePanel = new JPanel(); final private JLabel amplitudeLabel = new JLabel("Здесь будет амплитуда сигнала"); final private JPanel diffusivityPanel = new JPanel(); final private JLabel diffusivityLabel = new JLabel("Здесь будет температуропроводность"); TitledBorder border = new TitledBorder("Канал неизвестный"); private int channelNumber; public JTDiffLabelSet(int channelNumber) { super(new GridLayout(2, 2)); this.channelNumber = channelNumber; border.setTitle("Канал №" + channelNumber); argumentPanel.setBorder(BorderFactory.createTitledBorder("Фаза")); argumentPanel.add(argumentLabel); kappaPanel.setBorder(BorderFactory.createTitledBorder("kappa")); kappaPanel.add(kappaLabel); amplitudePanel.setBorder(BorderFactory.createTitledBorder("Амплитуда сигнала")); amplitudePanel.add(amplitudeLabel); diffusivityPanel.setBorder(BorderFactory.createTitledBorder("Температуропроводность")); diffusivityPanel.add(diffusivityLabel); setBorder(border); add(argumentPanel); add(kappaPanel); add(amplitudePanel); add(diffusivityPanel); } public void updateValues(Diffusivity tDiffus) { if (tDiffus == null) { argumentLabel.setText("Фаза неизвестна"); kappaLabel.setText("kappa неизвестна"); amplitudeLabel.setText("Амплитуда неизвестна"); diffusivityLabel.setText("Температуропроводность неизвестна"); } else { argumentLabel.setText(String.format("%+.3f", tDiffus.phase)); kappaLabel.setText(String.format("%+.3f", tDiffus.kappa)); amplitudeLabel.setText(String.format("%.0f", tDiffus.amplitude)); diffusivityLabel.setText(String.format("%.3e", tDiffus.diffusivity)); border.setTitle("Канал №" + tDiffus.channelNumber); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + channelNumber; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JTDiffLabelSet other = (JTDiffLabelSet) obj; if (channelNumber != other.channelNumber) return false; return true; } }
The [change log](https://github.com/richardschneider/bridge/releases) is automatically produced with the help of [semantic-release](https://github.com/semantic-release/semantic-release).
//= require_self //= require_tree /grails/templates/directives 'use strict'; /* @ngInject */ function <API key>($scope) { $scope.sort = {sort: undefined, order: undefined}; this.setSort = function(sort) { $scope.sort = sort; }; this.getSort = function() { return $scope.sort; }; } function sortHeader() { return { restrict: 'EA', replace: false, require: 'ngModel', scope: { onSort: '&' }, link: function($scope, $element, $attrs, ngModel) { $scope.$watch('sort', function() { ngModel.$setViewValue($scope.sort); if ($scope.onSort && $scope.sort.sort) { $scope.onSort(); } }); }, controller: '<API key>' } } function sortableColumn() { return { restrict: 'EA', replace: true, scope: { title: '@', property: '@' }, require: '^sortHeader', link: function($scope, $element, $attrs, sortHeader) { $scope.order = "desc"; $scope.isActive = function() { return (sortHeader.getSort().sort === $scope.property); }; $scope.sort = function() { $scope.order = ($scope.order == "asc") ? "desc" : "asc"; sortHeader.setSort({sort: $scope.property, order: $scope.order}); } }, templateUrl: 'sortable-column.html' } } angular.module('grails.directives.sort', []) .controller('<API key>', <API key>) .directive('sortHeader', sortHeader) .directive('sortableColumn', sortableColumn);
<?php //function to validate the email address //returns false if email is invalid function checkEmail($email){ if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){ return FALSE; } list($Username, $Domain) = split("@",$email); if(@getmxrr($Domain, $MXHost)){ return TRUE; } else { if(@fsockopen($Domain, 25, $errno, $errstr, 30)){ return TRUE; } else { return FALSE; } } } //response array with status code and message $response_array = array(); //validate the post form //check the name field if(empty($_POST['f_name'])){ //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Looks like you forgot your first name. Please try that again.'; } elseif(empty($_POST['l_name'])){ //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Looks like you forgot your last name. Please try that again.'; //check the email field } elseif(!checkEmail($_POST['email'])) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Looks like you forgot your email address. Please try that again.'; //check the message field } elseif(empty($_POST['message'])) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Looks like you forgot to type a message.'; //check the phone field } elseif(empty($_POST['phone'])) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Looks like you forgot to leave a phone number.'; //form validated. send email } else { //send the email $to = "roger@wulffelectricinc.com"; $subject = "Web Contact Form"; $message = $_POST['f_name'] . " " . $_POST['l_name'] . " sent you a message\n\n"; $message .= "Details: " . $_POST['message']; $message .= "\n\n How to reach them: " . $_POST['email'] . " or " . $_POST['phone']; mail($to,$subject,$message); //set the response $response_array['status'] = 'success'; $response_array['message'] = 'Message sent!'; } echo json_encode($response_array); ?>
# -*- coding: utf-8 -*- from app import app import os if __name__ == "__main__": port = int(os.environ.get('PORT', 33507)) app.run(port=port, debug = True)
define({ "root": { "attributes": { "title": "Title", "backupDatabase": "Backup Database", "restoreDatabase": "Restore Database", "domain": "Base Url" }, }, "de": true });
<?php // Custom functions by TwoWay /* This function attaches the image to the post in the database, add it to functions.php */
<textarea class="{{ $field['toolbar'] }}" data-action="{{ url('/'.$options->prefix) }}" name="{{ $name }}">{!! $value !!}</textarea>
maintainer "Josh Toft" maintainer_email "joshtoft@gmail.com" license "Apache 2.0" description "Installs/Configures virtualbox" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "0.0.1" %w( dmg ).each do |cp| depends cp end
package ClientInterfaces; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.<API key>; import javax.swing.JComboBox; import javax.swing.ComboBoxModel; import java.sql.*; import MainInterfaces.DBAccess; import Mundo.Ticket; import Mundo.Event; /** * * @author Nicolas */ public class BoughtTickets extends javax.swing.JFrame { /** * Creates new form BoughtTickets */ public BoughtTickets() { initComponents(); setVisible(true); //traer las categorias disponibles al comboBox try{ ResultSet rs=DBAccess.consultar(Ticket.buscarCategorias()); String[]array= DBAccess.rsToArray(rs); jCBCategoria.setModel(new <API key>(array)); }catch(Exception e){ JOptionPane.showMessageDialog(null,e.getMessage(),"Mensaje de Error",JOptionPane.ERROR_MESSAGE); } jCBCiudad.setEnabled(false); jCBEvento.setEnabled(false); jCBFecha.setEnabled(false); jCBDireccion.setEnabled(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); Salir = new javax.swing.JButton(); jCBCategoria = new javax.swing.JComboBox<>(); More = new javax.swing.JButton(); jCBEvento = new javax.swing.JComboBox<>(); jLabel1 = new javax.swing.JLabel(); jCBFecha = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); jTBoletas = new javax.swing.JTable(); jLabel4 = new javax.swing.JLabel(); jCBCiudad = new javax.swing.JComboBox<>(); jLabel6 = new javax.swing.JLabel(); jCBDireccion = new javax.swing.JComboBox<>(); <API key>(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel2.setText("Cuidad"); jLabel3.setText("Nombre del Evento"); jLabel5.setText("Fecha del Evento"); Salir.setText("Atrás"); Salir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); jCBCategoria.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); More.setText("Más Informacion"); More.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { MoreActionPerformed(evt); } }); jCBEvento.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setText("Tickets Comprados"); jCBFecha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); jTBoletas.<API key>(true); jTBoletas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Tipo de Boleta", "Precio" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.Short.class }; boolean[] canEdit = new boolean [] { false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTBoletas.setRowHeight(18); jScrollPane1.setViewportView(jTBoletas); jLabel4.setText("Categoria del Evento"); jCBCiudad.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); jLabel6.setText("Dirección"); jCBDireccion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.<API key>() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.<API key>() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.<API key>() .addGap(17, 17, 17) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel6)) .addGap(1, 1, 1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.<API key>() .addComponent(Salir) .addGap(28, 28, 28) .addComponent(More) .addGap(51, 51, 51)) .addGroup(layout.<API key>() .addGap(46, 46, 46) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.<API key>() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jCBEvento, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jCBCategoria, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jCBFecha, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jCBCiudad, 0, 217, Short.MAX_VALUE)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jCBDireccion, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))) .addGap(37, 37, 37)) .addGroup(layout.<API key>() .addGap(102, 102, 102) .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.<API key>() .addGap(25, 25, 25) .addComponent(jLabel1) .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCBCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCBCiudad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCBEvento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCBFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jCBDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Salir, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(More, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> dispose(); new ClientMenu(); }//GEN-LAST:<API key> private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> String categoria = (String)jCBCiudad.getSelectedItem(); Event.setCategoria(categoria); try{ ResultSet rs=DBAccess.consultar(Ticket.buscarCiudades()); jCBCiudad.setModel(new <API key>(DBAccess.rsToArray(rs))); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Error: "+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } jCBCiudad.setEnabled(true); jCBEvento.setEnabled(false); jCBFecha.setEnabled(false); jCBDireccion.setEnabled(false); }//GEN-LAST:<API key> private void MoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> dispose(); new EventsMoreInfo(true); }//GEN-LAST:<API key> private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> JComboBox cb = (JComboBox)evt.getSource(); String ciudad = (String)cb.getSelectedItem(); Event.setCiudad(ciudad); try{ ResultSet rs=DBAccess.consultar(Ticket.buscarEventos()); jCBEvento.setModel(new <API key>(DBAccess.rsToArray(rs))); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Error: "+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } jCBEvento.setEnabled(true); jCBFecha.setEnabled(false); jCBDireccion.setEnabled(false); }//GEN-LAST:<API key> private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> JComboBox cb = (JComboBox)evt.getSource(); String evento= (String)cb.getSelectedItem(); Event.setEname(evento); try{ ResultSet rs=DBAccess.consultar(Ticket.buscarFecha()); jCBFecha.setModel(new <API key>(DBAccess.rsToArray(rs)));; }catch(Exception e){ JOptionPane.showMessageDialog(null,"Error: "+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } jCBFecha.setEnabled(true); jCBDireccion.setEnabled(false); }//GEN-LAST:<API key> private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> JComboBox cb = (JComboBox)evt.getSource(); String fecha= (String)cb.getSelectedItem(); Event.setFecha(fecha); try{ ResultSet rs=DBAccess.consultar(Ticket.buscarDireccion()); jCBDireccion = new JComboBox(DBAccess.rsToArray(rs)); }catch(SQLException e) { JOptionPane.showMessageDialog(null,"Error: "+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } jCBDireccion.setEnabled(true); }//GEN-LAST:<API key> private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> JComboBox cb = (JComboBox)evt.getSource(); String direccion = (String)cb.getSelectedItem(); Event.setDireccion(direccion); DefaultTableModel modelo = new DefaultTableModel(); jCBDireccion.setModel((ComboBoxModel<String>) modelo); try{ ResultSet rs=DBAccess.consultar(Ticket.buscarBoletas()); ResultSetMetaData rsMD = rs.getMetaData(); int nColumnas = rsMD.getColumnCount(); while (rs.next()){ Object [] fila = new Object[nColumnas]; // Hay tres columnas en la tabla for (int i=0;i<nColumnas;i++) fila[i] = rs.getObject(i+1); modelo.addRow(fila); } rs=DBAccess.consultar(Event.buscarIdEvent()); if (rs.next()){ Event.setEvent_id(rs.getString(1)); System.out.println("id_event cambío a: "+Event.getEvent_id()); } }catch(SQLException e){ e.printStackTrace(); JOptionPane.showMessageDialog(null,"Error: "+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:<API key> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton More; private javax.swing.JButton Salir; private javax.swing.JComboBox<String> jCBCategoria; private javax.swing.JComboBox<String> jCBCiudad; private javax.swing.JComboBox<String> jCBDireccion; private javax.swing.JComboBox<String> jCBEvento; private javax.swing.JComboBox<String> jCBFecha; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTBoletas; private javax.persistence.Query query1; // End of variables declaration//GEN-END:variables }
// Template Source: Enum.java.tt package com.microsoft.graph.models; /** * The Enum Attendee Type. */ public enum AttendeeType { /** * required */ REQUIRED, /** * optional */ OPTIONAL, /** * resource */ RESOURCE, /** * For AttendeeType values that were not expected from the service */ UNEXPECTED_VALUE }
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-10-29 18:57:52 # @Author : jingray (lionel_jing@163.com) # @Version : $Id$ def zeroes(height, width): """ Creates a matrix of zeroes. """ g = [[0.0 for _ in range(width)] for __ in range(height)] return Matrix(g) class Matrix(object): # Initializes a matrix from a 2D grid of values # Assumes and initializes a grid-specified number of rows and columns def __init__(self, grid): self.grid = grid self.rows = len(grid) self.cols = len(grid[0]) # Overloading the multiplication operator def __mul__(self, other): ''' self and other are Matrix objects. This function check the dimensions of the two matrices, multiplies them according to the rules of linear algebra, and returns a new matrix.''' if(self.cols == other.rows): # Then the dimensions match for multiplication! # Create a new matrix of zeroes of the appropriate size (self.rows x other.cols) self_times_other = zeroes(self.rows, other.cols) # iterate through the rows of self for i in range(self.rows): # iterate through the columns of other for j in range(other.cols): # iterate through rows of other and sum for k in range(other.rows): # multiply and sum step self_times_other[i][j] += (self[i][k] * other[k][j]) # for debugging #print(' i = ' + str(i) +', j = ' + str(j) + ', k = ' + str(k)) return self_times_other else: print('Invalid matrix dimensions!') print('A_cols = ' + str(self.cols) + ', and B_rows = ' + str(other.rows)) # return [] # Overloading indexing def __getitem__(self, index): return self.grid[index] # Overloading print output def __repr__(self): s = '[' for row in self.grid: s += '[' for item in row: s += str(item) +' ' s += ']\n' s += ']' return s
//>>built define({widgetLabel:"P\u0159ep\u00edn\u00e1n\u00ed navigace",toggle:"P\u0159epnout na posun nebo ot\u00e1\u010den\u00ed ve 3D"});
#!/usr/bin/env python3 # -*- coding: cp1252 -*- """ Launch to orbit (with atmosphere) """ from threading import Thread import krpc from toolkit import ksp from toolkit import launch from toolkit import system from toolkit import warp from vessels import surveyor, stock STAGING_DICT = { "Surveyor 1": surveyor.surveyor1, "Kerbal X": stock.default, } def main(): cx = ksp.connect(name='Trajectory') ksp.set_globals(cx) # system.checkvessel("Surveyor 1") warp.warpday() # setup staging try: staging = STAGING_DICT[SC.active_vessel.name] except KeyError: staging = stock.default stage = Thread(target=staging, args=["Staging", ]) # launch to orbit stage.start() launch.ltoa() system.tts() if __name__ == "__main__": main()
package org.zalando.opentracing.proxy.plugin; import io.opentracing.Span; import io.opentracing.Tracer; import lombok.AllArgsConstructor; import org.apiguardian.api.API; import org.zalando.opentracing.proxy.listen.baggage.BaggageListener; import org.zalando.opentracing.proxy.listen.span.SpanListener; import java.util.Map; import java.util.Optional; import static java.util.Collections.singletonMap; import static org.apiguardian.api.API.Status.EXPERIMENTAL; @API(status = EXPERIMENTAL) @AllArgsConstructor public final class AutoTagging implements SpanListener, BaggageListener { private final Map<String, String> mapping; public AutoTagging(final String key) { this(key, key); } public AutoTagging(final String baggageKey, final String tagKey) { this(singletonMap(baggageKey, tagKey)); } @Override public void onStarted(final Span span) { mapping.forEach((baggageKey, tagKey) -> Optional.ofNullable(span.getBaggageItem(baggageKey)) .ifPresent(value -> span.setTag(tagKey, value))); } @Override public void onBaggage( final Tracer tracer, final Span span, final String key, final String value) { Optional.ofNullable(mapping.get(key)) .ifPresent(tagKey -> span.setTag(tagKey, value)); } }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> int main() { struct winsize ws; ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws); printf("height: %d, width: %d\n", ws.ws_row, ws.ws_col); return EXIT_SUCCESS; }
namespace PoseEstimation { partial class MainForm { <summary> Required designer variable. </summary> private System.ComponentModel.IContainer components = null; <summary> Clean up any resources being used. </summary> <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if ( disposing && ( components != null ) ) { components.Dispose( ); } base.Dispose( disposing ); } #region Windows Form Designer generated code <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent( ) { this.components = new System.ComponentModel.Container( ); this.mainPanel = new System.Windows.Forms.Panel( ); this.groupBox1 = new System.Windows.Forms.GroupBox( ); this.label7 = new System.Windows.Forms.Label( ); this.label6 = new System.Windows.Forms.Label( ); this.label5 = new System.Windows.Forms.Label( ); this.pictureBox = new System.Windows.Forms.PictureBox( ); this.mainMenu = new System.Windows.Forms.MenuStrip( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator( ); this.<API key> = new System.Windows.Forms.ToolStripMenuItem( ); this.openFileDialog = new System.Windows.Forms.OpenFileDialog( ); this.panel1 = new System.Windows.Forms.Panel( ); this.poseGroupBox = new System.Windows.Forms.GroupBox( ); this.alternatePoseButton = new System.Windows.Forms.Button( ); this.bestPoseButton = new System.Windows.Forms.Button( ); this.focalLengthBox = new System.Windows.Forms.TextBox( ); this.focalLengthLabel = new System.Windows.Forms.Label( ); this.copositRadio = new System.Windows.Forms.RadioButton( ); this.positRadio = new System.Windows.Forms.RadioButton( ); this.estimatePostButton = new System.Windows.Forms.Button( ); this.<API key> = new PoseEstimation.MatrixControl( ); this.modelPointsGroupBox = new System.Windows.Forms.GroupBox( ); this.modelPoint4zBox = new System.Windows.Forms.TextBox( ); this.modelPoint4yBox = new System.Windows.Forms.TextBox( ); this.modelPoint4xBox = new System.Windows.Forms.TextBox( ); this.modelPoint3zBox = new System.Windows.Forms.TextBox( ); this.modelPoint3yBox = new System.Windows.Forms.TextBox( ); this.modelPoint3xBox = new System.Windows.Forms.TextBox( ); this.modelPoint2zBox = new System.Windows.Forms.TextBox( ); this.modelPoint2yBox = new System.Windows.Forms.TextBox( ); this.modelPoint2xBox = new System.Windows.Forms.TextBox( ); this.modelPoint1zBox = new System.Windows.Forms.TextBox( ); this.modelPoint1yBox = new System.Windows.Forms.TextBox( ); this.modelPoint1xBox = new System.Windows.Forms.TextBox( ); this.modelPoint4Label = new System.Windows.Forms.Label( ); this.modelPoint1Label = new System.Windows.Forms.Label( ); this.modelPoint3Label = new System.Windows.Forms.Label( ); this.modelPoint2Label = new System.Windows.Forms.Label( ); this.imagePointsGroupBox = new System.Windows.Forms.GroupBox( ); this.<API key> = new System.Windows.Forms.Label( ); this.<API key> = new System.Windows.Forms.Label( ); this.<API key> = new System.Windows.Forms.Label( ); this.<API key> = new System.Windows.Forms.Label( ); this.locate4Button = new System.Windows.Forms.Button( ); this.imagePoint4Box = new System.Windows.Forms.TextBox( ); this.label4 = new System.Windows.Forms.Label( ); this.locate3Button = new System.Windows.Forms.Button( ); this.imagePoint3Box = new System.Windows.Forms.TextBox( ); this.label3 = new System.Windows.Forms.Label( ); this.locate2Button = new System.Windows.Forms.Button( ); this.imagePoint2Box = new System.Windows.Forms.TextBox( ); this.label2 = new System.Windows.Forms.Label( ); this.locate1Button = new System.Windows.Forms.Button( ); this.imagePoint1Box = new System.Windows.Forms.TextBox( ); this.label1 = new System.Windows.Forms.Label( ); this.statusStrip = new System.Windows.Forms.StatusStrip( ); this.statusLabel = new System.Windows.Forms.<API key>( ); this.estimationLabel = new System.Windows.Forms.<API key>( ); this.imageSizeLabel = new System.Windows.Forms.<API key>( ); this.errorProvider = new System.Windows.Forms.ErrorProvider( this.components ); this.toolTip = new System.Windows.Forms.ToolTip( this.components ); this.mainPanel.SuspendLayout( ); this.groupBox1.SuspendLayout( ); ( (System.ComponentModel.ISupportInitialize) ( this.pictureBox ) ).BeginInit( ); this.mainMenu.SuspendLayout( ); this.panel1.SuspendLayout( ); this.poseGroupBox.SuspendLayout( ); this.modelPointsGroupBox.SuspendLayout( ); this.imagePointsGroupBox.SuspendLayout( ); this.statusStrip.SuspendLayout( ); ( (System.ComponentModel.ISupportInitialize) ( this.errorProvider ) ).BeginInit( ); this.SuspendLayout( ); // mainPanel this.mainPanel.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.mainPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.mainPanel.Controls.Add( this.groupBox1 ); this.mainPanel.Controls.Add( this.pictureBox ); this.mainPanel.Location = new System.Drawing.Point( 0, 27 ); this.mainPanel.Name = "mainPanel"; this.mainPanel.Size = new System.Drawing.Size( 974, 478 ); this.mainPanel.TabIndex = 1; // groupBox1 this.groupBox1.Controls.Add( this.label7 ); this.groupBox1.Controls.Add( this.label6 ); this.groupBox1.Controls.Add( this.label5 ); this.groupBox1.ForeColor = System.Drawing.SystemColors.ControlText; this.groupBox1.Location = new System.Drawing.Point( 10, 5 ); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size( 65, 85 ); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Legend"; // label7 this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font( "Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ( (byte) ( 204 ) ) ); this.label7.ForeColor = System.Drawing.Color.Lime; this.label7.Location = new System.Drawing.Point( 10, 60 ); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size( 41, 13 ); this.label7.TabIndex = 2; this.label7.Text = "Z axis"; // label6 this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font( "Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ( (byte) ( 204 ) ) ); this.label6.ForeColor = System.Drawing.Color.Red; this.label6.Location = new System.Drawing.Point( 10, 40 ); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size( 41, 13 ); this.label6.TabIndex = 1; this.label6.Text = "Y axis"; // label5 this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font( "Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ( (byte) ( 204 ) ) ); this.label5.ForeColor = System.Drawing.Color.Blue; this.label5.Location = new System.Drawing.Point( 10, 20 ); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size( 41, 13 ); this.label5.TabIndex = 0; this.label5.Text = "X axis"; // pictureBox this.pictureBox.BackColor = System.Drawing.SystemColors.ControlDark; this.pictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pictureBox.Location = new System.Drawing.Point( 299, 128 ); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size( 320, 240 ); this.pictureBox.TabIndex = 0; this.pictureBox.TabStop = false; this.pictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler( this.<API key> ); this.pictureBox.MouseClick += new System.Windows.Forms.MouseEventHandler( this.<API key> ); this.pictureBox.Paint += new System.Windows.Forms.PaintEventHandler( this.pictureBox_Paint ); // mainMenu this.mainMenu.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.<API key>} ); this.mainMenu.Location = new System.Drawing.Point( 0, 0 ); this.mainMenu.Name = "mainMenu"; this.mainMenu.Size = new System.Drawing.Size( 974, 24 ); this.mainMenu.TabIndex = 0; // <API key> this.<API key>.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.<API key>, this.toolStripMenuItem2, this.<API key>, this.<API key>, this.<API key>, this.<API key>, this.<API key>, this.toolStripMenuItem1, this.<API key>} ); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size( 37, 20 ); this.<API key>.Text = "&File"; // <API key> this.<API key>.Name = "<API key>"; this.<API key>.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O ) ) ); this.<API key>.Size = new System.Drawing.Size( 193, 22 ); this.<API key>.Text = "&Open image"; this.<API key>.Click += new System.EventHandler( this.<API key> ); // toolStripMenuItem2 this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size( 190, 6 ); // <API key> this.<API key>.Name = "<API key>"; this.<API key>.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D1 ) ) ); this.<API key>.Size = new System.Drawing.Size( 193, 22 ); this.<API key>.Tag = "0"; this.<API key>.Text = "Open sample &1"; this.<API key>.Click += new System.EventHandler( this.<API key> ); // <API key> this.<API key>.Name = "<API key>"; this.<API key>.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D2 ) ) ); this.<API key>.Size = new System.Drawing.Size( 193, 22 ); this.<API key>.Tag = "1"; this.<API key>.Text = "Open sample &2"; this.<API key>.Click += new System.EventHandler( this.<API key> ); // <API key> this.<API key>.Name = "<API key>"; this.<API key>.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D3 ) ) ); this.<API key>.Size = new System.Drawing.Size( 193, 22 ); this.<API key>.Tag = "2"; this.<API key>.Text = "Open sample &3"; this.<API key>.Click += new System.EventHandler( this.<API key> ); // <API key> this.<API key>.Name = "<API key>"; this.<API key>.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D4 ) ) ); this.<API key>.Size = new System.Drawing.Size( 193, 22 ); this.<API key>.Tag = "3"; this.<API key>.Text = "Open sample &4"; this.<API key>.Click += new System.EventHandler( this.<API key> ); // <API key> this.<API key>.Name = "<API key>"; this.<API key>.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D5 ) ) ); this.<API key>.Size = new System.Drawing.Size( 193, 22 ); this.<API key>.Tag = "4"; this.<API key>.Text = "Open sample &5"; this.<API key>.Click += new System.EventHandler( this.<API key> ); // toolStripMenuItem1 this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size( 190, 6 ); // <API key> this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size( 193, 22 ); this.<API key>.Text = "E&xit"; this.<API key>.Click += new System.EventHandler( this.<API key> ); // openFileDialog this.openFileDialog.Filter = "Image files (*.jpg, *.bmp, *.png)|*.jpg; *.bmp; *.png"; this.openFileDialog.Title = "Select a image file"; // panel1 this.panel1.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.panel1.Controls.Add( this.poseGroupBox ); this.panel1.Controls.Add( this.modelPointsGroupBox ); this.panel1.Controls.Add( this.imagePointsGroupBox ); this.panel1.Location = new System.Drawing.Point( 0, 511 ); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size( 974, 130 ); this.panel1.TabIndex = 2; // poseGroupBox this.poseGroupBox.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.poseGroupBox.Controls.Add( this.alternatePoseButton ); this.poseGroupBox.Controls.Add( this.bestPoseButton ); this.poseGroupBox.Controls.Add( this.focalLengthBox ); this.poseGroupBox.Controls.Add( this.focalLengthLabel ); this.poseGroupBox.Controls.Add( this.copositRadio ); this.poseGroupBox.Controls.Add( this.positRadio ); this.poseGroupBox.Controls.Add( this.estimatePostButton ); this.poseGroupBox.Controls.Add( this.<API key> ); this.poseGroupBox.Location = new System.Drawing.Point( 530, 0 ); this.poseGroupBox.Name = "poseGroupBox"; this.poseGroupBox.Size = new System.Drawing.Size( 432, 127 ); this.poseGroupBox.TabIndex = 2; this.poseGroupBox.TabStop = false; this.poseGroupBox.Text = "Pose estimation"; // alternatePoseButton this.alternatePoseButton.Location = new System.Drawing.Point( 345, 7 ); this.alternatePoseButton.Name = "alternatePoseButton"; this.alternatePoseButton.Size = new System.Drawing.Size( 20, 20 ); this.alternatePoseButton.TabIndex = 2; this.alternatePoseButton.Text = "&A"; this.toolTip.SetToolTip( this.alternatePoseButton, "Select alternate CoPOSIT estimation" ); this.alternatePoseButton.<API key> = true; this.alternatePoseButton.Click += new System.EventHandler( this.<API key> ); // bestPoseButton this.bestPoseButton.Location = new System.Drawing.Point( 320, 7 ); this.bestPoseButton.Name = "bestPoseButton"; this.bestPoseButton.Size = new System.Drawing.Size( 20, 20 ); this.bestPoseButton.TabIndex = 1; this.bestPoseButton.Text = "&B"; this.toolTip.SetToolTip( this.bestPoseButton, "Select best CoPOSIT estimation" ); this.bestPoseButton.<API key> = true; this.bestPoseButton.Click += new System.EventHandler( this.<API key> ); // focalLengthBox this.focalLengthBox.Location = new System.Drawing.Point( 95, 50 ); this.focalLengthBox.Name = "focalLengthBox"; this.focalLengthBox.Size = new System.Drawing.Size( 85, 20 ); this.focalLengthBox.TabIndex = 4; this.focalLengthBox.Leave += new System.EventHandler( this.<API key> ); // focalLengthLabel this.focalLengthLabel.AutoSize = true; this.focalLengthLabel.Location = new System.Drawing.Point( 10, 53 ); this.focalLengthLabel.Name = "focalLengthLabel"; this.focalLengthLabel.Size = new System.Drawing.Size( 68, 13 ); this.focalLengthLabel.TabIndex = 3; this.focalLengthLabel.Text = "Focal length:"; this.toolTip.SetToolTip( this.focalLengthLabel, "Effective Focal Length" ); // copositRadio this.copositRadio.AutoSize = true; this.copositRadio.Location = new System.Drawing.Point( 80, 23 ); this.copositRadio.Name = "copositRadio"; this.copositRadio.Size = new System.Drawing.Size( 102, 17 ); this.copositRadio.TabIndex = 2; this.copositRadio.TabStop = true; this.copositRadio.Text = "Coplanar POSIT"; this.copositRadio.<API key> = true; this.copositRadio.CheckedChanged += new System.EventHandler( this.<API key> ); // positRadio this.positRadio.AutoSize = true; this.positRadio.Location = new System.Drawing.Point( 10, 23 ); this.positRadio.Name = "positRadio"; this.positRadio.Size = new System.Drawing.Size( 57, 17 ); this.positRadio.TabIndex = 1; this.positRadio.TabStop = true; this.positRadio.Text = "POSIT"; this.positRadio.<API key> = true; // estimatePostButton this.estimatePostButton.Location = new System.Drawing.Point( 105, 93 ); this.estimatePostButton.Name = "estimatePostButton"; this.estimatePostButton.Size = new System.Drawing.Size( 75, 23 ); this.estimatePostButton.TabIndex = 0; this.estimatePostButton.Text = "&Estimate"; this.estimatePostButton.<API key> = true; this.estimatePostButton.Click += new System.EventHandler( this.<API key> ); // <API key> this.<API key>.Location = new System.Drawing.Point( 190, 10 ); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size( 230, 110 ); this.<API key>.TabIndex = 5; this.<API key>.Title = "Estimated transformation"; // modelPointsGroupBox this.modelPointsGroupBox.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) ) ); this.modelPointsGroupBox.Controls.Add( this.modelPoint4zBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint4yBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint4xBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint3zBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint3yBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint3xBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint2zBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint2yBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint2xBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint1zBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint1yBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint1xBox ); this.modelPointsGroupBox.Controls.Add( this.modelPoint4Label ); this.modelPointsGroupBox.Controls.Add( this.modelPoint1Label ); this.modelPointsGroupBox.Controls.Add( this.modelPoint3Label ); this.modelPointsGroupBox.Controls.Add( this.modelPoint2Label ); this.modelPointsGroupBox.Location = new System.Drawing.Point( 250, 0 ); this.modelPointsGroupBox.Name = "modelPointsGroupBox"; this.modelPointsGroupBox.Size = new System.Drawing.Size( 270, 127 ); this.modelPointsGroupBox.TabIndex = 1; this.modelPointsGroupBox.TabStop = false; this.modelPointsGroupBox.Text = "Model coordinates (x, y, z)"; // modelPoint4zBox this.modelPoint4zBox.Location = new System.Drawing.Point( 200, 95 ); this.modelPoint4zBox.Name = "modelPoint4zBox"; this.modelPoint4zBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint4zBox.TabIndex = 15; this.modelPoint4zBox.Tag = "32"; this.modelPoint4zBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint4yBox this.modelPoint4yBox.Location = new System.Drawing.Point( 135, 95 ); this.modelPoint4yBox.Name = "modelPoint4yBox"; this.modelPoint4yBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint4yBox.TabIndex = 14; this.modelPoint4yBox.Tag = "31"; this.modelPoint4yBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint4xBox this.modelPoint4xBox.Location = new System.Drawing.Point( 70, 95 ); this.modelPoint4xBox.Name = "modelPoint4xBox"; this.modelPoint4xBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint4xBox.TabIndex = 13; this.modelPoint4xBox.Tag = "30"; this.modelPoint4xBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint3zBox this.modelPoint3zBox.Location = new System.Drawing.Point( 200, 70 ); this.modelPoint3zBox.Name = "modelPoint3zBox"; this.modelPoint3zBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint3zBox.TabIndex = 11; this.modelPoint3zBox.Tag = "22"; this.modelPoint3zBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint3yBox this.modelPoint3yBox.Location = new System.Drawing.Point( 135, 70 ); this.modelPoint3yBox.Name = "modelPoint3yBox"; this.modelPoint3yBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint3yBox.TabIndex = 10; this.modelPoint3yBox.Tag = "21"; this.modelPoint3yBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint3xBox this.modelPoint3xBox.Location = new System.Drawing.Point( 70, 70 ); this.modelPoint3xBox.Name = "modelPoint3xBox"; this.modelPoint3xBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint3xBox.TabIndex = 9; this.modelPoint3xBox.Tag = "20"; this.modelPoint3xBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint2zBox this.modelPoint2zBox.Location = new System.Drawing.Point( 200, 45 ); this.modelPoint2zBox.Name = "modelPoint2zBox"; this.modelPoint2zBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint2zBox.TabIndex = 7; this.modelPoint2zBox.Tag = "12"; this.modelPoint2zBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint2yBox this.modelPoint2yBox.Location = new System.Drawing.Point( 135, 45 ); this.modelPoint2yBox.Name = "modelPoint2yBox"; this.modelPoint2yBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint2yBox.TabIndex = 6; this.modelPoint2yBox.Tag = "11"; this.modelPoint2yBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint2xBox this.modelPoint2xBox.Location = new System.Drawing.Point( 70, 45 ); this.modelPoint2xBox.Name = "modelPoint2xBox"; this.modelPoint2xBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint2xBox.TabIndex = 5; this.modelPoint2xBox.Tag = "10"; this.modelPoint2xBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint1zBox this.modelPoint1zBox.Location = new System.Drawing.Point( 200, 20 ); this.modelPoint1zBox.Name = "modelPoint1zBox"; this.modelPoint1zBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint1zBox.TabIndex = 3; this.modelPoint1zBox.Tag = "2"; this.modelPoint1zBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint1yBox this.modelPoint1yBox.Location = new System.Drawing.Point( 135, 20 ); this.modelPoint1yBox.Name = "modelPoint1yBox"; this.modelPoint1yBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint1yBox.TabIndex = 2; this.modelPoint1yBox.Tag = "1"; this.modelPoint1yBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint1xBox this.modelPoint1xBox.Location = new System.Drawing.Point( 70, 20 ); this.modelPoint1xBox.Name = "modelPoint1xBox"; this.modelPoint1xBox.Size = new System.Drawing.Size( 60, 20 ); this.modelPoint1xBox.TabIndex = 1; this.modelPoint1xBox.Tag = "0"; this.modelPoint1xBox.Leave += new System.EventHandler( this.modelPointBox_Leave ); // modelPoint4Label this.modelPoint4Label.AutoSize = true; this.modelPoint4Label.Location = new System.Drawing.Point( 10, 98 ); this.modelPoint4Label.Name = "modelPoint4Label"; this.modelPoint4Label.Size = new System.Drawing.Size( 43, 13 ); this.modelPoint4Label.TabIndex = 12; this.modelPoint4Label.Text = "Point 4:"; // modelPoint1Label this.modelPoint1Label.AutoSize = true; this.modelPoint1Label.Location = new System.Drawing.Point( 10, 23 ); this.modelPoint1Label.Name = "modelPoint1Label"; this.modelPoint1Label.Size = new System.Drawing.Size( 43, 13 ); this.modelPoint1Label.TabIndex = 0; this.modelPoint1Label.Text = "Point 1:"; // modelPoint3Label this.modelPoint3Label.AutoSize = true; this.modelPoint3Label.Location = new System.Drawing.Point( 10, 73 ); this.modelPoint3Label.Name = "modelPoint3Label"; this.modelPoint3Label.Size = new System.Drawing.Size( 43, 13 ); this.modelPoint3Label.TabIndex = 8; this.modelPoint3Label.Text = "Point 3:"; // modelPoint2Label this.modelPoint2Label.AutoSize = true; this.modelPoint2Label.Location = new System.Drawing.Point( 10, 48 ); this.modelPoint2Label.Name = "modelPoint2Label"; this.modelPoint2Label.Size = new System.Drawing.Size( 43, 13 ); this.modelPoint2Label.TabIndex = 4; this.modelPoint2Label.Text = "Point 2:"; // imagePointsGroupBox this.imagePointsGroupBox.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) ) ); this.imagePointsGroupBox.Controls.Add( this.<API key> ); this.imagePointsGroupBox.Controls.Add( this.<API key> ); this.imagePointsGroupBox.Controls.Add( this.<API key> ); this.imagePointsGroupBox.Controls.Add( this.<API key> ); this.imagePointsGroupBox.Controls.Add( this.locate4Button ); this.imagePointsGroupBox.Controls.Add( this.imagePoint4Box ); this.imagePointsGroupBox.Controls.Add( this.label4 ); this.imagePointsGroupBox.Controls.Add( this.locate3Button ); this.imagePointsGroupBox.Controls.Add( this.imagePoint3Box ); this.imagePointsGroupBox.Controls.Add( this.label3 ); this.imagePointsGroupBox.Controls.Add( this.locate2Button ); this.imagePointsGroupBox.Controls.Add( this.imagePoint2Box ); this.imagePointsGroupBox.Controls.Add( this.label2 ); this.imagePointsGroupBox.Controls.Add( this.locate1Button ); this.imagePointsGroupBox.Controls.Add( this.imagePoint1Box ); this.imagePointsGroupBox.Controls.Add( this.label1 ); this.imagePointsGroupBox.Location = new System.Drawing.Point( 10, 0 ); this.imagePointsGroupBox.Name = "imagePointsGroupBox"; this.imagePointsGroupBox.Size = new System.Drawing.Size( 230, 127 ); this.imagePointsGroupBox.TabIndex = 0; this.imagePointsGroupBox.TabStop = false; this.imagePointsGroupBox.Text = "Image coordinates (x, y)"; // <API key> this.<API key>.BackColor = System.Drawing.Color.Black; this.<API key>.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.<API key>.Location = new System.Drawing.Point( 55, 115 ); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size( 75, 4 ); this.<API key>.TabIndex = 20; // <API key> this.<API key>.BackColor = System.Drawing.Color.Black; this.<API key>.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.<API key>.Location = new System.Drawing.Point( 55, 90 ); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size( 75, 4 ); this.<API key>.TabIndex = 19; // <API key> this.<API key>.BackColor = System.Drawing.Color.Black; this.<API key>.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.<API key>.Location = new System.Drawing.Point( 55, 65 ); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size( 75, 4 ); this.<API key>.TabIndex = 18; // <API key> this.<API key>.BackColor = System.Drawing.Color.Black; this.<API key>.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.<API key>.Location = new System.Drawing.Point( 55, 40 ); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size( 75, 4 ); this.<API key>.TabIndex = 17; // locate4Button this.locate4Button.Location = new System.Drawing.Point( 140, 94 ); this.locate4Button.Name = "locate4Button"; this.locate4Button.Size = new System.Drawing.Size( 75, 23 ); this.locate4Button.TabIndex = 11; this.locate4Button.Tag = "3"; this.locate4Button.Text = "Locate &4th"; this.locate4Button.<API key> = true; this.locate4Button.Click += new System.EventHandler( this.<API key> ); // imagePoint4Box this.imagePoint4Box.Location = new System.Drawing.Point( 55, 95 ); this.imagePoint4Box.Name = "imagePoint4Box"; this.imagePoint4Box.ReadOnly = true; this.imagePoint4Box.Size = new System.Drawing.Size( 75, 20 ); this.imagePoint4Box.TabIndex = 10; // label4 this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point( 10, 98 ); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size( 43, 13 ); this.label4.TabIndex = 9; this.label4.Text = "Point 4:"; // locate3Button this.locate3Button.Location = new System.Drawing.Point( 140, 69 ); this.locate3Button.Name = "locate3Button"; this.locate3Button.Size = new System.Drawing.Size( 75, 23 ); this.locate3Button.TabIndex = 8; this.locate3Button.Tag = "2"; this.locate3Button.Text = "Locate &3rd"; this.locate3Button.<API key> = true; this.locate3Button.Click += new System.EventHandler( this.<API key> ); // imagePoint3Box this.imagePoint3Box.Location = new System.Drawing.Point( 55, 70 ); this.imagePoint3Box.Name = "imagePoint3Box"; this.imagePoint3Box.ReadOnly = true; this.imagePoint3Box.Size = new System.Drawing.Size( 75, 20 ); this.imagePoint3Box.TabIndex = 7; // label3 this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point( 10, 73 ); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size( 43, 13 ); this.label3.TabIndex = 6; this.label3.Text = "Point 3:"; // locate2Button this.locate2Button.Location = new System.Drawing.Point( 140, 44 ); this.locate2Button.Name = "locate2Button"; this.locate2Button.Size = new System.Drawing.Size( 75, 23 ); this.locate2Button.TabIndex = 5; this.locate2Button.Tag = "1"; this.locate2Button.Text = "Locate &2nd"; this.locate2Button.<API key> = true; this.locate2Button.Click += new System.EventHandler( this.<API key> ); // imagePoint2Box this.imagePoint2Box.Location = new System.Drawing.Point( 55, 45 ); this.imagePoint2Box.Name = "imagePoint2Box"; this.imagePoint2Box.ReadOnly = true; this.imagePoint2Box.Size = new System.Drawing.Size( 75, 20 ); this.imagePoint2Box.TabIndex = 4; // label2 this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point( 10, 48 ); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size( 43, 13 ); this.label2.TabIndex = 3; this.label2.Text = "Point 2:"; // locate1Button this.locate1Button.Location = new System.Drawing.Point( 140, 19 ); this.locate1Button.Name = "locate1Button"; this.locate1Button.Size = new System.Drawing.Size( 75, 23 ); this.locate1Button.TabIndex = 2; this.locate1Button.Tag = "0"; this.locate1Button.Text = "Locate &1st"; this.locate1Button.<API key> = true; this.locate1Button.Click += new System.EventHandler( this.<API key> ); // imagePoint1Box this.imagePoint1Box.Location = new System.Drawing.Point( 55, 20 ); this.imagePoint1Box.Name = "imagePoint1Box"; this.imagePoint1Box.ReadOnly = true; this.imagePoint1Box.Size = new System.Drawing.Size( 75, 20 ); this.imagePoint1Box.TabIndex = 1; // label1 this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point( 10, 23 ); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size( 43, 13 ); this.label1.TabIndex = 0; this.label1.Text = "Point 1:"; // statusStrip this.statusStrip.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.statusLabel, this.estimationLabel, this.imageSizeLabel} ); this.statusStrip.Location = new System.Drawing.Point( 0, 644 ); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size( 974, 22 ); this.statusStrip.TabIndex = 3; // statusLabel this.statusLabel.AutoSize = false; this.statusLabel.BorderSides = ( (System.Windows.Forms.<API key>) ( ( ( ( System.Windows.Forms.<API key>.Left | System.Windows.Forms.<API key>.Top ) | System.Windows.Forms.<API key>.Right ) | System.Windows.Forms.<API key>.Bottom ) ) ); this.statusLabel.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenInner; this.statusLabel.Name = "statusLabel"; this.statusLabel.Size = new System.Drawing.Size( 300, 17 ); this.statusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // estimationLabel this.estimationLabel.AutoSize = false; this.estimationLabel.BorderSides = ( (System.Windows.Forms.<API key>) ( ( ( ( System.Windows.Forms.<API key>.Left | System.Windows.Forms.<API key>.Top ) | System.Windows.Forms.<API key>.Right ) | System.Windows.Forms.<API key>.Bottom ) ) ); this.estimationLabel.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenInner; this.estimationLabel.Name = "estimationLabel"; this.estimationLabel.Size = new System.Drawing.Size( 539, 17 ); this.estimationLabel.Spring = true; this.estimationLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // imageSizeLabel this.imageSizeLabel.AutoSize = false; this.imageSizeLabel.BorderSides = ( (System.Windows.Forms.<API key>) ( ( ( ( System.Windows.Forms.<API key>.Left | System.Windows.Forms.<API key>.Top ) | System.Windows.Forms.<API key>.Right ) | System.Windows.Forms.<API key>.Bottom ) ) ); this.imageSizeLabel.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenInner; this.imageSizeLabel.Name = "imageSizeLabel"; this.imageSizeLabel.Size = new System.Drawing.Size( 120, 17 ); this.imageSizeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // errorProvider this.errorProvider.ContainerControl = this; // toolTip this.toolTip.AutoPopDelay = 5000; this.toolTip.InitialDelay = 100; this.toolTip.ReshowDelay = 100; // MainForm this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 974, 666 ); this.Controls.Add( this.statusStrip ); this.Controls.Add( this.panel1 ); this.Controls.Add( this.mainPanel ); this.Controls.Add( this.mainMenu ); this.MainMenuStrip = this.mainMenu; this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Pose Estimation"; this.Resize += new System.EventHandler( this.MainForm_Resize ); this.mainPanel.ResumeLayout( false ); this.groupBox1.ResumeLayout( false ); this.groupBox1.PerformLayout( ); ( (System.ComponentModel.ISupportInitialize) ( this.pictureBox ) ).EndInit( ); this.mainMenu.ResumeLayout( false ); this.mainMenu.PerformLayout( ); this.panel1.ResumeLayout( false ); this.poseGroupBox.ResumeLayout( false ); this.poseGroupBox.PerformLayout( ); this.modelPointsGroupBox.ResumeLayout( false ); this.modelPointsGroupBox.PerformLayout( ); this.imagePointsGroupBox.ResumeLayout( false ); this.imagePointsGroupBox.PerformLayout( ); this.statusStrip.ResumeLayout( false ); this.statusStrip.PerformLayout( ); ( (System.ComponentModel.ISupportInitialize) ( this.errorProvider ) ).EndInit( ); this.ResumeLayout( false ); this.PerformLayout( ); } #endregion private System.Windows.Forms.Panel mainPanel; private System.Windows.Forms.PictureBox pictureBox; private System.Windows.Forms.MenuStrip mainMenu; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.GroupBox imagePointsGroupBox; private System.Windows.Forms.Button locate1Button; private System.Windows.Forms.TextBox imagePoint1Box; private System.Windows.Forms.Label label1; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.<API key> statusLabel; private System.Windows.Forms.Button locate4Button; private System.Windows.Forms.TextBox imagePoint4Box; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button locate3Button; private System.Windows.Forms.TextBox imagePoint3Box; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button locate2Button; private System.Windows.Forms.TextBox imagePoint2Box; private System.Windows.Forms.Label label2; private System.Windows.Forms.<API key> imageSizeLabel; private System.Windows.Forms.GroupBox modelPointsGroupBox; private System.Windows.Forms.TextBox modelPoint1xBox; private System.Windows.Forms.Label modelPoint4Label; private System.Windows.Forms.Label modelPoint1Label; private System.Windows.Forms.Label modelPoint3Label; private System.Windows.Forms.Label modelPoint2Label; private System.Windows.Forms.TextBox modelPoint4zBox; private System.Windows.Forms.TextBox modelPoint4yBox; private System.Windows.Forms.TextBox modelPoint4xBox; private System.Windows.Forms.TextBox modelPoint3zBox; private System.Windows.Forms.TextBox modelPoint3yBox; private System.Windows.Forms.TextBox modelPoint3xBox; private System.Windows.Forms.TextBox modelPoint2zBox; private System.Windows.Forms.TextBox modelPoint2yBox; private System.Windows.Forms.TextBox modelPoint2xBox; private System.Windows.Forms.TextBox modelPoint1zBox; private System.Windows.Forms.TextBox modelPoint1yBox; private System.Windows.Forms.ErrorProvider errorProvider; private System.Windows.Forms.GroupBox poseGroupBox; private System.Windows.Forms.Button estimatePostButton; private System.Windows.Forms.Label <API key>; private System.Windows.Forms.Label <API key>; private System.Windows.Forms.Label <API key>; private System.Windows.Forms.Label <API key>; private System.Windows.Forms.RadioButton copositRadio; private System.Windows.Forms.RadioButton positRadio; private System.Windows.Forms.TextBox focalLengthBox; private System.Windows.Forms.Label focalLengthLabel; private MatrixControl <API key>; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.ToolStripMenuItem <API key>; private System.Windows.Forms.<API key> estimationLabel; private System.Windows.Forms.Button alternatePoseButton; private System.Windows.Forms.Button bestPoseButton; private System.Windows.Forms.ToolTip toolTip; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; } }
#include <llmq/instantsend.h> #include <llmq/chainlocks.h> #include <llmq/quorums.h> #include <llmq/utils.h> #include <llmq/commitment.h> #include <bls/bls_batchverifier.h> #include <chainparams.h> #include <consensus/validation.h> #include <index/txindex.h> #include <txmempool.h> #include <util/ranges.h> #include <masternode/sync.h> #include <net_processing.h> #include <spork.h> #include <validation.h> #include <util/validation.h> #include <cxxtimer.hpp> namespace llmq { static const std::string <API key> = "inlock"; static const std::string <API key> = "islock"; static const std::string DB_ISLOCK_BY_HASH = "is_i"; static const std::string DB_HASH_BY_TXID = "is_tx"; static const std::string DB_HASH_BY_OUTPOINT = "is_in"; static const std::string <API key> = "is_m"; static const std::string <API key> = "is_a1"; static const std::string DB_ARCHIVED_BY_HASH = "is_a2"; static const std::string DB_VERSION = "is_v"; const int CInstantSendDb::CURRENT_VERSION; const uint8_t CInstantSendLock::islock_version; const uint8_t CInstantSendLock::isdlock_version; CInstantSendManager* <API key>; uint256 CInstantSendLock::GetRequestId() const { CHashWriter hw(SER_GETHASH, 0); hw << <API key>; hw << inputs; return hw.GetHash(); } void CInstantSendDb::Upgrade() { LOCK2(cs_main, ::mempool.cs); LOCK(cs_db); int v{0}; if (!db->Read(DB_VERSION, v) || v < CInstantSendDb::CURRENT_VERSION) { CDBBatch batch(*db); CInstantSendLock islock; CTransactionRef tx; uint256 hashBlock; auto it = std::unique_ptr<CDBIterator>(db->NewIterator()); auto firstKey = std::make_tuple(DB_ISLOCK_BY_HASH, uint256()); it->Seek(firstKey); decltype(firstKey) curKey; while (it->Valid()) { if (!it->GetKey(curKey) || std::get<0>(curKey) != DB_ISLOCK_BY_HASH) { break; } if (it->GetValue(islock) && !GetTransaction(islock.txid, tx, Params().GetConsensus(), hashBlock)) { // Drop locks for unknown txes batch.Erase(std::make_tuple(DB_HASH_BY_TXID, islock.txid)); for (auto& in : islock.inputs) { batch.Erase(std::make_tuple(DB_HASH_BY_OUTPOINT, in)); } batch.Erase(curKey); } it->Next(); } batch.Write(DB_VERSION, CInstantSendDb::CURRENT_VERSION); db->WriteBatch(batch); } } void CInstantSendDb::<API key>(const uint256& hash, const CInstantSendLock& islock) { LOCK(cs_db); CDBBatch batch(*db); batch.Write(std::make_tuple(DB_ISLOCK_BY_HASH, hash), islock); batch.Write(std::make_tuple(DB_HASH_BY_TXID, islock.txid), hash); for (auto& in : islock.inputs) { batch.Write(std::make_tuple(DB_HASH_BY_OUTPOINT, in), hash); } db->WriteBatch(batch); auto p = std::make_shared<CInstantSendLock>(islock); islockCache.insert(hash, p); txidCache.insert(islock.txid, hash); for (auto& in : islock.inputs) { outpointCache.insert(in, hash); } } void CInstantSendDb::<API key>(CDBBatch& batch, const uint256& hash, CInstantSendLockPtr islock, bool keep_cache) { AssertLockHeld(cs_db); if (!islock) { islock = <API key>(hash, false); if (!islock) { return; } } batch.Erase(std::make_tuple(DB_ISLOCK_BY_HASH, hash)); batch.Erase(std::make_tuple(DB_HASH_BY_TXID, islock->txid)); for (auto& in : islock->inputs) { batch.Erase(std::make_tuple(DB_HASH_BY_OUTPOINT, in)); } if (!keep_cache) { islockCache.erase(hash); txidCache.erase(islock->txid); for (const auto& in : islock->inputs) { outpointCache.erase(in); } } } static std::tuple<std::string, uint32_t, uint256> <API key>(const std::string& k, int nHeight, const uint256& islockHash) { return std::make_tuple(k, htobe32(std::numeric_limits<uint32_t>::max() - nHeight), islockHash); } void CInstantSendDb::<API key>(const uint256& hash, int nHeight) { LOCK(cs_db); CDBBatch batch(*db); <API key>(batch, hash, nHeight); db->WriteBatch(batch); } void CInstantSendDb::<API key>(CDBBatch& batch, const uint256& hash, int nHeight) { AssertLockHeld(cs_db); batch.Write(<API key>(<API key>, nHeight, hash), true); } void CInstantSendDb::<API key>(CDBBatch& batch, const uint256& hash, int nHeight) { AssertLockHeld(cs_db); batch.Erase(<API key>(<API key>, nHeight, hash)); } void CInstantSendDb::<API key>(CDBBatch& batch, const uint256& hash, int nHeight) { AssertLockHeld(cs_db); batch.Write(<API key>(<API key>, nHeight, hash), true); batch.Write(std::make_tuple(DB_ARCHIVED_BY_HASH, hash), true); } std::unordered_map<uint256, CInstantSendLockPtr, StaticSaltedHasher> CInstantSendDb::<API key>(int nUntilHeight) { LOCK(cs_db); if (nUntilHeight <= <API key>) { LogPrint(BCLog::ALL, "CInstantSendDb::%s -- Attempting to confirm height %d, however we've already confirmed height %d. This should never happen.\n", __func__, nUntilHeight, <API key>); return {}; } <API key> = nUntilHeight; auto it = std::unique_ptr<CDBIterator>(db->NewIterator()); auto firstKey = <API key>(<API key>, nUntilHeight, uint256()); it->Seek(firstKey); CDBBatch batch(*db); std::unordered_map<uint256, CInstantSendLockPtr, StaticSaltedHasher> ret; while (it->Valid()) { decltype(firstKey) curKey; if (!it->GetKey(curKey) || std::get<0>(curKey) != <API key>) { break; } uint32_t nHeight = std::numeric_limits<uint32_t>::max() - be32toh(std::get<1>(curKey)); if (nHeight > uint32_t(nUntilHeight)) { break; } auto& islockHash = std::get<2>(curKey); auto islock = <API key>(islockHash, false); if (islock) { <API key>(batch, islockHash, islock); ret.emplace(islockHash, islock); } // archive the islock hash, so that we're still able to check if we've seen the islock in the past <API key>(batch, islockHash, nHeight); batch.Erase(curKey); it->Next(); } db->WriteBatch(batch); return ret; } void CInstantSendDb::<API key>(int nUntilHeight) { LOCK(cs_db); if (nUntilHeight <= 0) { return; } auto it = std::unique_ptr<CDBIterator>(db->NewIterator()); auto firstKey = <API key>(<API key>, nUntilHeight, uint256()); it->Seek(firstKey); CDBBatch batch(*db); while (it->Valid()) { decltype(firstKey) curKey; if (!it->GetKey(curKey) || std::get<0>(curKey) != <API key>) { break; } uint32_t nHeight = std::numeric_limits<uint32_t>::max() - be32toh(std::get<1>(curKey)); if (nHeight > uint32_t(nUntilHeight)) { break; } auto& islockHash = std::get<2>(curKey); batch.Erase(std::make_tuple(DB_ARCHIVED_BY_HASH, islockHash)); batch.Erase(curKey); it->Next(); } db->WriteBatch(batch); } void CInstantSendDb::<API key>(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) { LOCK(cs_db); CDBBatch batch(*db); for (const auto& tx : pblock->vtx) { if (tx->IsCoinBase() || tx->vin.empty()) { // coinbase and TXs with no inputs can't be locked continue; } uint256 islockHash = <API key>(tx->GetHash()); // update DB about when an IS lock was mined if (!islockHash.IsNull()) { <API key>(batch, islockHash, pindexConnected->nHeight); } } db->WriteBatch(batch); } void CInstantSendDb::<API key>(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexDisconnected) { LOCK(cs_db); CDBBatch batch(*db); for (const auto& tx : pblock->vtx) { if (tx->IsCoinBase() || tx->vin.empty()) { // coinbase and TXs with no inputs can't be locked continue; } uint256 islockHash = <API key>(tx->GetHash()); if (!islockHash.IsNull()) { <API key>(batch, islockHash, pindexDisconnected->nHeight); } } db->WriteBatch(batch); } bool CInstantSendDb::<API key>(const uint256& islockHash) const { LOCK(cs_db); return <API key>(islockHash) != nullptr || db->Exists(std::make_tuple(DB_ARCHIVED_BY_HASH, islockHash)); } size_t CInstantSendDb::<API key>() const { LOCK(cs_db); auto it = std::unique_ptr<CDBIterator>(db->NewIterator()); auto firstKey = std::make_tuple(DB_ISLOCK_BY_HASH, uint256()); it->Seek(firstKey); size_t cnt = 0; while (it->Valid()) { decltype(firstKey) curKey; if (!it->GetKey(curKey) || std::get<0>(curKey) != DB_ISLOCK_BY_HASH) { break; } cnt++; it->Next(); } return cnt; } CInstantSendLockPtr CInstantSendDb::<API key>(const uint256& hash, bool use_cache) const { LOCK(cs_db); if (hash.IsNull()) { return nullptr; } CInstantSendLockPtr ret; if (use_cache && islockCache.get(hash, ret)) { return ret; } ret = std::make_shared<CInstantSendLock>(CInstantSendLock::isdlock_version); bool exists = db->Read(std::make_tuple(DB_ISLOCK_BY_HASH, hash), *ret); if (!exists || (::SerializeHash(*ret) != hash)) { ret = std::make_shared<CInstantSendLock>(); exists = db->Read(std::make_tuple(DB_ISLOCK_BY_HASH, hash), *ret); if (!exists || (::SerializeHash(*ret) != hash)) { ret = nullptr; } } islockCache.insert(hash, ret); return ret; } uint256 CInstantSendDb::<API key>(const uint256& txid) const { LOCK(cs_db); uint256 islockHash; if (!txidCache.get(txid, islockHash)) { if (!db->Read(std::make_tuple(DB_HASH_BY_TXID, txid), islockHash)) { return {}; } txidCache.insert(txid, islockHash); } return islockHash; } CInstantSendLockPtr CInstantSendDb::<API key>(const uint256& txid) const { LOCK(cs_db); return <API key>(<API key>(txid)); } CInstantSendLockPtr CInstantSendDb::<API key>(const COutPoint& outpoint) const { LOCK(cs_db); uint256 islockHash; if (!outpointCache.get(outpoint, islockHash)) { if (!db->Read(std::make_tuple(DB_HASH_BY_OUTPOINT, outpoint), islockHash)) { return nullptr; } outpointCache.insert(outpoint, islockHash); } return <API key>(islockHash); } std::vector<uint256> CInstantSendDb::<API key>(const uint256& parent) const { AssertLockHeld(cs_db); auto it = std::unique_ptr<CDBIterator>(db->NewIterator()); auto firstKey = std::make_tuple(DB_HASH_BY_OUTPOINT, COutPoint(parent, 0)); it->Seek(firstKey); std::vector<uint256> result; while (it->Valid()) { decltype(firstKey) curKey; if (!it->GetKey(curKey) || std::get<0>(curKey) != DB_HASH_BY_OUTPOINT) { break; } const auto& outpoint = std::get<1>(curKey); if (outpoint.hash != parent) { break; } uint256 islockHash; if (!it->GetValue(islockHash)) { break; } result.emplace_back(islockHash); it->Next(); } return result; } std::vector<uint256> CInstantSendDb::<API key>(const uint256& islockHash, const uint256& txid, int nHeight) { LOCK(cs_db); std::vector<uint256> result; std::vector<uint256> stack; std::unordered_set<uint256, StaticSaltedHasher> added; stack.emplace_back(txid); CDBBatch batch(*db); while (!stack.empty()) { auto children = <API key>(stack.back()); stack.pop_back(); for (auto& childIslockHash : children) { auto childIsLock = <API key>(childIslockHash, false); if (!childIsLock) { continue; } <API key>(batch, childIslockHash, childIsLock, false); <API key>(batch, childIslockHash, nHeight); result.emplace_back(childIslockHash); if (added.emplace(childIsLock->txid).second) { stack.emplace_back(childIsLock->txid); } } } <API key>(batch, islockHash, nullptr, false); <API key>(batch, islockHash, nHeight); result.emplace_back(islockHash); db->WriteBatch(batch); return result; } void CInstantSendDb::<API key>(const CInstantSendLockPtr& islock, int nHeight) { LOCK(cs_db); CDBBatch batch(*db); const auto hash = ::SerializeHash(*islock); <API key>(batch, hash, islock, false); <API key>(batch, hash, nHeight); db->WriteBatch(batch); } void CInstantSendManager::Start() { // can't start new thread if we have one running already if (workThread.joinable()) { assert(false); } workThread = std::thread(&TraceThread<std::function<void()> >, "isman", std::function<void()>(std::bind(&CInstantSendManager::WorkThreadMain, this))); <API key>-><API key>(this); } void CInstantSendManager::Stop() { <API key>-><API key>(this); // make sure to call <API key>() first if (!workInterrupt) { assert(false); } if (workThread.joinable()) { workThread.join(); } } void CInstantSendManager::ProcessTx(const CTransaction& tx, bool fRetroactive, const Consensus::Params& params) { AssertLockNotHeld(cs); if (!fMasternodeMode || !<API key>() || !masternodeSync.IsBlockchainSynced()) { return; } auto llmqType = params.llmqTypeInstantSend; if (llmqType == Consensus::LLMQType::LLMQ_NONE) { return; } if (!CheckCanLock(tx, true, params)) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: CheckCanLock returned false\n", __func__, tx.GetHash().ToString()); return; } auto conflictingLock = GetConflictingLock(tx); if (conflictingLock != nullptr) { auto conflictingLockHash = ::SerializeHash(*conflictingLock); LogPrintf("CInstantSendManager::%s -- txid=%s: conflicts with islock %s, txid=%s\n", __func__, tx.GetHash().ToString(), conflictingLockHash.ToString(), conflictingLock->txid.ToString()); return; } // Only sign for inlocks or islocks if mempool IS signing is enabled. // However, if we are processing a tx because it was included in a block we should // sign even if mempool IS signing is disabled. This allows a ChainLock to happen on this // block after we retroactively locked all transactions. if (!<API key>() && !fRetroactive) return; if (!TrySignInputLocks(tx, fRetroactive, llmqType)) return; // We might have received all input locks before we got the corresponding TX. In this case, we have to sign the // islock now instead of waiting for the input locks. <API key>(tx); } bool CInstantSendManager::TrySignInputLocks(const CTransaction& tx, bool fRetroactive, Consensus::LLMQType llmqType) { std::vector<uint256> ids; ids.reserve(tx.vin.size()); size_t alreadyVotedCount = 0; for (const auto& in : tx.vin) { auto id = ::SerializeHash(std::make_pair(<API key>, in.prevout)); ids.emplace_back(id); uint256 otherTxHash; if (<API key>->GetVoteForId(llmqType, id, otherTxHash)) { if (otherTxHash != tx.GetHash()) { LogPrintf("CInstantSendManager::%s -- txid=%s: input %s is conflicting with previous vote for tx %s\n", __func__, tx.GetHash().ToString(), in.prevout.ToStringShort(), otherTxHash.ToString()); return false; } alreadyVotedCount++; } // don't even try the actual signing if any input is conflicting if (<API key>->IsConflicting(llmqType, id, tx.GetHash())) { LogPrintf("CInstantSendManager::%s -- txid=%s: <API key>->IsConflicting returned true. id=%s\n", __func__, tx.GetHash().ToString(), id.ToString()); return false; } } if (!fRetroactive && alreadyVotedCount == ids.size()) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: already voted on all inputs, bailing out\n", __func__, tx.GetHash().ToString()); return true; } LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: trying to vote on %d inputs\n", __func__, tx.GetHash().ToString(), tx.vin.size()); for (size_t i = 0; i < tx.vin.size(); i++) { auto& in = tx.vin[i]; auto& id = ids[i]; WITH_LOCK(cs, inputRequestIds.emplace(id)); LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: trying to vote on input %s with id %s. fRetroactive=%d\n", __func__, tx.GetHash().ToString(), in.prevout.ToStringShort(), id.ToString(), fRetroactive); if (<API key>->AsyncSignIfMember(llmqType, id, tx.GetHash(), {}, fRetroactive)) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: voted on input %s with id %s\n", __func__, tx.GetHash().ToString(), in.prevout.ToStringShort(), id.ToString()); } } return true; } bool CInstantSendManager::CheckCanLock(const CTransaction& tx, bool printDebug, const Consensus::Params& params) const { if (tx.vin.empty()) { // can't lock TXs without inputs (e.g. quorum commitments) return false; } return ranges::all_of(tx.vin, [&](const auto& in) { return CheckCanLock(in.prevout, printDebug, tx.GetHash(), params); }); } bool CInstantSendManager::CheckCanLock(const COutPoint& outpoint, bool printDebug, const uint256& txHash, const Consensus::Params& params) const { AssertLockNotHeld(cs); int <API key> = params.<API key>; if (IsLocked(outpoint.hash)) { // if prevout was ix locked, allow locking of descendants (no matter if prevout is in mempool or already mined) return true; } auto mempoolTx = mempool.get(outpoint.hash); if (mempoolTx) { if (printDebug) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: parent mempool TX %s is not locked\n", __func__, txHash.ToString(), outpoint.hash.ToString()); } return false; } CTransactionRef tx; uint256 hashBlock; // this relies on enabled txindex and won't work if we ever try to remove the requirement for txindex for masternodes if (!GetTransaction(outpoint.hash, tx, params, hashBlock)) { if (printDebug) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: failed to find parent TX %s\n", __func__, txHash.ToString(), outpoint.hash.ToString()); } return false; } const CBlockIndex* pindexMined; int nTxAge; { LOCK(cs_main); pindexMined = LookupBlockIndex(hashBlock); nTxAge = ::ChainActive().Height() - pindexMined->nHeight + 1; } if (nTxAge < <API key> && !llmq::chainLocksHandler->HasChainLock(pindexMined->nHeight, pindexMined->GetBlockHash())) { if (printDebug) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: outpoint %s too new and not ChainLocked. nTxAge=%d, <API key>=%d\n", __func__, txHash.ToString(), outpoint.ToStringShort(), nTxAge, <API key>); } return false; } return true; } void CInstantSendManager::<API key>(const CRecoveredSig& recoveredSig) { if (!<API key>()) { return; } auto llmqType = Params().GetConsensus().llmqTypeInstantSend; if (llmqType == Consensus::LLMQType::LLMQ_NONE) { return; } uint256 txid; bool isInstantSendLock = false; { LOCK(cs); if (inputRequestIds.count(recoveredSig.id)) { txid = recoveredSig.msgHash; } if (<API key>.count(recoveredSig.id)) { isInstantSendLock = true; } } if (!txid.IsNull()) { <API key>(recoveredSig, txid); } else if (isInstantSendLock) { <API key>(recoveredSig); } } void CInstantSendManager::<API key>(const CRecoveredSig& recoveredSig, const uint256& txid) { if (g_txindex) { g_txindex-><API key>(); } CTransactionRef tx; uint256 hashBlock; if (!GetTransaction(txid, tx, Params().GetConsensus(), hashBlock)) { return; } if (LogAcceptCategory(BCLog::INSTANTSEND)) { for (auto& in : tx->vin) { auto id = ::SerializeHash(std::make_pair(<API key>, in.prevout)); if (id == recoveredSig.id) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: got recovered sig for input %s\n", __func__, txid.ToString(), in.prevout.ToStringShort()); break; } } } <API key>(*tx); } void CInstantSendManager::<API key>(const CTransaction& tx) { const auto llmqType = Params().GetConsensus().llmqTypeInstantSend; for (auto& in : tx.vin) { auto id = ::SerializeHash(std::make_pair(<API key>, in.prevout)); if (!<API key>->HasRecoveredSig(llmqType, id, tx.GetHash())) { return; } } LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: got all recovered sigs, creating CInstantSendLock\n", __func__, tx.GetHash().ToString()); CInstantSendLock islock(CInstantSendLock::isdlock_version); islock.txid = tx.GetHash(); for (auto& in : tx.vin) { islock.inputs.emplace_back(in.prevout); } // compute cycle hash { LOCK(cs_main); const auto dkgInterval = GetLLMQParams(llmqType).dkgInterval; const auto quorumHeight = ::ChainActive().Height() - (::ChainActive().Height() % dkgInterval); islock.cycleHash = ::ChainActive()[quorumHeight]->GetBlockHash(); } auto id = islock.GetRequestId(); if (<API key>-><API key>(llmqType, id)) { return; } { LOCK(cs); auto e = <API key>.emplace(id, std::move(islock)); if (!e.second) { return; } <API key>.emplace(tx.GetHash(), &e.first->second); } <API key>->AsyncSignIfMember(llmqType, id, tx.GetHash()); } void CInstantSendManager::<API key>(const llmq::CRecoveredSig& recoveredSig) { CInstantSendLockPtr islock; { LOCK(cs); auto it = <API key>.find(recoveredSig.id); if (it == <API key>.end()) { return; } islock = std::make_shared<CInstantSendLock>(std::move(it->second)); <API key>.erase(it); <API key>.erase(islock->txid); } if (islock->txid != recoveredSig.msgHash) { LogPrintf("CInstantSendManager::%s -- txid=%s: islock conflicts with %s, dropping own version\n", __func__, islock->txid.ToString(), recoveredSig.msgHash.ToString()); return; } islock->sig = recoveredSig.sig; auto hash = ::SerializeHash(*islock); LOCK(cs); if (<API key>.count(hash) || db.<API key>(hash)) { return; } <API key>.emplace(hash, std::make_pair(-1, islock)); } void CInstantSendManager::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv) { if (!<API key>()) { return; } if (strCommand == NetMsgType::ISLOCK || strCommand == NetMsgType::ISDLOCK) { const auto islock_version = strCommand == NetMsgType::ISLOCK ? CInstantSendLock::islock_version : CInstantSendLock::isdlock_version; const auto islock = std::make_shared<CInstantSendLock>(islock_version); vRecv >> *islock; <API key>(pfrom, islock); } } void CInstantSendManager::<API key>(const CNode* pfrom, const llmq::CInstantSendLockPtr& islock) { AssertLockNotHeld(cs); auto hash = ::SerializeHash(*islock); { LOCK(cs_main); EraseObjectRequest(pfrom->GetId(), CInv(islock->IsDeterministic() ? MSG_ISDLOCK : MSG_ISLOCK, hash)); } if (!<API key>(*islock)) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); return; } if (islock->IsDeterministic()) { const auto blockIndex = WITH_LOCK(cs_main, return LookupBlockIndex(islock->cycleHash)); if (blockIndex == nullptr) { // Maybe we don't have the block yet or maybe some peer spams invalid values for cycleHash WITH_LOCK(cs_main, Misbehaving(pfrom->GetId(), 1)); return; } const auto llmqType = Params().GetConsensus().llmqTypeInstantSend; const auto dkgInterval = GetLLMQParams(llmqType).dkgInterval; if (blockIndex->nHeight % dkgInterval != 0) { WITH_LOCK(cs_main, Misbehaving(pfrom->GetId(), 100)); return; } } LOCK(cs); if (<API key>.count(hash) || <API key>.count(hash) || db.<API key>(hash)) { return; } LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: received islock, peer=%d\n", __func__, islock->txid.ToString(), hash.ToString(), pfrom->GetId()); <API key>.emplace(hash, std::make_pair(pfrom->GetId(), islock)); } /** * Handles trivial ISLock verification * @param islock The islock message being undergoing verification * @return returns false if verification failed, otherwise true */ bool CInstantSendManager::<API key>(const llmq::CInstantSendLock& islock) { if (islock.txid.IsNull() || islock.inputs.empty()) { return false; } // Check that each input is unique std::set<COutPoint> dups; for (auto& o : islock.inputs) { if (!dups.emplace(o).second) { return false; } } return true; } bool CInstantSendManager::<API key>() { decltype(<API key>) pend; bool fMoreWork{false}; if (!<API key>()) { return false; } { LOCK(cs); // only process a max 32 locks at a time to avoid duplicate verification of recovered signatures which have been // verified by CSigningManager in parallel const size_t maxCount = 32; if (<API key>.size() <= maxCount) { pend = std::move(<API key>); } else { while (pend.size() < maxCount) { auto it = <API key>.begin(); pend.emplace(it->first, std::move(it->second)); <API key>.erase(it); } fMoreWork = true; } } if (pend.empty()) { return false; } auto llmqType = Params().GetConsensus().llmqTypeInstantSend; auto dkgInterval = GetLLMQParams(llmqType).dkgInterval; // First check against the current active set and don't ban auto badISLocks = <API key>(0, pend, false); if (!badISLocks.empty()) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- doing verification on old active set\n", __func__); // filter out valid IS locks from "pend" for (auto it = pend.begin(); it != pend.end(); ) { if (!badISLocks.count(it->first)) { it = pend.erase(it); } else { ++it; } } // Now check against the previous active set and perform banning if this fails <API key>(dkgInterval, pend, true); } return fMoreWork; } std::unordered_set<uint256, StaticSaltedHasher> CInstantSendManager::<API key>(int signOffset, const std::unordered_map<uint256, std::pair<NodeId, CInstantSendLockPtr>, StaticSaltedHasher>& pend, bool ban) { auto llmqType = Params().GetConsensus().llmqTypeInstantSend; CBLSBatchVerifier<NodeId, uint256> batchVerifier(false, true, 8); std::unordered_map<uint256, CRecoveredSig, StaticSaltedHasher> recSigs; size_t verifyCount = 0; size_t alreadyVerified = 0; for (const auto& p : pend) { auto& hash = p.first; auto nodeId = p.second.first; auto& islock = p.second.second; if (batchVerifier.badSources.count(nodeId)) { continue; } if (!islock->sig.Get().IsValid()) { batchVerifier.badSources.emplace(nodeId); continue; } auto id = islock->GetRequestId(); // no need to verify an ISLOCK if we already have verified the recovered sig that belongs to it if (<API key>->HasRecoveredSig(llmqType, id, islock->txid)) { alreadyVerified++; continue; } int nSignHeight{-1}; if (islock->IsDeterministic()) { LOCK(cs_main); const auto blockIndex = LookupBlockIndex(islock->cycleHash); if (blockIndex == nullptr) { batchVerifier.badSources.emplace(nodeId); continue; } const auto dkgInterval = GetLLMQParams(Params().GetConsensus().llmqTypeInstantSend).dkgInterval; if (blockIndex->nHeight + dkgInterval < ::ChainActive().Height()) { nSignHeight = blockIndex->nHeight + dkgInterval - 1; } } auto quorum = llmq::CSigningManager::<API key>(llmqType, id, nSignHeight, signOffset); if (!quorum) { // should not happen, but if one fails to select, all others will also fail to select return {}; } uint256 signHash = CLLMQUtils::BuildSignHash(llmqType, quorum->qc->quorumHash, id, islock->txid); batchVerifier.PushMessage(nodeId, hash, signHash, islock->sig.Get(), quorum->qc->quorumPublicKey); verifyCount++; // We can reconstruct the CRecoveredSig objects from the islock and pass it to the signing manager, which // avoids unnecessary double-verification of the signature. We however only do this when verification here // turns out to be good (which is checked further down) if (!<API key>-><API key>(llmqType, id)) { recSigs.try_emplace(hash, CRecoveredSig(llmqType, quorum->qc->quorumHash, id, islock->txid, islock->sig)); } } cxxtimer::Timer verifyTimer(true); batchVerifier.Verify(); verifyTimer.stop(); LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- verified locks. count=%d, alreadyVerified=%d, vt=%d, nodes=%d\n", __func__, verifyCount, alreadyVerified, verifyTimer.count(), batchVerifier.<API key>()); std::unordered_set<uint256, StaticSaltedHasher> badISLocks; if (ban && !batchVerifier.badSources.empty()) { LOCK(cs_main); for (auto& nodeId : batchVerifier.badSources) { // Let's not be too harsh, as the peer might simply be unlucky and might have sent us an old lock which // does not validate anymore due to changed quorums Misbehaving(nodeId, 20); } } for (const auto& p : pend) { auto& hash = p.first; auto nodeId = p.second.first; auto& islock = p.second.second; if (batchVerifier.badMessages.count(hash)) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: invalid sig in islock, peer=%d\n", __func__, islock->txid.ToString(), hash.ToString(), nodeId); badISLocks.emplace(hash); continue; } <API key>(nodeId, hash, islock); // See comment further on top. We pass a reconstructed recovered sig to the signing manager to avoid // double-verification of the sig. auto it = recSigs.find(hash); if (it != recSigs.end()) { auto recSig = std::make_shared<CRecoveredSig>(std::move(it->second)); if (!<API key>-><API key>(llmqType, recSig->id)) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: passing reconstructed recSig to signing mgr, peer=%d\n", __func__, islock->txid.ToString(), hash.ToString(), nodeId); <API key>-><API key>(recSig); } } } return badISLocks; } void CInstantSendManager::<API key>(NodeId from, const uint256& hash, const CInstantSendLockPtr& islock) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: processing islock, peer=%d\n", __func__, islock->txid.ToString(), hash.ToString(), from); { LOCK(cs); <API key>.erase(islock->GetRequestId()); <API key>.erase(islock->txid); } if (db.<API key>(hash)) { return; } CTransactionRef tx; uint256 hashBlock; const CBlockIndex* pindexMined{nullptr}; // we ignore failure here as we must be able to propagate the lock even if we don't have the TX locally if (GetTransaction(islock->txid, tx, Params().GetConsensus(), hashBlock) && !hashBlock.IsNull()) { pindexMined = WITH_LOCK(cs_main, return LookupBlockIndex(hashBlock)); // Let's see if the TX that was locked by this islock is already mined in a ChainLocked block. If yes, // we can simply ignore the islock, as the ChainLock implies locking of all TXs in that chain if (pindexMined != nullptr && llmq::chainLocksHandler->HasChainLock(pindexMined->nHeight, pindexMined->GetBlockHash())) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txlock=%s, islock=%s: dropping islock as it already got a ChainLock in block %s, peer=%d\n", __func__, islock->txid.ToString(), hash.ToString(), hashBlock.ToString(), from); return; } } const auto sameTxIsLock = db.<API key>(islock->txid); if (sameTxIsLock != nullptr) { if (sameTxIsLock->IsDeterministic() == islock->IsDeterministic()) { // shouldn't happen, investigate LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: duplicate islock, other islock=%s, peer=%d\n", __func__, islock->txid.ToString(), hash.ToString(), ::SerializeHash(*sameTxIsLock).ToString(), from); } if (sameTxIsLock->IsDeterministic()) { // can happen, nothing to do return; } else if (islock->IsDeterministic()) { // can happen, remove and archive the non-deterministic sameTxIsLock db.<API key>(sameTxIsLock, WITH_LOCK(::cs_main, return ::ChainActive().Height())); } } else { for (const auto& in : islock->inputs) { const auto sameOutpointIsLock = db.<API key>(in); if (sameOutpointIsLock != nullptr) { LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: conflicting outpoint in islock. input=%s, other islock=%s, peer=%d\n", __func__, islock->txid.ToString(), hash.ToString(), in.ToStringShort(), ::SerializeHash(*sameOutpointIsLock).ToString(), from); } } } if (tx == nullptr) { // put it in a separate pending map and try again later LOCK(cs); <API key>.try_emplace(hash, std::make_pair(from, islock)); } else { db.<API key>(hash, *islock); if (pindexMined) { db.<API key>(hash, pindexMined->nHeight); } } { LOCK(cs); // This will also add children TXs to pendingRetryTxs RemoveNonLockedTx(islock->txid, true); // We don't need the recovered sigs for the inputs anymore. This prevents unnecessary propagation of these sigs. // We only need the ISLOCK from now on to detect conflicts <API key>(*islock); } const auto is_det = islock->IsDeterministic(); CInv inv(is_det ? MSG_ISDLOCK : MSG_ISLOCK, hash); if (tx != nullptr) { g_connman->RelayInvFiltered(inv, *tx, is_det ? <API key> : LLMQS_PROTO_VERSION); } else { // we don't have the TX yet, so we only filter based on txid. Later when that TX arrives, we will re-announce // with the TX taken into account. g_connman->RelayInvFiltered(inv, islock->txid, is_det ? <API key> : LLMQS_PROTO_VERSION); } <API key>(hash, *islock); if (tx != nullptr) { <API key>(hash, *islock); LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- notify about lock %s for tx %s\n", __func__, hash.ToString(), tx->GetHash().ToString()); GetMainSignals().<API key>(tx, islock); // bump mempool counter to make sure newly locked txes are picked up by getblocktemplate mempool.<API key>(1); } else { AskNodesForLockedTx(islock->txid); } } void CInstantSendManager::<API key>(const CTransactionRef& tx) { if (!<API key>() || !masternodeSync.IsBlockchainSynced() || tx->vin.empty()) { return; } CInstantSendLockPtr islock{nullptr}; { LOCK(cs); auto it = <API key>.begin(); while (it != <API key>.end()) { if (it->second.second->txid == tx->GetHash()) { // we received an islock earlier LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s\n", __func__, tx->GetHash().ToString(), it->first.ToString()); islock = it->second.second; <API key>.try_emplace(it->first, it->second); <API key>.erase(it); break; } ++it; } } if (islock == nullptr) { ProcessTx(*tx, false, Params().GetConsensus()); // TX is not locked, so make sure it is tracked AddNonLockedTx(tx, nullptr); } else { <API key>(::SerializeHash(*islock), *islock); } } void CInstantSendManager::<API key>(const CTransactionRef& tx) { if (tx->vin.empty() || !fUpgradedDB) { return; } CInstantSendLockPtr islock = db.<API key>(tx->GetHash()); if (islock == nullptr) { return; } LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- transaction %s was removed from mempool\n", __func__, tx->GetHash().ToString()); <API key>(::SerializeHash(*islock), *islock); } void CInstantSendManager::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) { if (!<API key>()) { return; } if (!vtxConflicted.empty()) { LOCK(cs); for (const auto& tx : vtxConflicted) { RemoveConflictedTx(*tx); } } if (masternodeSync.IsBlockchainSynced()) { for (const auto& tx : pblock->vtx) { if (tx->IsCoinBase() || tx->vin.empty()) { // coinbase and TXs with no inputs can't be locked continue; } if (!IsLocked(tx->GetHash()) && !chainLocksHandler->HasChainLock(pindex->nHeight, pindex->GetBlockHash())) { ProcessTx(*tx, true, Params().GetConsensus()); // TX is not locked, so make sure it is tracked AddNonLockedTx(tx, pindex); } else { // TX is locked, so make sure we don't track it anymore LOCK(cs); RemoveNonLockedTx(tx->GetHash(), true); } } } db.<API key>(pblock, pindex); } void CInstantSendManager::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexDisconnected) { db.<API key>(pblock, pindexDisconnected); } void CInstantSendManager::AddNonLockedTx(const CTransactionRef& tx, const CBlockIndex* pindexMined) { LOCK(cs); auto res = nonLockedTxs.emplace(tx->GetHash(), NonLockedTxInfo()); auto& info = res.first->second; info.pindexMined = pindexMined; if (res.second) { info.tx = tx; for (const auto& in : tx->vin) { nonLockedTxs[in.prevout.hash].children.emplace(tx->GetHash()); <API key>.emplace(in.prevout, tx->GetHash()); } } auto it = <API key>.begin(); while (it != <API key>.end()) { if (it->second.second->txid == tx->GetHash()) { // we received an islock earlier, let's put it back into pending and verify/lock LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s\n", __func__, tx->GetHash().ToString(), it->first.ToString()); <API key>.try_emplace(it->first, it->second); <API key>.erase(it); break; } ++it; } LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, pindexMined=%s\n", __func__, tx->GetHash().ToString(), pindexMined ? pindexMined->GetBlockHash().ToString() : ""); } void CInstantSendManager::RemoveNonLockedTx(const uint256& txid, bool retryChildren) { AssertLockHeld(cs); auto it = nonLockedTxs.find(txid); if (it == nonLockedTxs.end()) { return; } const auto& info = it->second; size_t retryChildrenCount = 0; if (retryChildren) { // TX got locked, so we can retry locking children for (auto& childTxid : info.children) { pendingRetryTxs.emplace(childTxid); retryChildrenCount++; } } if (info.tx) { for (const auto& in : info.tx->vin) { auto jt = nonLockedTxs.find(in.prevout.hash); if (jt != nonLockedTxs.end()) { jt->second.children.erase(txid); if (!jt->second.tx && jt->second.children.empty()) { nonLockedTxs.erase(jt); } } <API key>.erase(in.prevout); } } nonLockedTxs.erase(it); LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, retryChildren=%d, retryChildrenCount=%d\n", __func__, txid.ToString(), retryChildren, retryChildrenCount); } void CInstantSendManager::RemoveConflictedTx(const CTransaction& tx) { AssertLockHeld(cs); RemoveNonLockedTx(tx.GetHash(), false); for (const auto& in : tx.vin) { auto inputRequestId = ::SerializeHash(std::make_pair(<API key>, in)); inputRequestIds.erase(inputRequestId); } } void CInstantSendManager::<API key>(const llmq::CInstantSendLock& islock) { AssertLockHeld(cs); auto& consensusParams = Params().GetConsensus(); for (auto& in : islock.inputs) { auto inputRequestId = ::SerializeHash(std::make_pair(<API key>, in)); inputRequestIds.erase(inputRequestId); <API key>-><API key>(consensusParams.llmqTypeInstantSend, inputRequestId); } } void CInstantSendManager::NotifyChainLock(const CBlockIndex* pindexChainLock) { <API key>(pindexChainLock); } void CInstantSendManager::UpdatedBlockTip(const CBlockIndex* pindexNew) { if (!fUpgradedDB) { if (WITH_LOCK(cs_llmq_vbc, return VersionBitsState(pindexNew, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0020, <API key>) == ThresholdState::ACTIVE)) { db.Upgrade(); fUpgradedDB = true; } } bool fDIP0008Active = pindexNew->pprev && pindexNew->pprev->nHeight >= Params().GetConsensus().DIP0008Height; if (<API key>() && fDIP0008Active) { // Nothing to do here. We should keep all islocks and let chainlocks handle them. return; } int nConfirmedHeight = pindexNew->nHeight - Params().GetConsensus().<API key>; const CBlockIndex* pindex = pindexNew->GetAncestor(nConfirmedHeight); if (pindex) { <API key>(pindex); } } void CInstantSendManager::<API key>(const CBlockIndex* pindex) { if (!<API key>()) { return; } auto& consensusParams = Params().GetConsensus(); auto removeISLocks = db.<API key>(pindex->nHeight); LOCK(cs); for (const auto& p : removeISLocks) { auto& islockHash = p.first; auto& islock = p.second; LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: removed islock as it got fully confirmed\n", __func__, islock->txid.ToString(), islockHash.ToString()); // No need to keep recovered sigs for fully confirmed IS locks, as there is no chance for conflicts // from now on. All inputs are spent now and can't be spend in any other TX. <API key>(*islock); // And we don't need the recovered sig for the ISLOCK anymore, as the block in which it got mined is considered // fully confirmed now <API key>-><API key>(consensusParams.llmqTypeInstantSend, islock->GetRequestId()); } db.<API key>(pindex->nHeight - 100); // Find all previously unlocked TXs that got locked by this fully confirmed (ChainLock) block and remove them // from the nonLockedTxs map. Also collect all children of these TXs and mark them for retrying of IS locking. std::vector<uint256> toRemove; for (const auto& p : nonLockedTxs) { auto pindexMined = p.second.pindexMined; if (pindexMined && pindex->GetAncestor(pindexMined->nHeight) == pindexMined) { toRemove.emplace_back(p.first); } } for (const auto& txid : toRemove) { // This will also add children to pendingRetryTxs RemoveNonLockedTx(txid, true); } } void CInstantSendManager::<API key>(const uint256& hash, const CInstantSendLock& islock) { std::unordered_map<uint256, CTransactionRef, StaticSaltedHasher> toDelete; { LOCK(mempool.cs); for (auto& in : islock.inputs) { auto it = mempool.mapNextTx.find(in); if (it == mempool.mapNextTx.end()) { continue; } if (it->second->GetHash() != islock.txid) { toDelete.emplace(it->second->GetHash(), mempool.get(it->second->GetHash())); LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: mempool TX %s with input %s conflicts with islock\n", __func__, islock.txid.ToString(), hash.ToString(), it->second->GetHash().ToString(), in.ToStringShort()); } } for (const auto& p : toDelete) { mempool.removeRecursive(*p.second, <API key>::CONFLICT); } } if (!toDelete.empty()) { { LOCK(cs); for (const auto& p : toDelete) { RemoveConflictedTx(*p.second); } } AskNodesForLockedTx(islock.txid); } } void CInstantSendManager::<API key>(const uint256& islockHash, const llmq::CInstantSendLock& islock) { // Lets first collect all non-locked TXs which conflict with the given ISLOCK std::unordered_map<const CBlockIndex*, std::unordered_map<uint256, CTransactionRef, StaticSaltedHasher>> conflicts; { LOCK(cs); for (auto& in : islock.inputs) { auto it = <API key>.find(in); if (it != <API key>.end()) { auto& conflictTxid = it->second; if (conflictTxid == islock.txid) { continue; } auto jt = nonLockedTxs.find(conflictTxid); if (jt == nonLockedTxs.end()) { continue; } auto& info = jt->second; if (!info.pindexMined || !info.tx) { continue; } LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: mined TX %s with input %s and mined in block %s conflicts with islock\n", __func__, islock.txid.ToString(), islockHash.ToString(), conflictTxid.ToString(), in.ToStringShort(), info.pindexMined->GetBlockHash().ToString()); conflicts[info.pindexMined].emplace(conflictTxid, info.tx); } } } // Lets see if any of the conflicts was already mined into a ChainLocked block bool <API key> = false; for (const auto& p : conflicts) { auto pindex = p.first; if (chainLocksHandler->HasChainLock(pindex->nHeight, pindex->GetBlockHash())) { <API key> = true; break; } } // If a conflict was mined into a ChainLocked block, then we have no other choice and must prune the ISLOCK and all // chained ISLOCKs that build on top of this one. The probability of this is practically zero and can only happen // when large parts of the masternode network are controlled by an attacker. In this case we must still find consensus // and its better to sacrifice individual ISLOCKs then to sacrifice whole ChainLocks. if (<API key>) { LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: at least one conflicted TX already got a ChainLock\n", __func__, islock.txid.ToString(), islockHash.ToString()); <API key>(islockHash, islock); return; } bool isLockedTxKnown = WITH_LOCK(cs, return <API key>.find(islockHash) == <API key>.end()); bool activateBestChain = false; for (const auto& p : conflicts) { auto pindex = p.first; { LOCK(cs); for (auto& p2 : p.second) { const auto& tx = *p2.second; RemoveConflictedTx(tx); } } LogPrintf("CInstantSendManager::%s -- invalidating block %s\n", __func__, pindex->GetBlockHash().ToString()); CValidationState state; // need non-const pointer auto pindex2 = WITH_LOCK(::cs_main, return LookupBlockIndex(pindex->GetBlockHash())); if (!InvalidateBlock(state, Params(), pindex2)) { LogPrintf("CInstantSendManager::%s -- InvalidateBlock failed: %s\n", __func__, FormatStateMessage(state)); // This should not have happened and we are in a state were it's not safe to continue anymore assert(false); } if (isLockedTxKnown) { activateBestChain = true; } else { LogPrintf("CInstantSendManager::%s -- resetting block %s\n", __func__, pindex2->GetBlockHash().ToString()); LOCK(cs_main); <API key>(pindex2); } } if (activateBestChain) { CValidationState state; if (!ActivateBestChain(state, Params())) { LogPrintf("CChainLocksHandler::%s -- ActivateBestChain failed: %s\n", __func__, FormatStateMessage(state)); // This should not have happened and we are in a state were it's not safe to continue anymore assert(false); } } } void CInstantSendManager::<API key>(const uint256& islockHash, const llmq::CInstantSendLock& islock) { AssertLockNotHeld(cs); LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: Removing ISLOCK and its chained children\n", __func__, islock.txid.ToString(), islockHash.ToString()); int tipHeight = WITH_LOCK(cs_main, return ::ChainActive().Height()); auto removedIslocks = db.<API key>(islockHash, islock.txid, tipHeight); for (const auto& h : removedIslocks) { LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: removed (child) ISLOCK %s\n", __func__, islock.txid.ToString(), islockHash.ToString(), h.ToString()); } } void CInstantSendManager::AskNodesForLockedTx(const uint256& txid) { std::vector<CNode*> nodesToAskFor; nodesToAskFor.reserve(4); auto <API key> = [&nodesToAskFor, &txid](CNode* pnode) { if (nodesToAskFor.size() >= 4) { return; } LOCK(pnode->cs_inventory); if (pnode-><API key>.contains(txid)) { pnode->AddRef(); nodesToAskFor.emplace_back(pnode); } }; g_connman->ForEachNode([&](CNode* pnode) { // Check masternodes first if (pnode-><API key>) <API key>(pnode); }); g_connman->ForEachNode([&](CNode* pnode) { // Check non-masternodes next if (!pnode-><API key>) <API key>(pnode); }); { LOCK(cs_main); for (const CNode* pnode : nodesToAskFor) { LogPrintf("CInstantSendManager::%s -- txid=%s: asking other peer %d for correct TX\n", __func__, txid.ToString(), pnode->GetId()); CInv inv(MSG_TX, txid); RequestObject(pnode->GetId(), inv, GetTime<std::chrono::microseconds>(), true); } } for (CNode* pnode : nodesToAskFor) { pnode->Release(); } } void CInstantSendManager::<API key>() { decltype(pendingRetryTxs) retryTxs = WITH_LOCK(cs, return std::move(pendingRetryTxs)); if (retryTxs.empty()) { return; } if (!<API key>()) { return; } int retryCount = 0; for (const auto& txid : retryTxs) { CTransactionRef tx; { LOCK(cs); auto it = nonLockedTxs.find(txid); if (it == nonLockedTxs.end()) { continue; } tx = it->second.tx; if (!tx) { continue; } if (<API key>.count(tx->GetHash())) { // we're already in the middle of locking this one continue; } if (IsLocked(tx->GetHash())) { continue; } if (IsConflicted(*tx)) { // should not really happen as we have already filtered these out continue; } } // CheckCanLock is already called by ProcessTx, so we should avoid calling it twice. But we also shouldn't spam // the logs when retrying TXs that are not ready yet. if (LogAcceptCategory(BCLog::INSTANTSEND)) { if (!CheckCanLock(*tx, false, Params().GetConsensus())) { continue; } LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: retrying to lock\n", __func__, tx->GetHash().ToString()); } ProcessTx(*tx, false, Params().GetConsensus()); retryCount++; } if (retryCount != 0) { LOCK(cs); LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- retried %d TXs. nonLockedTxs.size=%d\n", __func__, retryCount, nonLockedTxs.size()); } } bool CInstantSendManager::AlreadyHave(const CInv& inv) const { if (!<API key>()) { return true; } LOCK(cs); return <API key>.count(inv.hash) != 0 || <API key>.count(inv.hash) != 0 || db.<API key>(inv.hash); } bool CInstantSendManager::<API key>(const uint256& hash, llmq::CInstantSendLock& ret) const { if (!<API key>()) { return false; } auto islock = db.<API key>(hash); if (!islock) { LOCK(cs); auto it = <API key>.find(hash); if (it != <API key>.end()) { islock = it->second.second; } else { auto itNoTx = <API key>.find(hash); if (itNoTx != <API key>.end()) { islock = itNoTx->second.second; } else { return false; } } } ret = *islock; return true; } CInstantSendLockPtr CInstantSendManager::<API key>(const uint256& txid) const { if (!<API key>()) { return nullptr; } return db.<API key>(txid); } bool CInstantSendManager::<API key>(const uint256& txid, uint256& ret) const { if (!<API key>()) { return false; } ret = db.<API key>(txid); return !ret.IsNull(); } bool CInstantSendManager::IsLocked(const uint256& txHash) const { if (!<API key>()) { return false; } return db.<API key>(db.<API key>(txHash)); } bool CInstantSendManager::IsWaitingForTx(const uint256& txHash) const { if (!<API key>()) { return false; } LOCK(cs); auto it = <API key>.begin(); while (it != <API key>.end()) { if (it->second.second->txid == txHash) { LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s\n", __func__, txHash.ToString(), it->first.ToString()); return true; } ++it; } return false; } CInstantSendLockPtr CInstantSendManager::GetConflictingLock(const CTransaction& tx) const { if (!<API key>()) { return nullptr; } for (const auto& in : tx.vin) { auto otherIsLock = db.<API key>(in.prevout); if (!otherIsLock) { continue; } if (otherIsLock->txid != tx.GetHash()) { return otherIsLock; } } return nullptr; } size_t CInstantSendManager::<API key>() const { return db.<API key>(); } void CInstantSendManager::WorkThreadMain() { while (!workInterrupt) { bool fMoreWork = <API key>(); <API key>(); if (!fMoreWork && !workInterrupt.sleep_for(std::chrono::milliseconds(100))) { return; } } } bool <API key>() { return !fReindex && !fImporting && sporkManager.IsSporkActive(<API key>); } bool <API key>() { return !fReindex && !fImporting && sporkManager.GetSporkValue(<API key>) == 0; } bool <API key>() { if (!masternodeSync.IsBlockchainSynced()) { return false; } if (!sporkManager.IsSporkActive(<API key>)) { LogPrint(BCLog::INSTANTSEND, "%s: spork3 is off, skipping transaction locking checks\n", __func__); return false; } return true; } } // namespace llmq
<?php use Monolog\Logger; use Monolog\Handler\StreamHandler; /** * @param $url * @return string */ function downloadData($url) { $logger = new Logger('cURL'); $logger->pushHandler(new StreamHandler(__DIR__ . '/log/libraryError.log', Logger::DEBUG)); try { $userAgent = "Mozilla/5.0 (en-us;)"; $curl = curl_init(); curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); curl_setopt($curl, CURLOPT_TIMEOUT, 12); curl_setopt($curl, CURLOPT_POST, false); curl_setopt($curl, <API key>, false); curl_setopt($curl, CURLOPT_ENCODING, ""); $headers = array(); $headers[] = "Connection: keep-alive"; $headers[] = "Keep-Alive: timeout=12, max=1000"; curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, <API key>, true); $result = curl_exec($curl); return $result; } catch (Exception $e) { $logger->error("cURL Error: " . $e->getMessage()); return null; } } /** * @param string $url * @param $downloadPath * @return bool */ function downloadLargeData($url, $downloadPath) { $logger = new Logger('cURL'); $logger->pushHandler(new StreamHandler(__DIR__ . '/log/libraryError.log', Logger::DEBUG)); $userAgent = "Mozilla/5.0 (en-us;)"; try { $opts = array( 'http' => array( 'method' => "GET", 'user_agent' => $userAgent, ) ); $context = <API key>($opts); $readHandle = fopen($url, "rb", false, $context); $writeHandle = fopen($downloadPath, "w+b"); if (!$readHandle || !$writeHandle) { return false; } while (!feof($readHandle)) { if (fwrite($writeHandle, fread($readHandle, 4096)) === false) { return false; } } fclose($readHandle); fclose($writeHandle); return true; } catch (Exception $e) { $logger->error("Download Error: " . $e->getMessage()); return false; } }
#include "port.h" #include "../../utils/err.h" int grid_port_resolve (const char *port, size_t portlen) { int res; size_t i; res = 0; for (i = 0; i != portlen; ++i) { if (port [i] < '0' || port [i] > '9') return -EINVAL; res *= 10; res += port [i] - '0'; if (res > 0xffff) return -EINVAL; } if (res == 0) return -EINVAL; return res; }
{ "posts": [ { "url": "/comic/c_chat/2018/01/03/C_ChatM.1514910078.A.4A9.html", "title": " ", "image": "https://pbs.twimg.com/media/DSi2C1lVwAA8ly3.jpg:large", "push": "41", "boo": "0", "date": "2018-01-03 00:21:13 +0800", "boardName": "", "boardLink": "/category/c-chat" } , { "url": "/chat/boy-girl/2018/01/02/Boy-GirlM.1514897829.A.6B8.html", "title": "", "image": "https://i.imgur.com/v5dLZUz.jpg?fb", "push": "21", "boo": "0", "date": "2018-01-02 20:57:06 +0800", "boardName": "", "boardLink": "/category/boy-girl" } , { "url": "/comic/c_chat/2018/01/01/C_ChatM.1514736055.A.555.html", "title": "-", "image": "https://i.imgur.com/dOeSsB0.png", "push": "52", "boo": "1", "date": "2018-01-01 00:00:40 +0800", "boardName": "", "boardLink": "/category/c-chat" } ] }
require 'stringio' # Capture STDOUT and STDERR def capture(*streams) streams.map! { |stream| stream.to_s } begin result = StringIO.new streams.each { |stream| eval "$#{stream} = result" } yield ensure streams.each { |stream| eval("$#{stream} = #{stream.upcase}") } end result.string end
#ifndef <API key> #define <API key> #pragma once #include "ge/subsystem.hpp" #include "ge/<API key>.hpp" #include "ge/<API key>.hpp" #include "Rocket/Core.h" namespace ge { A subsystem for running Rocket struct rocket_subsystem : subsystem { Empty config object, no need for any config yet struct config { }; Initialize function for subsystems bool initialize(config c); Shutdown function for subsystems bool shutdown() override; The rocket context--the subsystem owns it. Rocket::Core::Context* m_context; }; } #endif // <API key>
Version 0.3.12 is now available. Features: * json-rpc errors return a more standard error object. (thanks to Gavin Andresen) * json-rpc command line returns exit codes. * json-rpc "backupwallet" command. * Recovers and continues if an exception is caused by a message you received. Other nodes shouldn't be able to cause an exception, and it hasn't happened before, but if a way is found to cause an exception, this would keep it from being used to stop network nodes. If you have json-rpc code that checks the contents of the error string, you need to change it to expect error objects of the form {"code":<number>,"message":<string>}, which is the standard. See this thread: http: Download: http://sourceforge.net/projects/thalercoin/files/Thalercoin/thalercoin-0.3.12/
using MediatR; using VideoCollection.Data; using VideoCollection.Data.Models; using VideoCollection.Utilities; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using System.Data.Entity; namespace VideoCollection.Features.Tenants { public class RemoveTenantCommand { public class RemoveTenantRequest : IRequest<<API key>> { public int Id { get; set; } } public class <API key> { } public class RemoveTenantHandler : <API key><RemoveTenantRequest, <API key>> { public RemoveTenantHandler(<API key> dataContext, ICache cache) { _dataContext = dataContext; _cache = cache; } public async Task<<API key>> Handle(RemoveTenantRequest request) { var tenant = await _dataContext.Tenants.FindAsync(request.Id); tenant.IsDeleted = true; await _dataContext.SaveChangesAsync(); return new <API key>(); } private readonly <API key> _dataContext; private readonly ICache _cache; } } }
#define CATCHERROR using System; using System.Drawing; using System.IO; using System.Windows.Forms; using Engine; using Engine.Interfaces; using Engine.Xna; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using ButtonState = Microsoft.Xna.Framework.Input.ButtonState; using Keys = Microsoft.Xna.Framework.Input.Keys; using Point = Microsoft.Xna.Framework.Point; namespace Client.WindowsGame { public class GameClient : Game { SpriteBatch spriteBatch; <API key> graphics; private BaseClient client; private IRenderer renderer; public GameClient() : base() { graphics = new <API key>(this); var c = new ContentManager(this.Services); Content.RootDirectory = "Content"; IsMouseVisible = true; TouchPanel.<API key> = true; graphics.<API key> = 1536/2; graphics.<API key> = 2048/2; } protected override void Initialize() { base.Initialize(); } private void ExceptionOccured(Exception exc) { Form form = new Form(); form.Width = 1000; form.Height = 500; TextBox txt = new TextBox(); txt.Multiline = true; txt.Font = new Font(txt.Font.FontFamily, 15); txt.WordWrap = false; txt.ScrollBars = ScrollBars.Both; txt.Dock=DockStyle.Fill; txt.Text = exc.ToString(); form.Controls.Add(txt); form.FormClosed += (sender, args) => this.Exit(); form.Show(); failed = true; } protected override void LoadContent() { if (failed) return; #if CATCHERROR try { #endif spriteBatch = new SpriteBatch(GraphicsDevice); client = new XnaClient({{{projectName}}}, new XnaClientSettings(getKeyboardInput: (callback) => { callback(""); }, oneLayoutAtATime: false, loadFile: s => new StreamReader("Content/" + s), openAppStore: () => { }, rateApp: () => { }, sendEmail: (to, subject, message) => { }) { }, new <API key>(), Content); renderer = new XnaRenderer(GraphicsDevice, Content, graphics, client); client.LoadAssets(renderer); client.Init(renderer); #if CATCHERROR } catch (Exception ex) { ExceptionOccured(ex); } #endif } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } private int mouseX; private int mouseY; private bool mouseIsDown; // private int currentIndex = 0; protected override void Update(GameTime gameTime) { if (failed) return; #if CATCHERROR try { #endif if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); if (Keyboard.GetState().IsKeyDown(Keys.Space)) { // currentIndex = currentIndex == 0 ? 1 : 0; // var screen = client.ScreenManager.Screens.ElementAt(currentIndex); // client.ScreenManager.ChangeScreen(screen); } var layoutManager = client.ScreenManager.CurrentScreen; if (Keyboard.GetState().IsKeyDown(Keys.Left)) { layoutManager.ChangeLayout(Direction.Left); } if (Keyboard.GetState().IsKeyDown(Keys.Right)) { layoutManager.ChangeLayout(Direction.Right); } if (Keyboard.GetState().IsKeyDown(Keys.Up)) { layoutManager.ChangeLayout(Direction.Up); } if (Keyboard.GetState().IsKeyDown(Keys.Down)) { layoutManager.ChangeLayout(Direction.Down); } MouseState mouseState = Mouse.GetState(); if (mouseX != mouseState.X || mouseY != mouseState.Y) { mouseX = mouseState.X; mouseY = mouseState.Y; client.TouchEvent(TouchType.TouchMove, (int)mouseState.X, (int)mouseState.Y); } /* switch (mouseState.LeftButton) { case ButtonState.Pressed: if (!mouseIsDown) { client.TouchEvent(TouchType.TouchDown, (int)mouseState.X, (int)mouseState.Y); } mouseIsDown = true; break; case ButtonState.Released: if (mouseIsDown) { client.TouchEvent(TouchType.TouchUp, (int)mouseState.X, (int)mouseState.Y); mouseIsDown = false; } break; }*/ TouchCollection touchCollection = TouchPanel.GetState(); foreach (var touch in touchCollection) { switch (touch.State) { case TouchLocationState.Moved: client.TouchEvent(TouchType.TouchMove, (int)touch.Position.X, (int)touch.Position.Y); break; case TouchLocationState.Pressed: client.TouchEvent(TouchType.TouchDown, (int)touch.Position.X, (int)touch.Position.Y); break; case TouchLocationState.Released: client.TouchEvent(TouchType.TouchUp, (int)touch.Position.X, (int)touch.Position.Y); break; } } client.Tick(gameTime.TotalGameTime); base.Update(gameTime); #if CATCHERROR } catch (Exception ex) { ExceptionOccured(ex); } #endif } private bool failed = false; protected override void Draw(GameTime gameTime) { if (failed) return; #if CATCHERROR try { #endif GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue); client.Draw(gameTime.TotalGameTime); client.DrawLetterbox(); base.Draw(gameTime); #if CATCHERROR } catch (Exception ex) { ExceptionOccured(ex); } #endif } } }
<?php /** * Include needed Date classes */ require_once 'Zend/Date/DateObject.php'; require_once 'Zend/Locale.php'; require_once 'Zend/Locale/Format.php'; require_once 'Zend/Locale/Math.php'; class Zend_Date extends <API key> { private $_locale = null; // Fractional second variables private $_fractional = 0; private $_precision = 3; private static $_options = array( 'format_type' => 'iso', // format for date strings 'iso' or 'php' 'fix_dst' => true, // fix dst on summer/winter time change 'extend_month' => false, // false - addMonth like SQL, true like excel 'cache' => null, // cache to set 'timesync' => null // timesync server to set ); // Class wide Date Constants const DAY = 'dd'; const DAY_SHORT = 'd'; const DAY_SUFFIX = 'SS'; const DAY_OF_YEAR = 'D'; const WEEKDAY = 'EEEE'; const WEEKDAY_SHORT = 'EEE'; const WEEKDAY_NARROW = 'E'; const WEEKDAY_NAME = 'EE'; const WEEKDAY_8601 = 'eee'; const WEEKDAY_DIGIT = 'e'; const WEEK = 'ww'; const MONTH = 'MM'; const MONTH_SHORT = 'M'; const MONTH_DAYS = 'ddd'; const MONTH_NAME = 'MMMM'; const MONTH_NAME_SHORT = 'MMM'; const MONTH_NAME_NARROW = 'MMMMM'; const YEAR = 'y'; const YEAR_SHORT = 'yy'; const YEAR_8601 = 'Y'; const YEAR_SHORT_8601 = 'YY'; const LEAPYEAR = 'l'; const MERIDIEM = 'a'; const SWATCH = 'B'; const HOUR = 'HH'; const HOUR_SHORT = 'H'; const HOUR_AM = 'hh'; const HOUR_SHORT_AM = 'h'; const MINUTE = 'mm'; const MINUTE_SHORT = 'm'; const SECOND = 'ss'; const SECOND_SHORT = 's'; const MILLISECOND = 'S'; const TIMEZONE_NAME = 'zzzz'; const DAYLIGHT = 'I'; const GMT_DIFF = 'Z'; const GMT_DIFF_SEP = 'ZZZZ'; const TIMEZONE = 'z'; const TIMEZONE_SECS = 'X'; const ISO_8601 = 'c'; const RFC_2822 = 'r'; const TIMESTAMP = 'U'; const ERA = 'G'; const ERA_NAME = 'GGGG'; const ERA_NARROW = 'GGGGG'; const DATES = 'F'; const DATE_FULL = 'FFFFF'; const DATE_LONG = 'FFFF'; const DATE_MEDIUM = 'FFF'; const DATE_SHORT = 'FF'; const TIMES = 'WW'; const TIME_FULL = 'TTTTT'; const TIME_LONG = 'TTTT'; const TIME_MEDIUM = 'TTT'; const TIME_SHORT = 'TT'; const DATETIME = 'K'; const DATETIME_FULL = 'KKKKK'; const DATETIME_LONG = 'KKKK'; const DATETIME_MEDIUM = 'KKK'; const DATETIME_SHORT = 'KK'; const ATOM = 'OOO'; const COOKIE = 'CCC'; const RFC_822 = 'R'; const RFC_850 = 'RR'; const RFC_1036 = 'RRR'; const RFC_1123 = 'RRRR'; const RFC_3339 = 'RRRRR'; const RSS = 'SSS'; const W3C = 'WWW'; public function __construct($date = null, $part = null, $locale = null) { if (is_object($date) and !($date instanceof <API key>) and !($date instanceof Zend_Date)) { if ($locale instanceof Zend_Locale) { $locale = $date; $date = null; $part = null; } else { $date = (string) $date; } } if (($date !== null) and !is_array($date) and !($date instanceof <API key>) and !($date instanceof Zend_Date) and !defined($date) and Zend_Locale::isLocale($date, true, false)) { $locale = $date; $date = null; $part = null; } else if (($part !== null) and !defined($part) and Zend_Locale::isLocale($part, true, false)) { $locale = $part; $part = null; } $this->setLocale($locale); if (is_string($date) && ($part === null) && (strlen($date) <= 5)) { $part = $date; $date = null; } if ($date === null) { if ($part === null) { $date = time(); } else if ($part !== self::TIMESTAMP) { $date = self::now($locale); $date = $date->get($part); } } if ($date instanceof <API key>) { $date = $date->getInfo(); $date = $this->_getTime($date['offset']); $part = null; } else if (parent::$_defaultOffset != 0) { $date = $this->_getTime(parent::$_defaultOffset); } // set the timezone and offset for $this $zone = @<API key>(); $this->setTimezone($zone); // try to get timezone from date-string if (!is_int($date)) { $zone = $this-><API key>($date); $this->setTimezone($zone); } // set datepart if (($part !== null && $part !== self::TIMESTAMP) or (!is_numeric($date))) { // switch off dst handling for value setting $this->setUnixTimestamp($this->getGmtOffset()); $this->set($date, $part, $this->_locale); // DST fix if (is_array($date) === true) { if (!isset($date['hour'])) { $date['hour'] = 0; } $hour = $this->toString('H', 'iso', true); $hour = $date['hour'] - $hour; switch ($hour) { case 1 : case -23 : $this->addTimestamp(3600); break; case -1 : case 23 : $this->subTimestamp(3600); break; case 2 : case -22 : $this->addTimestamp(7200); break; case -2 : case 22 : $this->subTimestamp(7200); break; } } } else { $this->setUnixTimestamp($date); } } /** * Sets class wide options, if no option was given, the actual set options will be returned * * @param array $options Options to set * @throws Zend_Date_Exception * @return Options array if no option was given */ public static function setOptions(array $options = array()) { if (empty($options)) { return self::$_options; } foreach ($options as $name => $value) { $name = strtolower($name); if (array_key_exists($name, self::$_options)) { switch($name) { case 'format_type' : if ((strtolower($value) != 'php') && (strtolower($value) != 'iso')) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("Unknown format type ($value) for dates, only 'iso' and 'php' supported", 0, null, $value); } break; case 'fix_dst' : if (!is_bool($value)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("'fix_dst' has to be boolean", 0, null, $value); } break; case 'extend_month' : if (!is_bool($value)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("'extend_month' has to be boolean", 0, null, $value); } break; case 'cache' : if ($value === null) { parent::$_cache = null; } else { if (!$value instanceof Zend_Cache_Core) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("Instance of Zend_Cache expected"); } parent::$_cache = $value; Zend_Locale_Data::setCache($value); } break; case 'timesync' : if ($value === null) { parent::$_defaultOffset = 0; } else { if (!$value instanceof <API key>) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("Instance of Zend_TimeSync expected"); } $date = $value->getInfo(); parent::$_defaultOffset = $date['offset']; } break; } self::$_options[$name] = $value; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("Unknown option: $name = $value"); } } } public function getTimestamp() { return $this->getUnixTimestamp(); } /** * Returns the calculated timestamp * HINT: timestamps are always GMT * * @param string $calc Type of calculation to make * @param string|integer|array|Zend_Date $stamp Timestamp to calculate, when null the actual timestamp is calculated * @return Zend_Date|integer * @throws Zend_Date_Exception */ private function _timestamp($calc, $stamp) { if ($stamp instanceof Zend_Date) { // extract timestamp from object $stamp = $stamp->getTimestamp(); } if (is_array($stamp)) { if (isset($stamp['timestamp']) === true) { $stamp = $stamp['timestamp']; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('no timestamp given in array'); } } if ($calc === 'set') { $return = $this->setUnixTimestamp($stamp); } else { $return = $this->_calcdetail($calc, $stamp, self::TIMESTAMP, null); } if ($calc != 'cmp') { return $this; } return $return; } /** * Sets a new timestamp * * @param integer|string|array|Zend_Date $timestamp Timestamp to set * @return Zend_Date * @throws Zend_Date_Exception */ public function setTimestamp($timestamp) { return $this->_timestamp('set', $timestamp); } /** * Adds a timestamp * * @param integer|string|array|Zend_Date $timestamp Timestamp to add * @return Zend_Date * @throws Zend_Date_Exception */ public function addTimestamp($timestamp) { return $this->_timestamp('add', $timestamp); } /** * Subtracts a timestamp * * @param integer|string|array|Zend_Date $timestamp Timestamp to sub * @return Zend_Date * @throws Zend_Date_Exception */ public function subTimestamp($timestamp) { return $this->_timestamp('sub', $timestamp); } /** * Compares two timestamps, returning the difference as integer * * @param integer|string|array|Zend_Date $timestamp Timestamp to compare * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareTimestamp($timestamp) { return $this->_timestamp('cmp', $timestamp); } /** * Returns a string representation of the object * Supported format tokens are: * G - era, y - year, Y - ISO year, M - month, w - week of year, D - day of year, d - day of month * E - day of week, e - number of weekday (1-7), h - hour 1-12, H - hour 0-23, m - minute, s - second * A - milliseconds of day, z - timezone, Z - timezone offset, S - fractional second, a - period of day * * Additionally format tokens but non ISO conform are: * SS - day suffix, eee - php number of weekday(0-6), ddd - number of days per month * l - Leap year, B - swatch internet time, I - daylight saving time, X - timezone offset in seconds * r - RFC2822 format, U - unix timestamp * * Not supported ISO tokens are * u - extended year, Q - quarter, q - quarter, L - stand alone month, W - week of month * F - day of week of month, g - modified julian, c - stand alone weekday, k - hour 0-11, K - hour 1-24 * v - wall zone * * @param string $format OPTIONAL Rule for formatting output. If null the default date format is used * @param string $type OPTIONAL Type for the format string which overrides the standard setting * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return string */ public function toString($format = null, $type = null, $locale = null) { if (is_object($format)) { if ($format instanceof Zend_Locale) { $locale = $format; $format = null; } else { $format = (string) $format; } } if (is_object($type)) { if ($type instanceof Zend_Locale) { $locale = $type; $type = null; } else { $type = (string) $type; } } if (($format !== null) and !defined($format) and ($format != 'ee') and ($format != 'ss') and Zend_Locale::isLocale($format, null, false)) { $locale = $format; $format = null; } if (($type !== null) and ($type != 'php') and ($type != 'iso') and Zend_Locale::isLocale($type, null, false)) { $locale = $type; $type = null; } if ($locale === null) { $locale = $this->getLocale(); } if ($format === null) { $format = Zend_Locale_Format::getDateFormat($locale) . ' ' . Zend_Locale_Format::getTimeFormat($locale); } else if (((self::$_options['format_type'] == 'php') && ($type === null)) or ($type == 'php')) { $format = Zend_Locale_Format::<API key>($format); } return $this->date($this->_toToken($format, $locale), $this->getUnixTimestamp(), false); } /** * Returns a string representation of the date which is equal with the timestamp * * @return string */ public function __toString() { return $this->toString(null, $this->_locale); } /** * Returns a integer representation of the object * But returns false when the given part is no value f.e. Month-Name * * @param string|integer|Zend_Date $part OPTIONAL Defines the date or datepart to return as integer * @return integer|false */ public function toValue($part = null) { $result = $this->get($part); if (is_numeric($result)) { return intval("$result"); } else { return false; } } /** * Returns an array representation of the object * * @return array */ public function toArray() { return array('day' => $this->toString(self::DAY_SHORT, 'iso'), 'month' => $this->toString(self::MONTH_SHORT, 'iso'), 'year' => $this->toString(self::YEAR, 'iso'), 'hour' => $this->toString(self::HOUR_SHORT, 'iso'), 'minute' => $this->toString(self::MINUTE_SHORT, 'iso'), 'second' => $this->toString(self::SECOND_SHORT, 'iso'), 'timezone' => $this->toString(self::TIMEZONE, 'iso'), 'timestamp' => $this->toString(self::TIMESTAMP, 'iso'), 'weekday' => $this->toString(self::WEEKDAY_8601, 'iso'), 'dayofyear' => $this->toString(self::DAY_OF_YEAR, 'iso'), 'week' => $this->toString(self::WEEK, 'iso'), 'gmtsecs' => $this->toString(self::TIMEZONE_SECS, 'iso')); } /** * Returns a representation of a date or datepart * This could be for example a localized monthname, the time without date, * the era or only the fractional seconds. There are about 50 different supported date parts. * For a complete list of supported datepart values look into the docu * * @param string $part OPTIONAL Part of the date to return, if null the timestamp is returned * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return string date or datepart */ public function get($part = null, $locale = null) { if ($locale === null) { $locale = $this->getLocale(); } if (($part !== null) and !defined($part) and ($part != 'ee') and ($part != 'ss') and Zend_Locale::isLocale($part, null, false)) { $locale = $part; $part = null; } if ($part === null) { $part = self::TIMESTAMP; } else if (self::$_options['format_type'] == 'php') { $part = Zend_Locale_Format::<API key>($part); } return $this->date($this->_toToken($part, $locale), $this->getUnixTimestamp(), false); } /** * Internal method to apply tokens * * @param string $part * @param string $locale * @return string */ private function _toToken($part, $locale) { // get format tokens $comment = false; $format = ''; $orig = ''; for ($i = 0; $i < strlen($part); ++$i) { if ($part[$i] == "'") { $comment = $comment ? false : true; if (isset($part[$i+1]) && ($part[$i+1] == "'")) { $comment = $comment ? false : true; $format .= "\\'"; ++$i; } $orig = ''; continue; } if ($comment) { $format .= '\\' . $part[$i]; $orig = ''; } else { $orig .= $part[$i]; if (!isset($part[$i+1]) || (isset($orig[0]) && ($orig[0] != $part[$i+1]))) { $format .= $this->_parseIsoToDate($orig, $locale); $orig = ''; } } } return $format; } /** * Internal parsing method * * @param string $token * @param string $locale * @return string */ private function _parseIsoToDate($token, $locale) { switch($token) { case self::DAY : return 'd'; break; case self::WEEKDAY_SHORT : $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); $day = Zend_Locale_Data::getContent($locale, 'day', array('gregorian', 'format', 'wide', $weekday)); return $this->_toComment(iconv_substr($day, 0, 3, 'UTF-8')); break; case self::DAY_SHORT : return 'j'; break; case self::WEEKDAY : $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); return $this->_toComment(Zend_Locale_Data::getContent($locale, 'day', array('gregorian', 'format', 'wide', $weekday))); break; case self::WEEKDAY_8601 : return 'N'; break; case 'ee' : return $this->_toComment(str_pad($this->date('N', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); break; case self::DAY_SUFFIX : return 'S'; break; case self::WEEKDAY_DIGIT : return 'w'; break; case self::DAY_OF_YEAR : return 'z'; break; case 'DDD' : return $this->_toComment(str_pad($this->date('z', $this->getUnixTimestamp(), false), 3, '0', STR_PAD_LEFT)); break; case 'DD' : return $this->_toComment(str_pad($this->date('z', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); break; case self::WEEKDAY_NARROW : case 'EEEEE' : $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); $day = Zend_Locale_Data::getContent($locale, 'day', array('gregorian', 'format', 'abbreviated', $weekday)); return $this->_toComment(iconv_substr($day, 0, 1, 'UTF-8')); break; case self::WEEKDAY_NAME : $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); return $this->_toComment(Zend_Locale_Data::getContent($locale, 'day', array('gregorian', 'format', 'abbreviated', $weekday))); break; case 'w' : $week = $this->date('W', $this->getUnixTimestamp(), false); return $this->_toComment(($week[0] == '0') ? $week[1] : $week); break; case self::WEEK : return 'W'; break; case self::MONTH_NAME : $month = $this->date('n', $this->getUnixTimestamp(), false); return $this->_toComment(Zend_Locale_Data::getContent($locale, 'month', array('gregorian', 'format', 'wide', $month))); break; case self::MONTH : return 'm'; break; case self::MONTH_NAME_SHORT : $month = $this->date('n', $this->getUnixTimestamp(), false); return $this->_toComment(Zend_Locale_Data::getContent($locale, 'month', array('gregorian', 'format', 'abbreviated', $month))); break; case self::MONTH_SHORT : return 'n'; break; case self::MONTH_DAYS : return 't'; break; case self::MONTH_NAME_NARROW : $month = $this->date('n', $this->getUnixTimestamp(), false); $mon = Zend_Locale_Data::getContent($locale, 'month', array('gregorian', 'format', 'abbreviated', $month)); return $this->_toComment(iconv_substr($mon, 0, 1, 'UTF-8')); break; case self::LEAPYEAR : return 'L'; break; case self::YEAR_8601 : return 'o'; break; case self::YEAR : return 'Y'; break; case self::YEAR_SHORT : return 'y'; break; case self::YEAR_SHORT_8601 : return $this->_toComment(substr($this->date('o', $this->getUnixTimestamp(), false), -2, 2)); break; case self::MERIDIEM : $am = $this->date('a', $this->getUnixTimestamp(), false); if ($am == 'am') { return $this->_toComment(Zend_Locale_Data::getContent($locale, 'am')); } return $this->_toComment(Zend_Locale_Data::getContent($locale, 'pm')); break; case self::SWATCH : return 'B'; break; case self::HOUR_SHORT_AM : return 'g'; break; case self::HOUR_SHORT : return 'G'; break; case self::HOUR_AM : return 'h'; break; case self::HOUR : return 'H'; break; case self::MINUTE : return $this->_toComment(str_pad($this->date('i', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); break; case self::SECOND : return $this->_toComment(str_pad($this->date('s', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); break; case self::MINUTE_SHORT : return 'i'; break; case self::SECOND_SHORT : return 's'; break; case self::MILLISECOND : return $this->_toComment($this->getMilliSecond()); break; case self::TIMEZONE_NAME : case 'vvvv' : return 'e'; break; case self::DAYLIGHT : return 'I'; break; case self::GMT_DIFF : case 'ZZ' : case 'ZZZ' : return 'O'; break; case self::GMT_DIFF_SEP : return 'P'; break; case self::TIMEZONE : case 'v' : case 'zz' : case 'zzz' : return 'T'; break; case self::TIMEZONE_SECS : return 'Z'; break; case self::ISO_8601 : return 'c'; break; case self::RFC_2822 : return 'r'; break; case self::TIMESTAMP : return 'U'; break; case self::ERA : case 'GG' : case 'GGG' : $year = $this->date('Y', $this->getUnixTimestamp(), false); if ($year < 0) { return $this->_toComment(Zend_Locale_Data::getContent($locale, 'era', array('gregorian', 'Abbr', '0'))); } return $this->_toComment(Zend_Locale_Data::getContent($locale, 'era', array('gregorian', 'Abbr', '1'))); break; case self::ERA_NARROW : $year = $this->date('Y', $this->getUnixTimestamp(), false); if ($year < 0) { return $this->_toComment(iconv_substr(Zend_Locale_Data::getContent($locale, 'era', array('gregorian', 'Abbr', '0')), 0, 1, 'UTF-8')) . '.'; } return $this->_toComment(iconv_substr(Zend_Locale_Data::getContent($locale, 'era', array('gregorian', 'Abbr', '1')), 0, 1, 'UTF-8')) . '.'; break; case self::ERA_NAME : $year = $this->date('Y', $this->getUnixTimestamp(), false); if ($year < 0) { return $this->_toComment(Zend_Locale_Data::getContent($locale, 'era', array('gregorian', 'Names', '0'))); } return $this->_toComment(Zend_Locale_Data::getContent($locale, 'era', array('gregorian', 'Names', '1'))); break; case self::DATES : return $this->_toToken(Zend_Locale_Format::getDateFormat($locale), $locale); break; case self::DATE_FULL : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'full')), $locale); break; case self::DATE_LONG : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'long')), $locale); break; case self::DATE_MEDIUM : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'medium')), $locale); break; case self::DATE_SHORT : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'short')), $locale); break; case self::TIMES : return $this->_toToken(Zend_Locale_Format::getTimeFormat($locale), $locale); break; case self::TIME_FULL : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'time', 'full'), $locale); break; case self::TIME_LONG : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'time', 'long'), $locale); break; case self::TIME_MEDIUM : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'time', 'medium'), $locale); break; case self::TIME_SHORT : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'time', 'short'), $locale); break; case self::DATETIME : return $this->_toToken(Zend_Locale_Format::getDateTimeFormat($locale), $locale); break; case self::DATETIME_FULL : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'full')), $locale); break; case self::DATETIME_LONG : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'long')), $locale); break; case self::DATETIME_MEDIUM : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'medium')), $locale); break; case self::DATETIME_SHORT : return $this->_toToken(Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'short')), $locale); break; case self::ATOM : return 'Y\-m\-d\TH\:i\:sP'; break; case self::COOKIE : return 'l\, d\-M\-y H\:i\:s e'; break; case self::RFC_822 : return 'D\, d M y H\:i\:s O'; break; case self::RFC_850 : return 'l\, d\-M\-y H\:i\:s e'; break; case self::RFC_1036 : return 'D\, d M y H\:i\:s O'; break; case self::RFC_1123 : return 'D\, d M Y H\:i\:s O'; break; case self::RFC_3339 : return 'Y\-m\-d\TH\:i\:sP'; break; case self::RSS : return 'D\, d M Y H\:i\:s O'; break; case self::W3C : return 'Y\-m\-d\TH\:i\:sP'; break; } if ($token == '') { return ''; } switch ($token[0]) { case 'y' : if ((strlen($token) == 4) && (abs($this->getUnixTimestamp()) <= 0x7FFFFFFF)) { return 'Y'; } $length = iconv_strlen($token, 'UTF-8'); return $this->_toComment(str_pad($this->date('Y', $this->getUnixTimestamp(), false), $length, '0', STR_PAD_LEFT)); break; case 'Y' : if ((strlen($token) == 4) && (abs($this->getUnixTimestamp()) <= 0x7FFFFFFF)) { return 'o'; } $length = iconv_strlen($token, 'UTF-8'); return $this->_toComment(str_pad($this->date('o', $this->getUnixTimestamp(), false), $length, '0', STR_PAD_LEFT)); break; case 'A' : $length = iconv_strlen($token, 'UTF-8'); $result = substr($this->getMilliSecond(), 0, 3); $result += $this->date('s', $this->getUnixTimestamp(), false) * 1000; $result += $this->date('i', $this->getUnixTimestamp(), false) * 60000; $result += $this->date('H', $this->getUnixTimestamp(), false) * 3600000; return $this->_toComment(str_pad($result, $length, '0', STR_PAD_LEFT)); break; } return $this->_toComment($token); } /** * Private function to make a comment of a token * * @param string $token * @return string */ private function _toComment($token) { $token = str_split($token); $result = ''; foreach ($token as $tok) { $result .= '\\' . $tok; } return $result; } /** * Return digit from standard names (english) * Faster implementation than locale aware searching * * @param string $name * @return integer Number of this month * @throws Zend_Date_Exception */ private function _getDigitFromName($name) { switch($name) { case "Jan": return 1; case "Feb": return 2; case "Mar": return 3; case "Apr": return 4; case "May": return 5; case "Jun": return 6; case "Jul": return 7; case "Aug": return 8; case "Sep": return 9; case "Oct": return 10; case "Nov": return 11; case "Dec": return 12; default: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('Month ($name) is not a known month'); } } /** * Counts the exact year number * < 70 - 2000 added, >70 < 100 - 1900, others just returned * * @param integer $value year number * @return integer Number of year */ public static function getFullYear($value) { if ($value >= 0) { if ($value < 70) { $value += 2000; } else if ($value < 100) { $value += 1900; } } return $value; } /** * Sets the given date as new date or a given datepart as new datepart returning the new datepart * This could be for example a localized dayname, the date without time, * the month or only the seconds. There are about 50 different supported date parts. * For a complete list of supported datepart values look into the docu * * @param string|integer|array|Zend_Date $date Date or datepart to set * @param string $part OPTIONAL Part of the date to set, if null the timestamp is set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date Provides fluid interface * @throws Zend_Date_Exception */ public function set($date, $part = null, $locale = null) { if (self::$_options['format_type'] == 'php') { $part = Zend_Locale_Format::<API key>($part); } $zone = $this-><API key>($date); $this->setTimezone($zone); $this->_calculate('set', $date, $part, $locale); return $this; } /** * Adds a date or datepart to the existing date, by extracting $part from $date, * and modifying this object by adding that part. The $part is then extracted from * this object and returned as an integer or numeric string (for large values, or $part's * corresponding to pre-defined formatted date strings). * This could be for example a ISO 8601 date, the hour the monthname or only the minute. * There are about 50 different supported date parts. * For a complete list of supported datepart values look into the docu. * * @param string|integer|array|Zend_Date $date Date or datepart to add * @param string $part OPTIONAL Part of the date to add, if null the timestamp is added * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|string new datepart * @throws Zend_Date_Exception */ public function add($date, $part = self::TIMESTAMP, $locale = null) { if (self::$_options['format_type'] == 'php') { $part = Zend_Locale_Format::<API key>($part); } $this->_calculate('add', $date, $part, $locale); return $this; } /** * Subtracts a date from another date. * This could be for example a RFC2822 date, the time, * the year or only the timestamp. There are about 50 different supported date parts. * For a complete list of supported datepart values look into the docu * Be aware: Adding -2 Months is not equal to Subtracting 2 Months !!! * * @param string|integer|array|Zend_Date $date Date or datepart to subtract * @param string $part OPTIONAL Part of the date to sub, if null the timestamp is subtracted * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|string new datepart * @throws Zend_Date_Exception */ public function sub($date, $part = self::TIMESTAMP, $locale = null) { if (self::$_options['format_type'] == 'php') { $part = Zend_Locale_Format::<API key>($part); } $this->_calculate('sub', $date, $part, $locale); return $this; } /** * Compares a date or datepart with the existing one. * Returns -1 if earlier, 0 if equal and 1 if later. * * @param string|integer|array|Zend_Date $date Date or datepart to compare with the date object * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is subtracted * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compare($date, $part = null, $locale = null) { if (self::$_options['format_type'] == 'php') { $part = Zend_Locale_Format::<API key>($part); } $compare = $this->_calculate('cmp', $date, $part, $locale); if ($compare > 0) { return 1; } else if ($compare < 0) { return -1; } return 0; } /** * Returns a new instance of Zend_Date with the selected part copied. * To make an exact copy, use PHP's clone keyword. * For a complete list of supported date part values look into the docu. * If a date part is copied, all other date parts are set to standard values. * For example: If only YEAR is copied, the returned date object is equal to * 01-01-YEAR 00:00:00 (01-01-1970 00:00:00 is equal to timestamp 0) * If only HOUR is copied, the returned date object is equal to * 01-01-1970 HOUR:00:00 (so $this contains a timestamp equal to a timestamp of 0 plus HOUR). * * @param string $part Part of the date to compare, if null the timestamp is subtracted * @param string|Zend_Locale $locale OPTIONAL New object's locale. No adjustments to timezone are made. * @return Zend_Date */ public function copyPart($part, $locale = null) { $clone = clone $this; // copy all instance variables $clone->setUnixTimestamp(0); // except the timestamp if ($locale != null) { $clone->setLocale($locale); // set an other locale if selected } $clone->set($this, $part); return $clone; } /** * Internal function, returns the offset of a given timezone * * @param string $zone * @return integer */ public function <API key>($zone) { if (is_array($zone)) { return $this->getTimezone(); } if ($zone instanceof Zend_Date) { return $zone->getTimezone(); } $match = array(); preg_match('/\dZ$/', $zone, $match); if (!empty($match)) { return "Etc/UTC"; } preg_match('/([+-]\d{2}):{0,1}\d{2}/', $zone, $match); if (!empty($match) and ($match[count($match) - 1] <= 12) and ($match[count($match) - 1] >= -12)) { $zone = "Etc/GMT"; $zone .= ($match[count($match) - 1] < 0) ? "+" : "-"; $zone .= (int) abs($match[count($match) - 1]); return $zone; } preg_match('/([[:alpha:]\/]{3,30})(?!.*([[:alpha:]\/]{3,30}))/', $zone, $match); try { if (!empty($match) and (!is_int($match[count($match) - 1]))) { $oldzone = $this->getTimezone(); $this->setTimezone($match[count($match) - 1]); $result = $this->getTimezone(); $this->setTimezone($oldzone); if ($result !== $oldzone) { return $match[count($match) - 1]; } } } catch (Exception $e) { // fall through } return $this->getTimezone(); } /** * Calculates the date or object * * @param string $calc Calculation to make * @param string|integer $date Date for calculation * @param string|integer $comp Second date for calculation * @param boolean|integer $dst Use dst correction if option is set * @return integer|string|Zend_Date new timestamp or Zend_Date depending on calculation */ private function _assign($calc, $date, $comp = 0, $dst = false) { switch ($calc) { case 'set' : if (!empty($comp)) { $this->setUnixTimestamp(call_user_func(Zend_Locale_Math::$sub, $this->getUnixTimestamp(), $comp)); } $this->setUnixTimestamp(call_user_func(Zend_Locale_Math::$add, $this->getUnixTimestamp(), $date)); $value = $this->getUnixTimestamp(); break; case 'add' : $this->setUnixTimestamp(call_user_func(Zend_Locale_Math::$add, $this->getUnixTimestamp(), $date)); $value = $this->getUnixTimestamp(); break; case 'sub' : $this->setUnixTimestamp(call_user_func(Zend_Locale_Math::$sub, $this->getUnixTimestamp(), $date)); $value = $this->getUnixTimestamp(); break; default : // cmp - compare return call_user_func(Zend_Locale_Math::$comp, $comp, $date); break; } // dst-correction if 'fix_dst' = true and dst !== false but only for non UTC and non GMT if ((self::$_options['fix_dst'] === true) and ($dst !== false) and ($this->_dst === true)) { $hour = $this->toString(self::HOUR, 'iso'); if ($hour != $dst) { if (($dst == ($hour + 1)) or ($dst == ($hour - 23))) { $value += 3600; } else if (($dst == ($hour - 1)) or ($dst == ($hour + 23))) { $value -= 3600; } $this->setUnixTimestamp($value); } } return $this->getUnixTimestamp(); } /** * Calculates the date or object * * @param string $calc Calculation to make, one of: 'add'|'sub'|'cmp'|'copy'|'set' * @param string|integer|array|Zend_Date $date Date or datepart to calculate with * @param string $part Part of the date to calculate, if null the timestamp is used * @param string|Zend_Locale $locale Locale for parsing input * @return integer|string|Zend_Date new timestamp * @throws Zend_Date_Exception */ private function _calculate($calc, $date, $part, $locale) { if ($date === null) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('parameter $date must be set, null is not allowed'); } if (($part !== null) && (strlen($part) !== 2) && (Zend_Locale::isLocale($part, null, false))) { $locale = $part; $part = null; } if ($locale === null) { $locale = $this->getLocale(); } $locale = (string) $locale; // Create date parts $year = $this->toString(self::YEAR, 'iso'); $month = $this->toString(self::MONTH_SHORT, 'iso'); $day = $this->toString(self::DAY_SHORT, 'iso'); $hour = $this->toString(self::HOUR_SHORT, 'iso'); $minute = $this->toString(self::MINUTE_SHORT, 'iso'); $second = $this->toString(self::SECOND_SHORT, 'iso'); // If object extract value if ($date instanceof Zend_Date) { $date = $date->toString($part, 'iso', $locale); } if (is_array($date) === true) { if (empty($part) === false) { switch($part) { // Fall through case self::DAY: case self::DAY_SHORT: if (isset($date['day']) === true) { $date = $date['day']; } break; // Fall through case self::WEEKDAY_SHORT: case self::WEEKDAY: case self::WEEKDAY_8601: case self::WEEKDAY_DIGIT: case self::WEEKDAY_NARROW: case self::WEEKDAY_NAME: if (isset($date['weekday']) === true) { $date = $date['weekday']; $part = self::WEEKDAY_DIGIT; } break; case self::DAY_OF_YEAR: if (isset($date['day_of_year']) === true) { $date = $date['day_of_year']; } break; // Fall through case self::MONTH: case self::MONTH_SHORT: case self::MONTH_NAME: case self::MONTH_NAME_SHORT: case self::MONTH_NAME_NARROW: if (isset($date['month']) === true) { $date = $date['month']; } break; // Fall through case self::YEAR: case self::YEAR_SHORT: case self::YEAR_8601: case self::YEAR_SHORT_8601: if (isset($date['year']) === true) { $date = $date['year']; } break; // Fall through case self::HOUR: case self::HOUR_AM: case self::HOUR_SHORT: case self::HOUR_SHORT_AM: if (isset($date['hour']) === true) { $date = $date['hour']; } break; // Fall through case self::MINUTE: case self::MINUTE_SHORT: if (isset($date['minute']) === true) { $date = $date['minute']; } break; // Fall through case self::SECOND: case self::SECOND_SHORT: if (isset($date['second']) === true) { $date = $date['second']; } break; // Fall through case self::TIMEZONE: case self::TIMEZONE_NAME: if (isset($date['timezone']) === true) { $date = $date['timezone']; } break; case self::TIMESTAMP: if (isset($date['timestamp']) === true) { $date = $date['timestamp']; } break; case self::WEEK: if (isset($date['week']) === true) { $date = $date['week']; } break; case self::TIMEZONE_SECS: if (isset($date['gmtsecs']) === true) { $date = $date['gmtsecs']; } break; default: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("datepart for part ($part) not found in array"); break; } } else { $hours = 0; if (isset($date['hour']) === true) { $hours = $date['hour']; } $minutes = 0; if (isset($date['minute']) === true) { $minutes = $date['minute']; } $seconds = 0; if (isset($date['second']) === true) { $seconds = $date['second']; } $months = 0; if (isset($date['month']) === true) { $months = $date['month']; } $days = 0; if (isset($date['day']) === true) { $days = $date['day']; } $years = 0; if (isset($date['year']) === true) { $years = $date['year']; } return $this->_assign($calc, $this->mktime($hours, $minutes, $seconds, $months, $days, $years, true), $this->mktime($hour, $minute, $second, $month, $day, $year, true), $hour); } } // $date as object, part of foreign date as own date switch($part) { // day formats case self::DAY: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), $this->mktime(0, 0, 0, 1, 1 + intval($day), 1970, true), $hour); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, day expected", 0, null, $date); break; case self::WEEKDAY_SHORT: $daylist = Zend_Locale_Data::getList($locale, 'day'); $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); $cnt = 0; foreach ($daylist as $key => $value) { if (strtoupper(iconv_substr($value, 0, 3, 'UTF-8')) == strtoupper($date)) { $found = $cnt; break; } ++$cnt; } // Weekday found if ($cnt < 7) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } // Weekday not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, weekday expected", 0, null, $date); break; case self::DAY_SHORT: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), $this->mktime(0, 0, 0, 1, 1 + intval($day), 1970, true), $hour); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, day expected", 0, null, $date); break; case self::WEEKDAY: $daylist = Zend_Locale_Data::getList($locale, 'day'); $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); $cnt = 0; foreach ($daylist as $key => $value) { if (strtoupper($value) == strtoupper($date)) { $found = $cnt; break; } ++$cnt; } // Weekday found if ($cnt < 7) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } // Weekday not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, weekday expected", 0, null, $date); break; case self::WEEKDAY_8601: $weekday = (int) $this->toString(self::WEEKDAY_8601, 'iso', $locale); if ((intval($date) > 0) and (intval($date) < 8)) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } // Weekday not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, weekday expected", 0, null, $date); break; case self::DAY_SUFFIX: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('day suffix not supported', 0, null, $date); break; case self::WEEKDAY_DIGIT: $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); if (is_numeric($date) and (intval($date) >= 0) and (intval($date) < 7)) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $date, 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } // Weekday not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, weekday expected", 0, null, $date); break; case self::DAY_OF_YEAR: if (is_numeric($date)) { if (($calc == 'add') || ($calc == 'sub')) { $year = 1970; ++$date; ++$day; } return $this->_assign($calc, $this->mktime(0, 0, 0, 1, $date, $year, true), $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, day expected", 0, null, $date); break; case self::WEEKDAY_NARROW: $daylist = Zend_Locale_Data::getList($locale, 'day', array('gregorian', 'format', 'abbreviated')); $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); $cnt = 0; foreach ($daylist as $key => $value) { if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) == strtoupper($date)) { $found = $cnt; break; } ++$cnt; } // Weekday found if ($cnt < 7) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } // Weekday not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, weekday expected", 0, null, $date); break; case self::WEEKDAY_NAME: $daylist = Zend_Locale_Data::getList($locale, 'day', array('gregorian', 'format', 'abbreviated')); $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); $cnt = 0; foreach ($daylist as $key => $value) { if (strtoupper($value) == strtoupper($date)) { $found = $cnt; break; } ++$cnt; } // Weekday found if ($cnt < 7) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } // Weekday not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, weekday expected", 0, null, $date); break; // week formats case self::WEEK: if (is_numeric($date)) { $week = (int) $this->toString(self::WEEK, 'iso', $locale); return $this->_assign($calc, parent::mktime(0, 0, 0, 1, 1 + ($date * 7), 1970, true), parent::mktime(0, 0, 0, 1, 1 + ($week * 7), 1970, true), $hour); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, week expected", 0, null, $date); break; // month formats case self::MONTH_NAME: $monthlist = Zend_Locale_Data::getList($locale, 'month'); $cnt = 0; foreach ($monthlist as $key => $value) { if (strtoupper($value) == strtoupper($date)) { $found = $key; break; } ++$cnt; } $date = array_search($date, $monthlist); // Monthname found if ($cnt < 12) { $fixday = 0; if ($calc == 'add') { $date += $found; $calc = 'set'; if (self::$_options['extend_month'] == false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } else if ($calc == 'sub') { $date = $month - $found; $calc = 'set'; if (self::$_options['extend_month'] == false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); } // Monthname not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, month expected", 0, null, $date); break; case self::MONTH: if (is_numeric($date)) { $fixday = 0; if ($calc == 'add') { $date += $month; $calc = 'set'; if (self::$_options['extend_month'] == false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } else if ($calc == 'sub') { $date = $month - $date; $calc = 'set'; if (self::$_options['extend_month'] == false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, month expected", 0, null, $date); break; case self::MONTH_NAME_SHORT: $monthlist = Zend_Locale_Data::getList($locale, 'month', array('gregorian', 'format', 'abbreviated')); $cnt = 0; foreach ($monthlist as $key => $value) { if (strtoupper($value) == strtoupper($date)) { $found = $key; break; } ++$cnt; } $date = array_search($date, $monthlist); // Monthname found if ($cnt < 12) { $fixday = 0; if ($calc == 'add') { $date += $found; $calc = 'set'; if (self::$_options['extend_month'] === false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } else if ($calc == 'sub') { $date = $month - $found; $calc = 'set'; if (self::$_options['extend_month'] === false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); } // Monthname not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, month expected", 0, null, $date); break; case self::MONTH_SHORT: if (is_numeric($date) === true) { $fixday = 0; if ($calc === 'add') { $date += $month; $calc = 'set'; if (self::$_options['extend_month'] === false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } else if ($calc === 'sub') { $date = $month - $date; $calc = 'set'; if (self::$_options['extend_month'] === false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, month expected", 0, null, $date); break; case self::MONTH_DAYS: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('month days not supported', 0, null, $date); break; case self::MONTH_NAME_NARROW: $monthlist = Zend_Locale_Data::getList($locale, 'month', array('gregorian', 'stand-alone', 'narrow')); $cnt = 0; foreach ($monthlist as $key => $value) { if (strtoupper($value) === strtoupper($date)) { $found = $key; break; } ++$cnt; } $date = array_search($date, $monthlist); // Monthname found if ($cnt < 12) { $fixday = 0; if ($calc === 'add') { $date += $found; $calc = 'set'; if (self::$_options['extend_month'] === false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } else if ($calc === 'sub') { $date = $month - $found; $calc = 'set'; if (self::$_options['extend_month'] === false) { $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); if ($parts['mday'] != $day) { $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } } return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); } // Monthname not found require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, month expected", 0, null, $date); break; // year formats case self::LEAPYEAR: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('leap year not supported', 0, null, $date); break; case self::YEAR_8601: if (is_numeric($date)) { if ($calc === 'add') { $date += $year; $calc = 'set'; } else if ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, intval($date), true), $this->mktime(0, 0, 0, $month, $day, $year, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, year expected", 0, null, $date); break; case self::YEAR: if (is_numeric($date)) { if ($calc === 'add') { $date += $year; $calc = 'set'; } else if ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, intval($date), true), $this->mktime(0, 0, 0, $month, $day, $year, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, year expected", 0, null, $date); break; case self::YEAR_SHORT: if (is_numeric($date)) { $date = intval($date); if (($calc == 'set') || ($calc == 'cmp')) { $date = self::getFullYear($date); } if ($calc === 'add') { $date += $year; $calc = 'set'; } else if ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, $date, true), $this->mktime(0, 0, 0, $month, $day, $year, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, year expected", 0, null, $date); break; case self::YEAR_SHORT_8601: if (is_numeric($date)) { $date = intval($date); if (($calc === 'set') || ($calc === 'cmp')) { $date = self::getFullYear($date); } if ($calc === 'add') { $date += $year; $calc = 'set'; } else if ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, $date, true), $this->mktime(0, 0, 0, $month, $day, $year, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, year expected", 0, null, $date); break; // time formats case self::MERIDIEM: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('meridiem not supported', 0, null, $date); break; case self::SWATCH: if (is_numeric($date)) { $rest = intval($date); $hours = floor($rest * 24 / 1000); $rest = $rest - ($hours * 1000 / 24); $minutes = floor($rest * 1440 / 1000); $rest = $rest - ($minutes * 1000 / 1440); $seconds = floor($rest * 86400 / 1000); return $this->_assign($calc, $this->mktime($hours, $minutes, $seconds, 1, 1, 1970, true), $this->mktime($hour, $minute, $second, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, swatchstamp expected", 0, null, $date); break; case self::HOUR_SHORT_AM: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, hour expected", 0, null, $date); break; case self::HOUR_SHORT: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, hour expected", 0, null, $date); break; case self::HOUR_AM: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, hour expected", 0, null, $date); break; case self::HOUR: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, hour expected", 0, null, $date); break; case self::MINUTE: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(0, intval($date), 0, 1, 1, 1970, true), $this->mktime(0, $minute, 0, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, minute expected", 0, null, $date); break; case self::SECOND: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(0, 0, intval($date), 1, 1, 1970, true), $this->mktime(0, 0, $second, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, second expected", 0, null, $date); break; case self::MILLISECOND: if (is_numeric($date)) { switch($calc) { case 'set' : return $this->setMillisecond($date); break; case 'add' : return $this->addMillisecond($date); break; case 'sub' : return $this->subMillisecond($date); break; } return $this->compareMillisecond($date); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, milliseconds expected", 0, null, $date); break; case self::MINUTE_SHORT: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(0, intval($date), 0, 1, 1, 1970, true), $this->mktime(0, $minute, 0, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, minute expected", 0, null, $date); break; case self::SECOND_SHORT: if (is_numeric($date)) { return $this->_assign($calc, $this->mktime(0, 0, intval($date), 1, 1, 1970, true), $this->mktime(0, 0, $second, 1, 1, 1970, true), false); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, second expected", 0, null, $date); break; // timezone formats // break intentionally omitted case self::TIMEZONE_NAME: case self::TIMEZONE: case self::TIMEZONE_SECS: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('timezone not supported', 0, null, $date); break; case self::DAYLIGHT: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('daylight not supported', 0, null, $date); break; case self::GMT_DIFF: case self::GMT_DIFF_SEP: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('gmtdiff not supported', 0, null, $date); break; // date strings case self::ISO_8601: // (-)YYYY-MM-dd preg_match('/^(-{0,1}\d{4})-(\d{2})-(\d{2})/', $date, $datematch); // (-)YY-MM-dd if (empty($datematch)) { preg_match('/^(-{0,1}\d{2})-(\d{2})-(\d{2})/', $date, $datematch); } // (-)YYYYMMdd if (empty($datematch)) { preg_match('/^(-{0,1}\d{4})(\d{2})(\d{2})/', $date, $datematch); } // (-)YYMMdd if (empty($datematch)) { preg_match('/^(-{0,1}\d{2})(\d{2})(\d{2})/', $date, $datematch); } $tmpdate = $date; if (!empty($datematch)) { $dateMatchCharCount = iconv_strlen($datematch[0], 'UTF-8'); $tmpdate = iconv_substr($date, $dateMatchCharCount, iconv_strlen($date, 'UTF-8') - $dateMatchCharCount, 'UTF-8'); } // (T)hh:mm:ss preg_match('/[T,\s]{0,1}(\d{2}):(\d{2}):(\d{2})/', $tmpdate, $timematch); if (empty($timematch)) { preg_match('/[T,\s]{0,1}(\d{2})(\d{2})(\d{2})/', $tmpdate, $timematch); } if (empty($datematch) and empty($timematch)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("unsupported ISO8601 format ($date)", 0, null, $date); } if (!empty($timematch)) { $timeMatchCharCount = iconv_strlen($timematch[0], 'UTF-8'); $tmpdate = iconv_substr($tmpdate, $timeMatchCharCount, iconv_strlen($tmpdate, 'UTF-8') - $timeMatchCharCount, 'UTF-8'); } if (empty($datematch)) { $datematch[1] = 1970; $datematch[2] = 1; $datematch[3] = 1; } else if (iconv_strlen($datematch[1], 'UTF-8') == 2) { $datematch[1] = self::getFullYear($datematch[1]); } if (empty($timematch)) { $timematch[1] = 0; $timematch[2] = 0; $timematch[3] = 0; } if (($calc == 'set') || ($calc == 'cmp')) { --$datematch[2]; --$month; --$datematch[3]; --$day; $datematch[1] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($timematch[1], $timematch[2], $timematch[3], 1 + $datematch[2], 1 + $datematch[3], 1970 + $datematch[1], false), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, false), false); break; case self::RFC_2822: $result = preg_match('/^\w{3},\s(\d{1,2})\s(\w{3})\s(\d{4})\s(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]{1}\d{4})$/', $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("no RFC 2822 format ($date)", 0, null, $date); } $months = $this->_getDigitFromName($match[2]); if (($calc == 'set') || ($calc == 'cmp')) { --$months; --$month; --$match[1]; --$day; $match[3] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], false), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, false), false); break; case self::TIMESTAMP: if (is_numeric($date)) { return $this->_assign($calc, $date, $this->getUnixTimestamp()); } require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, timestamp expected", 0, null, $date); break; // additional formats // break intentionally omitted case self::ERA: case self::ERA_NAME: require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('era not supported', 0, null, $date); break; case self::DATES: try { $parsed = Zend_Locale_Format::getDate($date, array('locale' => $locale, 'format_type' => 'iso', 'fix_date' => true)); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATE_FULL: try { $format = Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'full')); $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATE_LONG: try { $format = Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'long')); $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if (($calc == 'set') || ($calc == 'cmp')){ --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATE_MEDIUM: try { $format = Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'medium')); $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATE_SHORT: try { $format = Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'short')); $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); $parsed['year'] = self::getFullYear($parsed['year']); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::TIMES: try { if ($calc != 'set') { $month = 1; $day = 1; $year = 1970; } $parsed = Zend_Locale_Format::getTime($date, array('locale' => $locale, 'format_type' => 'iso', 'fix_date' => true)); return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::TIME_FULL: try { $format = Zend_Locale_Data::getContent($locale, 'time', array('gregorian', 'full')); $parsed = Zend_Locale_Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if ($calc != 'set') { $month = 1; $day = 1; $year = 1970; } if (!isset($parsed['second'])) { $parsed['second'] = 0; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::TIME_LONG: try { $format = Zend_Locale_Data::getContent($locale, 'time', array('gregorian', 'long')); $parsed = Zend_Locale_Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if ($calc != 'set') { $month = 1; $day = 1; $year = 1970; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::TIME_MEDIUM: try { $format = Zend_Locale_Data::getContent($locale, 'time', array('gregorian', 'medium')); $parsed = Zend_Locale_Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if ($calc != 'set') { $month = 1; $day = 1; $year = 1970; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::TIME_SHORT: try { $format = Zend_Locale_Data::getContent($locale, 'time', array('gregorian', 'short')); $parsed = Zend_Locale_Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if ($calc != 'set') { $month = 1; $day = 1; $year = 1970; } if (!isset($parsed['second'])) { $parsed['second'] = 0; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATETIME: try { $parsed = Zend_Locale_Format::getDateTime($date, array('locale' => $locale, 'format_type' => 'iso', 'fix_date' => true)); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATETIME_FULL: try { $format = Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'full')); $parsed = Zend_Locale_Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } if (!isset($parsed['second'])) { $parsed['second'] = 0; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATETIME_LONG: try { $format = Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'long')); $parsed = Zend_Locale_Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if (($calc == 'set') || ($calc == 'cmp')){ --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATETIME_MEDIUM: try { $format = Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'medium')); $parsed = Zend_Locale_Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; case self::DATETIME_SHORT: try { $format = Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'short')); $parsed = Zend_Locale_Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); $parsed['year'] = self::getFullYear($parsed['year']); if (($calc == 'set') || ($calc == 'cmp')) { --$parsed['month']; --$month; --$parsed['day']; --$day; $parsed['year'] -= 1970; $year -= 1970; } if (!isset($parsed['second'])) { $parsed['second'] = 0; } return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } break; // ATOM and RFC_3339 are identical case self::ATOM: case self::RFC_3339: $result = preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\d{0,4}([+-]{1}\d{2}:\d{2}|Z)$/', $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, ATOM format expected", 0, null, $date); } if (($calc == 'set') || ($calc == 'cmp')) { --$match[2]; --$month; --$match[3]; --$day; $match[1] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $match[2], 1 + $match[3], 1970 + $match[1], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); break; case self::COOKIE: $result = preg_match("/^\w{6,9},\s(\d{2})-(\w{3})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})\s.{3,20}$/", $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, COOKIE format expected", 0, null, $date); } $matchStartPos = iconv_strpos($match[0], ' ', 0, 'UTF-8') + 1; $match[0] = iconv_substr($match[0], $matchStartPos, iconv_strlen($match[0], 'UTF-8') - $matchStartPos, 'UTF-8'); $months = $this->_getDigitFromName($match[2]); $match[3] = self::getFullYear($match[3]); if (($calc == 'set') || ($calc == 'cmp')) { --$months; --$month; --$match[1]; --$day; $match[3] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); break; case self::RFC_822: case self::RFC_1036: // new RFC 822 format, identical to RFC 1036 standard $result = preg_match('/^\w{0,3},{0,1}\s{0,1}(\d{1,2})\s(\w{3})\s(\d{2})\s(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]{1}\d{4}|\w{1,20})$/', $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, RFC 822 date format expected", 0, null, $date); } $months = $this->_getDigitFromName($match[2]); $match[3] = self::getFullYear($match[3]); if (($calc == 'set') || ($calc == 'cmp')) { --$months; --$month; --$match[1]; --$day; $match[3] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], false), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, false), false); break; case self::RFC_850: $result = preg_match('/^\w{6,9},\s(\d{2})-(\w{3})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})\s.{3,21}$/', $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, RFC 850 date format expected", 0, null, $date); } $months = $this->_getDigitFromName($match[2]); $match[3] = self::getFullYear($match[3]); if (($calc == 'set') || ($calc == 'cmp')) { --$months; --$month; --$match[1]; --$day; $match[3] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); break; case self::RFC_1123: $result = preg_match('/^\w{0,3},{0,1}\s{0,1}(\d{1,2})\s(\w{3})\s(\d{2,4})\s(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]{1}\d{4}|\w{1,20})$/', $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, RFC 1123 date format expected", 0, null, $date); } $months = $this->_getDigitFromName($match[2]); if (($calc == 'set') || ($calc == 'cmp')) { --$months; --$month; --$match[1]; --$day; $match[3] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); break; case self::RSS: $result = preg_match('/^\w{3},\s(\d{2})\s(\w{3})\s(\d{2,4})\s(\d{1,2}):(\d{2}):(\d{2})\s.{1,21}$/', $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, RSS date format expected", 0, null, $date); } $months = $this->_getDigitFromName($match[2]); $match[3] = self::getFullYear($match[3]); if (($calc == 'set') || ($calc == 'cmp')) { --$months; --$month; --$match[1]; --$day; $match[3] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); break; case self::W3C: $result = preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})[+-]{1}\d{2}:\d{2}$/', $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid date ($date) operand, W3C date format expected", 0, null, $date); } if (($calc == 'set') || ($calc == 'cmp')) { --$match[2]; --$month; --$match[3]; --$day; $match[1] -= 1970; $year -= 1970; } return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $match[2], 1 + $match[3], 1970 + $match[1], true), $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); break; default: if (!is_numeric($date) || !empty($part)) { try { if (empty($part)) { $part = Zend_Locale_Format::getDateFormat($locale) . " "; $part .= Zend_Locale_Format::getTimeFormat($locale); } $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $part, 'locale' => $locale, 'fix_date' => true, 'format_type' => 'iso')); if ((strpos(strtoupper($part), 'YY') !== false) and (strpos(strtoupper($part), 'YYYY') === false)) { $parsed['year'] = self::getFullYear($parsed['year']); } if (($calc == 'set') || ($calc == 'cmp')) { if (isset($parsed['month'])) { --$parsed['month']; } else { $parsed['month'] = 0; } if (isset($parsed['day'])) { --$parsed['day']; } else { $parsed['day'] = 0; } if (isset($parsed['year'])) { $parsed['year'] -= 1970; } else { $parsed['year'] = 0; } } return $this->_assign($calc, $this->mktime( isset($parsed['hour']) ? $parsed['hour'] : 0, isset($parsed['minute']) ? $parsed['minute'] : 0, isset($parsed['second']) ? $parsed['second'] : 0, isset($parsed['month']) ? (1 + $parsed['month']) : 1, isset($parsed['day']) ? (1 + $parsed['day']) : 1, isset($parsed['year']) ? (1970 + $parsed['year']) : 1970, false), $this->getUnixTimestamp(), false); } catch (<API key> $e) { if (!is_numeric($date)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e, $date); } } } return $this->_assign($calc, $date, $this->getUnixTimestamp(), false); break; } } /** * Returns true when both date objects or date parts are equal. * For example: * 15.May.2000 <-> 15.June.2000 Equals only for Day or Year... all other will return false * * @param string|integer|array|Zend_Date $date Date or datepart to equal with * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is used * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return boolean * @throws Zend_Date_Exception */ public function equals($date, $part = null, $locale = null) { $result = $this->compare($date, $part, $locale); if ($result == 0) { return true; } return false; } /** * Returns if the given date or datepart is earlier * For example: * 15.May.2000 <-> 13.June.1999 will return true for day, year and date, but not for month * * @param string|integer|array|Zend_Date $date Date or datepart to compare with * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is used * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return boolean * @throws Zend_Date_Exception */ public function isEarlier($date, $part = null, $locale = null) { $result = $this->compare($date, $part, $locale); if ($result == -1) { return true; } return false; } /** * Returns if the given date or datepart is later * For example: * 15.May.2000 <-> 13.June.1999 will return true for month but false for day, year and date * Returns if the given date is later * * @param string|integer|array|Zend_Date $date Date or datepart to compare with * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is used * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return boolean * @throws Zend_Date_Exception */ public function isLater($date, $part = null, $locale = null) { $result = $this->compare($date, $part, $locale); if ($result == 1) { return true; } return false; } /** * Returns only the time of the date as new Zend_Date object * For example: * 15.May.2000 10:11:23 will return a dateobject equal to 01.Jan.1970 10:11:23 * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getTime($locale = null) { return $this->copyPart(self::TIME_MEDIUM, $locale); } /** * Returns the calculated time * * @param string $calc Calculation to make * @param string|integer|array|Zend_Date $time Time to calculate with, if null the actual time is taken * @param string $format Timeformat for parsing input * @param string|Zend_Locale $locale Locale for parsing input * @return integer|Zend_Date new time * @throws Zend_Date_Exception */ private function _time($calc, $time, $format, $locale) { if ($time === null) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('parameter $time must be set, null is not allowed'); } if ($time instanceof Zend_Date) { // extract time from object $time = $time->toString('HH:mm:ss', 'iso'); } else { if (is_array($time)) { if ((isset($time['hour']) === true) or (isset($time['minute']) === true) or (isset($time['second']) === true)) { $parsed = $time; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("no hour, minute or second given in array"); } } else { if (self::$_options['format_type'] == 'php') { $format = Zend_Locale_Format::<API key>($format); } try { if ($locale === null) { $locale = $this->getLocale(); } $parsed = Zend_Locale_Format::getTime($time, array('date_format' => $format, 'locale' => $locale, 'format_type' => 'iso')); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e); } } $time = str_pad($parsed['hour'], 2, '0', STR_PAD_LEFT) . ":"; $time .= str_pad($parsed['minute'], 2, '0', STR_PAD_LEFT) . ":"; $time .= str_pad($parsed['second'], 2, '0', STR_PAD_LEFT); } $return = $this->_calcdetail($calc, $time, self::TIMES, 'de'); if ($calc != 'cmp') { return $this; } return $return; } /** * Sets a new time for the date object. Format defines how to parse the time string. * Also a complete date can be given, but only the time is used for setting. * For example: dd.MMMM.yyTHH:mm' and 'ss sec'-> 10.May.07T25:11 and 44 sec => 1h11min44sec + 1 day * Returned is the new date object and the existing date is left as it was before * * @param string|integer|array|Zend_Date $time Time to set * @param string $format OPTIONAL Timeformat for parsing input * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new time * @throws Zend_Date_Exception */ public function setTime($time, $format = null, $locale = null) { return $this->_time('set', $time, $format, $locale); } /** * Adds a time to the existing date. Format defines how to parse the time string. * If only parts are given the other parts are set to 0. * If no format is given, the standardformat of this locale is used. * For example: HH:mm:ss -> 10 -> +10 hours * * @param string|integer|array|Zend_Date $time Time to add * @param string $format OPTIONAL Timeformat for parsing input * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new time * @throws Zend_Date_Exception */ public function addTime($time, $format = null, $locale = null) { return $this->_time('add', $time, $format, $locale); } /** * Subtracts a time from the existing date. Format defines how to parse the time string. * If only parts are given the other parts are set to 0. * If no format is given, the standardformat of this locale is used. * For example: HH:mm:ss -> 10 -> -10 hours * * @param string|integer|array|Zend_Date $time Time to sub * @param string $format OPTIONAL Timeformat for parsing input * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new time * @throws Zend_Date_Exception */ public function subTime($time, $format = null, $locale = null) { return $this->_time('sub', $time, $format, $locale); } /** * Compares the time from the existing date. Format defines how to parse the time string. * If only parts are given the other parts are set to default. * If no format us given, the standardformat of this locale is used. * For example: HH:mm:ss -> 10 -> 10 hours * * @param string|integer|array|Zend_Date $time Time to compare * @param string $format OPTIONAL Timeformat for parsing input * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareTime($time, $format = null, $locale = null) { return $this->_time('cmp', $time, $format, $locale); } /** * Returns a clone of $this, with the time part set to 00:00:00. * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getDate($locale = null) { $date = $this->copyPart(self::DATE_MEDIUM, $locale); $date->addTimestamp($this->getGmtOffset()); return $date; } /** * Returns the calculated date * * @param string $calc Calculation to make * @param string|integer|array|Zend_Date $date Date to calculate with, if null the actual date is taken * @param string $format Date format for parsing * @param string|Zend_Locale $locale Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ private function _date($calc, $date, $format, $locale) { if ($date === null) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('parameter $date must be set, null is not allowed'); } if ($date instanceof Zend_Date) { // extract date from object $date = $date->toString('d.M.y', 'iso'); } else { if (is_array($date)) { if ((isset($date['year']) === true) or (isset($date['month']) === true) or (isset($date['day']) === true)) { $parsed = $date; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("no day,month or year given in array"); } } else { if ((self::$_options['format_type'] == 'php') && !defined($format)) { $format = Zend_Locale_Format::<API key>($format); } try { if ($locale === null) { $locale = $this->getLocale(); } $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $format, 'locale' => $locale, 'format_type' => 'iso')); if ((strpos(strtoupper($format), 'YY') !== false) and (strpos(strtoupper($format), 'YYYY') === false)) { $parsed['year'] = self::getFullYear($parsed['year']); } } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e); } } $date = $parsed['day'] . "." . $parsed['month'] . "." . $parsed['year']; } $return = $this->_calcdetail($calc, $date, self::DATE_MEDIUM, 'de'); if ($calc != 'cmp') { return $this; } return $return; } /** * Sets a new date for the date object. Format defines how to parse the date string. * Also a complete date with time can be given, but only the date is used for setting. * For example: MMMM.yy HH:mm-> May.07 22:11 => 01.May.07 00:00 * Returned is the new date object and the existing time is left as it was before * * @param string|integer|array|Zend_Date $date Date to set * @param string $format OPTIONAL Date format for parsing * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ public function setDate($date, $format = null, $locale = null) { return $this->_date('set', $date, $format, $locale); } /** * Adds a date to the existing date object. Format defines how to parse the date string. * If only parts are given the other parts are set to 0. * If no format is given, the standardformat of this locale is used. * For example: MM.dd.YYYY -> 10 -> +10 months * * @param string|integer|array|Zend_Date $date Date to add * @param string $format OPTIONAL Date format for parsing input * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addDate($date, $format = null, $locale = null) { return $this->_date('add', $date, $format, $locale); } /** * Subtracts a date from the existing date object. Format defines how to parse the date string. * If only parts are given the other parts are set to 0. * If no format is given, the standardformat of this locale is used. * For example: MM.dd.YYYY -> 10 -> -10 months * Be aware: Subtracting 2 months is not equal to Adding -2 months !!! * * @param string|integer|array|Zend_Date $date Date to sub * @param string $format OPTIONAL Date format for parsing input * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subDate($date, $format = null, $locale = null) { return $this->_date('sub', $date, $format, $locale); } /** * Compares the date from the existing date object, ignoring the time. * Format defines how to parse the date string. * If only parts are given the other parts are set to 0. * If no format is given, the standardformat of this locale is used. * For example: 10.01.2000 => 10.02.1999 -> false * * @param string|integer|array|Zend_Date $date Date to compare * @param string $format OPTIONAL Date format for parsing input * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareDate($date, $format = null, $locale = null) { return $this->_date('cmp', $date, $format, $locale); } /** * Returns the full ISO 8601 date from the date object. * Always the complete ISO 8601 specifiction is used. If an other ISO date is needed * (ISO 8601 defines several formats) use toString() instead. * This function does not return the ISO date as object. Use copy() instead. * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return string */ public function getIso($locale = null) { return $this->toString(self::ISO_8601, 'iso', $locale); } /** * Sets a new date for the date object. Not given parts are set to default. * Only supported ISO 8601 formats are accepted. * For example: 050901 -> 01.Sept.2005 00:00:00, 20050201T10:00:30 -> 01.Feb.2005 10h00m30s * Returned is the new date object * * @param string|integer|Zend_Date $date ISO Date to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ public function setIso($date, $locale = null) { return $this->_calcvalue('set', $date, 'iso', self::ISO_8601, $locale); } /** * Adds a ISO date to the date object. Not given parts are set to default. * Only supported ISO 8601 formats are accepted. * For example: 050901 -> + 01.Sept.2005 00:00:00, 10:00:00 -> +10h * Returned is the new date object * * @param string|integer|Zend_Date $date ISO Date to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ public function addIso($date, $locale = null) { return $this->_calcvalue('add', $date, 'iso', self::ISO_8601, $locale); } /** * Subtracts a ISO date from the date object. Not given parts are set to default. * Only supported ISO 8601 formats are accepted. * For example: 050901 -> - 01.Sept.2005 00:00:00, 10:00:00 -> -10h * Returned is the new date object * * @param string|integer|Zend_Date $date ISO Date to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ public function subIso($date, $locale = null) { return $this->_calcvalue('sub', $date, 'iso', self::ISO_8601, $locale); } /** * Compares a ISO date with the date object. Not given parts are set to default. * Only supported ISO 8601 formats are accepted. * For example: 050901 -> - 01.Sept.2005 00:00:00, 10:00:00 -> -10h * Returns if equal, earlier or later * * @param string|integer|Zend_Date $date ISO Date to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareIso($date, $locale = null) { return $this->_calcvalue('cmp', $date, 'iso', self::ISO_8601, $locale); } /** * Returns a RFC 822 compilant datestring from the date object. * This function does not return the RFC date as object. Use copy() instead. * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return string */ public function getArpa($locale = null) { return $this->toString(self::RFC_822, 'iso', $locale); } /** * Sets a RFC 822 date as new date for the date object. * Only RFC 822 compilant date strings are accepted. * For example: Sat, 14 Feb 09 00:31:30 +0100 * Returned is the new date object * * @param string|integer|Zend_Date $date RFC 822 to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ public function setArpa($date, $locale = null) { return $this->_calcvalue('set', $date, 'arpa', self::RFC_822, $locale); } /** * Adds a RFC 822 date to the date object. * ARPA messages are used in emails or HTTP Headers. * Only RFC 822 compilant date strings are accepted. * For example: Sat, 14 Feb 09 00:31:30 +0100 * Returned is the new date object * * @param string|integer|Zend_Date $date RFC 822 Date to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ public function addArpa($date, $locale = null) { return $this->_calcvalue('add', $date, 'arpa', self::RFC_822, $locale); } /** * Subtracts a RFC 822 date from the date object. * ARPA messages are used in emails or HTTP Headers. * Only RFC 822 compilant date strings are accepted. * For example: Sat, 14 Feb 09 00:31:30 +0100 * Returned is the new date object * * @param string|integer|Zend_Date $date RFC 822 Date to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ public function subArpa($date, $locale = null) { return $this->_calcvalue('sub', $date, 'arpa', self::RFC_822, $locale); } /** * Compares a RFC 822 compilant date with the date object. * ARPA messages are used in emails or HTTP Headers. * Only RFC 822 compilant date strings are accepted. * For example: Sat, 14 Feb 09 00:31:30 +0100 * Returns if equal, earlier or later * * @param string|integer|Zend_Date $date RFC 822 Date to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareArpa($date, $locale = null) { return $this->_calcvalue('cmp', $date, 'arpa', self::RFC_822, $locale); } /** * Check if location is supported * * @param $location array - locations array * @return $horizon float */ private function _checkLocation($location) { if (!isset($location['longitude']) or !isset($location['latitude'])) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('Location must include \'longitude\' and \'latitude\'', 0, null, $location); } if (($location['longitude'] > 180) or ($location['longitude'] < -180)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('Longitude must be between -180 and 180', 0, null, $location); } if (($location['latitude'] > 90) or ($location['latitude'] < -90)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('Latitude must be between -90 and 90', 0, null, $location); } if (!isset($location['horizon'])){ $location['horizon'] = 'effective'; } switch ($location['horizon']) { case 'civil' : return -0.104528; break; case 'nautic' : return -0.207912; break; case 'astronomic' : return -0.309017; break; default : return -0.0145439; break; } } /** * Returns the time of sunrise for this date and a given location as new date object * For a list of cities and correct locations use the class Zend_Date_Cities * * @param $location array - location of sunrise * ['horizon'] -> civil, nautic, astronomical, effective (default) * ['longitude'] -> longitude of location * ['latitude'] -> latitude of location * @return Zend_Date * @throws Zend_Date_Exception */ public function getSunrise($location) { $horizon = $this->_checkLocation($location); $result = clone $this; $result->set($this->calcSun($location, $horizon, true), self::TIMESTAMP); return $result; } /** * Returns the time of sunset for this date and a given location as new date object * For a list of cities and correct locations use the class Zend_Date_Cities * * @param $location array - location of sunset * ['horizon'] -> civil, nautic, astronomical, effective (default) * ['longitude'] -> longitude of location * ['latitude'] -> latitude of location * @return Zend_Date * @throws Zend_Date_Exception */ public function getSunset($location) { $horizon = $this->_checkLocation($location); $result = clone $this; $result->set($this->calcSun($location, $horizon, false), self::TIMESTAMP); return $result; } /** * Returns an array with the sunset and sunrise dates for all horizon types * For a list of cities and correct locations use the class Zend_Date_Cities * * @param $location array - location of suninfo * ['horizon'] -> civil, nautic, astronomical, effective (default) * ['longitude'] -> longitude of location * ['latitude'] -> latitude of location * @return array - [sunset|sunrise][effective|civil|nautic|astronomic] * @throws Zend_Date_Exception */ public function getSunInfo($location) { $suninfo = array(); for ($i = 0; $i < 4; ++$i) { switch ($i) { case 0 : $location['horizon'] = 'effective'; break; case 1 : $location['horizon'] = 'civil'; break; case 2 : $location['horizon'] = 'nautic'; break; case 3 : $location['horizon'] = 'astronomic'; break; } $horizon = $this->_checkLocation($location); $result = clone $this; $result->set($this->calcSun($location, $horizon, true), self::TIMESTAMP); $suninfo['sunrise'][$location['horizon']] = $result; $result = clone $this; $result->set($this->calcSun($location, $horizon, false), self::TIMESTAMP); $suninfo['sunset'][$location['horizon']] = $result; } return $suninfo; } /** * Check a given year for leap year. * * @param integer|array|Zend_Date $year Year to check * @return boolean */ public static function checkLeapYear($year) { if ($year instanceof Zend_Date) { $year = (int) $year->toString(self::YEAR, 'iso'); } if (is_array($year)) { if (isset($year['year']) === true) { $year = $year['year']; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("no year given in array"); } } if (!is_numeric($year)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("year ($year) has to be integer for checkLeapYear()", 0, null, $year); } return (bool) parent::isYearLeapYear($year); } /** * Returns true, if the year is a leap year. * * @return boolean */ public function isLeapYear() { return self::checkLeapYear($this); } /** * Returns if the set date is todays date * * @return boolean */ public function isToday() { $today = $this->date('Ymd', $this->_getTime()); $day = $this->date('Ymd', $this->getUnixTimestamp()); return ($today == $day); } /** * Returns if the set date is yesterdays date * * @return boolean */ public function isYesterday() { list($year, $month, $day) = explode('-', $this->date('Y-m-d', $this->_getTime())); // adjusts for leap days and DST changes that are timezone specific $yesterday = $this->date('Ymd', $this->mktime(0, 0, 0, $month, $day -1, $year)); $day = $this->date('Ymd', $this->getUnixTimestamp()); return $day == $yesterday; } /** * Returns if the set date is tomorrows date * * @return boolean */ public function isTomorrow() { list($year, $month, $day) = explode('-', $this->date('Y-m-d', $this->_getTime())); // adjusts for leap days and DST changes that are timezone specific $tomorrow = $this->date('Ymd', $this->mktime(0, 0, 0, $month, $day +1, $year)); $day = $this->date('Ymd', $this->getUnixTimestamp()); return $day == $tomorrow; } /** * Returns the actual date as new date object * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public static function now($locale = null) { return new Zend_Date(time(), self::TIMESTAMP, $locale); } /** * Calculate date details * * @param string $calc Calculation to make * @param string|integer|array|Zend_Date $date Date or Part to calculate * @param string $part Datepart for Calculation * @param string|Zend_Locale $locale Locale for parsing input * @return integer|string new date * @throws Zend_Date_Exception */ private function _calcdetail($calc, $date, $type, $locale) { $old = false; if (self::$_options['format_type'] == 'php') { self::$_options['format_type'] = 'iso'; $old = true; } switch($calc) { case 'set' : $return = $this->set($date, $type, $locale); break; case 'add' : $return = $this->add($date, $type, $locale); break; case 'sub' : $return = $this->sub($date, $type, $locale); break; default : $return = $this->compare($date, $type, $locale); break; } if ($old) { self::$_options['format_type'] = 'php'; } return $return; } /** * Internal calculation, returns the requested date type * * @param string $calc Calculation to make * @param string|integer|Zend_Date $value Datevalue to calculate with, if null the actual value is taken * @param string|Zend_Locale $locale Locale for parsing input * @return integer|Zend_Date new date * @throws Zend_Date_Exception */ private function _calcvalue($calc, $value, $type, $parameter, $locale) { if ($value === null) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("parameter $type must be set, null is not allowed"); } if ($locale === null) { $locale = $this->getLocale(); } if ($value instanceof Zend_Date) { // extract value from object $value = $value->toString($parameter, 'iso', $locale); } else if (!is_array($value) && !is_numeric($value) && ($type != 'iso') && ($type != 'arpa')) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid $type ($value) operand", 0, null, $value); } $return = $this->_calcdetail($calc, $value, $parameter, $locale); if ($calc != 'cmp') { return $this; } return $return; } /** * Returns only the year from the date object as new object. * For example: 10.May.2000 10:30:00 -> 01.Jan.2000 00:00:00 * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getYear($locale = null) { return $this->copyPart(self::YEAR, $locale); } /** * Sets a new year * If the year is between 0 and 69, 2000 will be set (2000-2069) * If the year if between 70 and 99, 1999 will be set (1970-1999) * 3 or 4 digit years are set as expected. If you need to set year 0-99 * use set() instead. * Returned is the new date object * * @param string|integer|array|Zend_Date $date Year to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setYear($year, $locale = null) { return $this->_calcvalue('set', $year, 'year', self::YEAR, $locale); } /** * Adds the year to the existing date object * If the year is between 0 and 69, 2000 will be added (2000-2069) * If the year if between 70 and 99, 1999 will be added (1970-1999) * 3 or 4 digit years are added as expected. If you need to add years from 0-99 * use add() instead. * Returned is the new date object * * @param string|integer|array|Zend_Date $date Year to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addYear($year, $locale = null) { return $this->_calcvalue('add', $year, 'year', self::YEAR, $locale); } /** * Subs the year from the existing date object * If the year is between 0 and 69, 2000 will be subtracted (2000-2069) * If the year if between 70 and 99, 1999 will be subtracted (1970-1999) * 3 or 4 digit years are subtracted as expected. If you need to subtract years from 0-99 * use sub() instead. * Returned is the new date object * * @param string|integer|array|Zend_Date $date Year to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subYear($year, $locale = null) { return $this->_calcvalue('sub', $year, 'year', self::YEAR, $locale); } /** * Compares the year with the existing date object, ignoring other date parts. * For example: 10.03.2000 -> 15.02.2000 -> true * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $year Year to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareYear($year, $locale = null) { return $this->_calcvalue('cmp', $year, 'year', self::YEAR, $locale); } /** * Returns only the month from the date object as new object. * For example: 10.May.2000 10:30:00 -> 01.May.1970 00:00:00 * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getMonth($locale = null) { return $this->copyPart(self::MONTH, $locale); } /** * Returns the calculated month * * @param string $calc Calculation to make * @param string|integer|array|Zend_Date $month Month to calculate with, if null the actual month is taken * @param string|Zend_Locale $locale Locale for parsing input * @return integer|Zend_Date new time * @throws Zend_Date_Exception */ private function _month($calc, $month, $locale) { if ($month === null) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('parameter $month must be set, null is not allowed'); } if ($locale === null) { $locale = $this->getLocale(); } if ($month instanceof Zend_Date) { // extract month from object $found = $month->toString(self::MONTH_SHORT, 'iso', $locale); } else { if (is_numeric($month)) { $found = $month; } else if (is_array($month)) { if (isset($month['month']) === true) { $month = $month['month']; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("no month given in array"); } } else { $monthlist = Zend_Locale_Data::getList($locale, 'month'); $monthlist2 = Zend_Locale_Data::getList($locale, 'month', array('gregorian', 'format', 'abbreviated')); $monthlist = array_merge($monthlist, $monthlist2); $found = 0; $cnt = 0; foreach ($monthlist as $key => $value) { if (strtoupper($value) == strtoupper($month)) { $found = ($key % 12) + 1; break; } ++$cnt; } if ($found == 0) { foreach ($monthlist2 as $key => $value) { if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) == strtoupper($month)) { $found = $key + 1; break; } ++$cnt; } } if ($found == 0) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("unknown month name ($month)", 0, null, $month); } } } $return = $this->_calcdetail($calc, $found, self::MONTH_SHORT, $locale); if ($calc != 'cmp') { return $this; } return $return; } /** * Sets a new month * The month can be a number or a string. Setting months lower then 0 and greater then 12 * will result in adding or subtracting the relevant year. (12 months equal one year) * If a localized monthname is given it will be parsed with the default locale or the optional * set locale. * Returned is the new date object * * @param string|integer|array|Zend_Date $month Month to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setMonth($month, $locale = null) { return $this->_month('set', $month, $locale); } /** * Adds months to the existing date object. * The month can be a number or a string. Adding months lower then 0 and greater then 12 * will result in adding or subtracting the relevant year. (12 months equal one year) * If a localized monthname is given it will be parsed with the default locale or the optional * set locale. * Returned is the new date object * * @param string|integer|array|Zend_Date $month Month to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addMonth($month, $locale = null) { return $this->_month('add', $month, $locale); } /** * Subtracts months from the existing date object. * The month can be a number or a string. Subtracting months lower then 0 and greater then 12 * will result in adding or subtracting the relevant year. (12 months equal one year) * If a localized monthname is given it will be parsed with the default locale or the optional * set locale. * Returned is the new date object * * @param string|integer|array|Zend_Date $month Month to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subMonth($month, $locale = null) { return $this->_month('sub', $month, $locale); } /** * Compares the month with the existing date object, ignoring other date parts. * For example: 10.03.2000 -> 15.03.1950 -> true * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $month Month to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareMonth($month, $locale = null) { return $this->_month('cmp', $month, $locale); } /** * Returns the day as new date object * Example: 20.May.1986 -> 20.Jan.1970 00:00:00 * * @param $locale string|Zend_Locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getDay($locale = null) { return $this->copyPart(self::DAY_SHORT, $locale); } /** * Returns the calculated day * * @param $calc string Type of calculation to make * @param $day string|integer|Zend_Date Day to calculate, when null the actual day is calculated * @param $locale string|Zend_Locale Locale for parsing input * @return Zend_Date|integer */ private function _day($calc, $day, $locale) { if ($day === null) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('parameter $day must be set, null is not allowed'); } if ($locale === null) { $locale = $this->getLocale(); } if ($day instanceof Zend_Date) { $day = $day->toString(self::DAY_SHORT, 'iso', $locale); } if (is_numeric($day)) { $type = self::DAY_SHORT; } else if (is_array($day)) { if (isset($day['day']) === true) { $day = $day['day']; $type = self::WEEKDAY; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("no day given in array"); } } else { switch (iconv_strlen($day, 'UTF-8')) { case 1 : $type = self::WEEKDAY_NARROW; break; case 2: $type = self::WEEKDAY_NAME; break; case 3: $type = self::WEEKDAY_SHORT; break; default: $type = self::WEEKDAY; break; } } $return = $this->_calcdetail($calc, $day, $type, $locale); if ($calc != 'cmp') { return $this; } return $return; } /** * Sets a new day * The day can be a number or a string. Setting days lower then 0 or greater than the number of this months days * will result in adding or subtracting the relevant month. * If a localized dayname is given it will be parsed with the default locale or the optional * set locale. * Returned is the new date object * Example: setDay('Montag', 'de_AT'); will set the monday of this week as day. * * @param string|integer|array|Zend_Date $month Day to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setDay($day, $locale = null) { return $this->_day('set', $day, $locale); } /** * Adds days to the existing date object. * The day can be a number or a string. Adding days lower then 0 or greater than the number of this months days * will result in adding or subtracting the relevant month. * If a localized dayname is given it will be parsed with the default locale or the optional * set locale. * * @param string|integer|array|Zend_Date $month Day to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addDay($day, $locale = null) { return $this->_day('add', $day, $locale); } /** * Subtracts days from the existing date object. * The day can be a number or a string. Subtracting days lower then 0 or greater than the number of this months days * will result in adding or subtracting the relevant month. * If a localized dayname is given it will be parsed with the default locale or the optional * set locale. * * @param string|integer|array|Zend_Date $month Day to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subDay($day, $locale = null) { return $this->_day('sub', $day, $locale); } /** * Compares the day with the existing date object, ignoring other date parts. * For example: 'Monday', 'en' -> 08.Jan.2007 -> 0 * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $day Day to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareDay($day, $locale = null) { return $this->_day('cmp', $day, $locale); } /** * Returns the weekday as new date object * Weekday is always from 1-7 * Example: 09-Jan-2007 -> 2 = Tuesday -> 02-Jan-1970 (when 02.01.1970 is also Tuesday) * * @param $locale string|Zend_Locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getWeekday($locale = null) { return $this->copyPart(self::WEEKDAY, $locale); } /** * Returns the calculated weekday * * @param $calc string Type of calculation to make * @param $weekday string|integer|array|Zend_Date Weekday to calculate, when null the actual weekday is calculated * @param $locale string|Zend_Locale Locale for parsing input * @return Zend_Date|integer * @throws Zend_Date_Exception */ private function _weekday($calc, $weekday, $locale) { if ($weekday === null) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('parameter $weekday must be set, null is not allowed'); } if ($locale === null) { $locale = $this->getLocale(); } if ($weekday instanceof Zend_Date) { $weekday = $weekday->toString(self::WEEKDAY_8601, 'iso', $locale); } if (is_numeric($weekday)) { $type = self::WEEKDAY_8601; } else if (is_array($weekday)) { if (isset($weekday['weekday']) === true) { $weekday = $weekday['weekday']; $type = self::WEEKDAY; } else { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("no weekday given in array"); } } else { switch(iconv_strlen($weekday, 'UTF-8')) { case 1: $type = self::WEEKDAY_NARROW; break; case 2: $type = self::WEEKDAY_NAME; break; case 3: $type = self::WEEKDAY_SHORT; break; default: $type = self::WEEKDAY; break; } } $return = $this->_calcdetail($calc, $weekday, $type, $locale); if ($calc != 'cmp') { return $this; } return $return; } /** * Sets a new weekday * The weekday can be a number or a string. If a localized weekday name is given, * then it will be parsed as a date in $locale (defaults to the same locale as $this). * Returned is the new date object. * Example: setWeekday(3); will set the wednesday of this week as day. * * @param string|integer|array|Zend_Date $month Weekday to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setWeekday($weekday, $locale = null) { return $this->_weekday('set', $weekday, $locale); } /** * Adds weekdays to the existing date object. * The weekday can be a number or a string. * If a localized dayname is given it will be parsed with the default locale or the optional * set locale. * Returned is the new date object * Example: addWeekday(3); will add the difference of days from the begining of the month until * wednesday. * * @param string|integer|array|Zend_Date $month Weekday to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addWeekday($weekday, $locale = null) { return $this->_weekday('add', $weekday, $locale); } /** * Subtracts weekdays from the existing date object. * The weekday can be a number or a string. * If a localized dayname is given it will be parsed with the default locale or the optional * set locale. * Returned is the new date object * Example: subWeekday(3); will subtract the difference of days from the begining of the month until * wednesday. * * @param string|integer|array|Zend_Date $month Weekday to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subWeekday($weekday, $locale = null) { return $this->_weekday('sub', $weekday, $locale); } /** * Compares the weekday with the existing date object, ignoring other date parts. * For example: 'Monday', 'en' -> 08.Jan.2007 -> 0 * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $weekday Weekday to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareWeekday($weekday, $locale = null) { return $this->_weekday('cmp', $weekday, $locale); } /** * Returns the day of year as new date object * Example: 02.Feb.1986 10:00:00 -> 02.Feb.1970 00:00:00 * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getDayOfYear($locale = null) { return $this->copyPart(self::DAY_OF_YEAR, $locale); } /** * Sets a new day of year * The day of year is always a number. * Returned is the new date object * Example: 04.May.2004 -> setDayOfYear(10) -> 10.Jan.2004 * * @param string|integer|array|Zend_Date $day Day of Year to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setDayOfYear($day, $locale = null) { return $this->_calcvalue('set', $day, 'day of year', self::DAY_OF_YEAR, $locale); } /** * Adds a day of year to the existing date object. * The day of year is always a number. * Returned is the new date object * Example: addDayOfYear(10); will add 10 days to the existing date object. * * @param string|integer|array|Zend_Date $day Day of Year to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addDayOfYear($day, $locale = null) { return $this->_calcvalue('add', $day, 'day of year', self::DAY_OF_YEAR, $locale); } /** * Subtracts a day of year from the existing date object. * The day of year is always a number. * Returned is the new date object * Example: subDayOfYear(10); will subtract 10 days from the existing date object. * * @param string|integer|array|Zend_Date $day Day of Year to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subDayOfYear($day, $locale = null) { return $this->_calcvalue('sub', $day, 'day of year', self::DAY_OF_YEAR, $locale); } /** * Compares the day of year with the existing date object. * For example: compareDayOfYear(33) -> 02.Feb.2007 -> 0 * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $day Day of Year to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareDayOfYear($day, $locale = null) { return $this->_calcvalue('cmp', $day, 'day of year', self::DAY_OF_YEAR, $locale); } /** * Returns the hour as new date object * Example: 02.Feb.1986 10:30:25 -> 01.Jan.1970 10:00:00 * * @param $locale string|Zend_Locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getHour($locale = null) { return $this->copyPart(self::HOUR, $locale); } /** * Sets a new hour * The hour is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> setHour(7); -> 04.May.1993 07:07:25 * * @param string|integer|array|Zend_Date $hour Hour to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setHour($hour, $locale = null) { return $this->_calcvalue('set', $hour, 'hour', self::HOUR_SHORT, $locale); } /** * Adds hours to the existing date object. * The hour is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> addHour(12); -> 05.May.1993 01:07:25 * * @param string|integer|array|Zend_Date $hour Hour to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addHour($hour, $locale = null) { return $this->_calcvalue('add', $hour, 'hour', self::HOUR_SHORT, $locale); } /** * Subtracts hours from the existing date object. * The hour is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> subHour(6); -> 05.May.1993 07:07:25 * * @param string|integer|array|Zend_Date $hour Hour to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subHour($hour, $locale = null) { return $this->_calcvalue('sub', $hour, 'hour', self::HOUR_SHORT, $locale); } /** * Compares the hour with the existing date object. * For example: 10:30:25 -> compareHour(10) -> 0 * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $hour Hour to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareHour($hour, $locale = null) { return $this->_calcvalue('cmp', $hour, 'hour', self::HOUR_SHORT, $locale); } /** * Returns the minute as new date object * Example: 02.Feb.1986 10:30:25 -> 01.Jan.1970 00:30:00 * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getMinute($locale = null) { return $this->copyPart(self::MINUTE, $locale); } /** * Sets a new minute * The minute is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> setMinute(29); -> 04.May.1993 13:29:25 * * @param string|integer|array|Zend_Date $minute Minute to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setMinute($minute, $locale = null) { return $this->_calcvalue('set', $minute, 'minute', self::MINUTE_SHORT, $locale); } /** * Adds minutes to the existing date object. * The minute is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> addMinute(65); -> 04.May.1993 13:12:25 * * @param string|integer|array|Zend_Date $minute Minute to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addMinute($minute, $locale = null) { return $this->_calcvalue('add', $minute, 'minute', self::MINUTE_SHORT, $locale); } /** * Subtracts minutes from the existing date object. * The minute is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> subMinute(9); -> 04.May.1993 12:58:25 * * @param string|integer|array|Zend_Date $minute Minute to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subMinute($minute, $locale = null) { return $this->_calcvalue('sub', $minute, 'minute', self::MINUTE_SHORT, $locale); } /** * Compares the minute with the existing date object. * For example: 10:30:25 -> compareMinute(30) -> 0 * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $minute Hour to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareMinute($minute, $locale = null) { return $this->_calcvalue('cmp', $minute, 'minute', self::MINUTE_SHORT, $locale); } /** * Returns the second as new date object * Example: 02.Feb.1986 10:30:25 -> 01.Jan.1970 00:00:25 * * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getSecond($locale = null) { return $this->copyPart(self::SECOND, $locale); } /** * Sets new seconds to the existing date object. * The second is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> setSecond(100); -> 04.May.1993 13:08:40 * * @param string|integer|array|Zend_Date $second Second to set * @param string|Zend_Locale $locale (Optional) Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function setSecond($second, $locale = null) { return $this->_calcvalue('set', $second, 'second', self::SECOND_SHORT, $locale); } /** * Adds seconds to the existing date object. * The second is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> addSecond(65); -> 04.May.1993 13:08:30 * * @param string|integer|array|Zend_Date $second Second to add * @param string|Zend_Locale $locale (Optional) Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function addSecond($second, $locale = null) { return $this->_calcvalue('add', $second, 'second', self::SECOND_SHORT, $locale); } /** * Subtracts seconds from the existing date object. * The second is always a number. * Returned is the new date object * Example: 04.May.1993 13:07:25 -> subSecond(10); -> 04.May.1993 13:07:15 * * @param string|integer|array|Zend_Date $second Second to sub * @param string|Zend_Locale $locale (Optional) Locale for parsing input * @return Zend_Date new date * @throws Zend_Date_Exception */ public function subSecond($second, $locale = null) { return $this->_calcvalue('sub', $second, 'second', self::SECOND_SHORT, $locale); } /** * Compares the second with the existing date object. * For example: 10:30:25 -> compareSecond(25) -> 0 * Returns if equal, earlier or later * * @param string|integer|array|Zend_Date $second Second to compare * @param string|Zend_Locale $locale (Optional) Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier * @throws Zend_Date_Exception */ public function compareSecond($second, $locale = null) { return $this->_calcvalue('cmp', $second, 'second', self::SECOND_SHORT, $locale); } /** * Returns the precision for fractional seconds * * @return integer */ public function <API key>() { return $this->_precision; } /** * Sets a new precision for fractional seconds * * @param integer $precision Precision for the fractional datepart 3 = milliseconds * @throws Zend_Date_Exception * @return Zend_Date Provides fluid interface */ public function <API key>($precision) { if (!intval($precision) or ($precision < 0) or ($precision > 9)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("precision ($precision) must be a positive integer less than 10", 0, null, $precision); } $this->_precision = (int) $precision; if ($this->_precision < strlen($this->_fractional)) { $this->_fractional = substr($this->_fractional, 0, $this->_precision); } else { $this->_fractional = str_pad($this->_fractional, $this->_precision, '0', STR_PAD_RIGHT); } return $this; } /** * Returns the milliseconds of the date object * * @return string */ public function getMilliSecond() { return $this->_fractional; } /** * Sets new milliseconds for the date object * Example: setMilliSecond(550, 2) -> equals +5 Sec +50 MilliSec * * @param integer|Zend_Date $milli (Optional) Millisecond to set, when null the actual millisecond is set * @param integer $precision (Optional) Fraction precision of the given milliseconds * @return Zend_Date Prodives fluid interface */ public function setMilliSecond($milli = null, $precision = null) { if ($milli === null) { list($milli, $time) = explode(" ", microtime()); $milli = intval($milli); $precision = 6; } else if (!is_numeric($milli)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid milli second ($milli) operand", 0, null, $milli); } if ($precision === null) { $precision = $this->_precision; } if (!is_int($precision) || $precision < 1 || $precision > 9) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("precision ($precision) must be a positive integer less than 10", 0, null, $precision); } $this->_fractional = 0; $this->addMilliSecond($milli, $precision); return $this; } /** * Adds milliseconds to the date object * * @param integer|Zend_Date $milli (Optional) Millisecond to add, when null the actual millisecond is added * @param integer $precision (Optional) Fractional precision for the given milliseconds * @return Zend_Date Provides fluid interface */ public function addMilliSecond($milli = null, $precision = null) { if ($milli === null) { list($milli, $time) = explode(" ", microtime()); $milli = intval($milli); } else if (!is_numeric($milli)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid milli second ($milli) operand", 0, null, $milli); } if ($precision === null) { $precision = strlen($milli); if ($milli < 0) { --$precision; } } if (!is_int($precision) || $precision < 1 || $precision > 9) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("precision ($precision) must be a positive integer less than 10", 0, null, $precision); } $this->_fractional += $milli; // Add/sub milliseconds + add/sub seconds $max = pow(10, $this->_precision); // Milli includes seconds if ($this->_fractional >= $max) { while ($this->_fractional >= $max) { $this->addSecond(1); $this->_fractional -= $max; } } if ($this->_fractional < 0) { while ($this->_fractional < 0) { $this->subSecond(1); $this->_fractional += $max; } } if ($this->_precision > strlen($this->_fractional)) { $this->_fractional = str_pad($this->_fractional, $this->_precision, '0', STR_PAD_LEFT); } return $this; } /** * Subtracts a millisecond * * @param integer|Zend_Date $milli (Optional) Millisecond to sub, when null the actual millisecond is subtracted * @param integer $precision (Optional) Fractional precision for the given milliseconds * @return Zend_Date Provides fluid interface */ public function subMilliSecond($milli = null, $precision = null) { $this->addMilliSecond(0 - $milli, $precision); return $this; } /** * Compares only the millisecond part, returning the difference * * @param integer|Zend_Date $milli OPTIONAL Millisecond to compare, when null the actual millisecond is compared * @param integer $precision OPTIONAL Fractional precision for the given milliseconds * @throws Zend_Date_Exception On invalid input * @return integer 0 = equal, 1 = later, -1 = earlier */ public function compareMilliSecond($milli = null, $precision = null) { if ($milli === null) { list($milli, $time) = explode(" ", microtime()); $milli = intval($milli); } else if (is_numeric($milli) === false) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid milli second ($milli) operand", 0, null, $milli); } if ($precision === null) { $precision = strlen($milli); } else if (!is_int($precision) || $precision < 1 || $precision > 9) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("precision ($precision) must be a positive integer less than 10", 0, null, $precision); } if ($precision === 0) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('precision is 0'); } if ($precision != $this->_precision) { if ($precision > $this->_precision) { $diff = $precision - $this->_precision; $milli = (int) ($milli / (10 * $diff)); } else { $diff = $this->_precision - $precision; $milli = (int) ($milli * (10 * $diff)); } } $comp = $this->_fractional - $milli; if ($comp < 0) { return -1; } else if ($comp > 0) { return 1; } return 0; } /** * Returns the week as new date object using monday as begining of the week * Example: 12.Jan.2007 -> 08.Jan.1970 00:00:00 * * @param $locale string|Zend_Locale OPTIONAL Locale for parsing input * @return Zend_Date */ public function getWeek($locale = null) { return $this->copyPart(self::WEEK, $locale); } /** * Sets a new week. The week is always a number. The day of week is not changed. * Returned is the new date object * Example: 09.Jan.2007 13:07:25 -> setWeek(1); -> 02.Jan.2007 13:07:25 * * @param string|integer|array|Zend_Date $week Week to set * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date * @throws Zend_Date_Exception */ public function setWeek($week, $locale = null) { return $this->_calcvalue('set', $week, 'week', self::WEEK, $locale); } /** * Adds a week. The week is always a number. The day of week is not changed. * Returned is the new date object * Example: 09.Jan.2007 13:07:25 -> addWeek(1); -> 16.Jan.2007 13:07:25 * * @param string|integer|array|Zend_Date $week Week to add * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date * @throws Zend_Date_Exception */ public function addWeek($week, $locale = null) { return $this->_calcvalue('add', $week, 'week', self::WEEK, $locale); } /** * Subtracts a week. The week is always a number. The day of week is not changed. * Returned is the new date object * Example: 09.Jan.2007 13:07:25 -> subWeek(1); -> 02.Jan.2007 13:07:25 * * @param string|integer|array|Zend_Date $week Week to sub * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return Zend_Date * @throws Zend_Date_Exception */ public function subWeek($week, $locale = null) { return $this->_calcvalue('sub', $week, 'week', self::WEEK, $locale); } /** * Compares only the week part, returning the difference * Returned is the new date object * Returns if equal, earlier or later * Example: 09.Jan.2007 13:07:25 -> compareWeek(2); -> 0 * * @param string|integer|array|Zend_Date $week Week to compare * @param string|Zend_Locale $locale OPTIONAL Locale for parsing input * @return integer 0 = equal, 1 = later, -1 = earlier */ public function compareWeek($week, $locale = null) { return $this->_calcvalue('cmp', $week, 'week', self::WEEK, $locale); } /** * Sets a new standard locale for the date object. * This locale will be used for all functions * Returned is the really set locale. * Example: 'de_XX' will be set to 'de' because 'de_XX' does not exist * 'xx_YY' will be set to 'root' because 'xx' does not exist * * @param string|Zend_Locale $locale (Optional) Locale for parsing input * @throws Zend_Date_Exception When the given locale does not exist * @return Zend_Date Provides fluent interface */ public function setLocale($locale = null) { try { $this->_locale = Zend_Locale::findLocale($locale); } catch (<API key> $e) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception($e->getMessage(), 0, $e); } return $this; } /** * Returns the actual set locale * * @return string */ public function getLocale() { return $this->_locale; } /** * Checks if the given date is a real date or datepart. * Returns false if a expected datepart is missing or a datepart exceeds its possible border. * But the check will only be done for the expected dateparts which are given by format. * If no format is given the standard dateformat for the actual locale is used. * f.e. 30.February.2007 will return false if format is 'dd.MMMM.YYYY' * * @param string|array|Zend_Date $date Date to parse for correctness * @param string $format (Optional) Format for parsing the date string * @param string|Zend_Locale $locale (Optional) Locale for parsing date parts * @return boolean True when all date parts are correct */ public static function isDate($date, $format = null, $locale = null) { if (!is_string($date) && !is_numeric($date) && !($date instanceof Zend_Date) && !is_array($date)) { return false; } if (($format !== null) and (Zend_Locale::isLocale($format, null, false))) { $locale = $format; $format = null; } $locale = Zend_Locale::findLocale($locale); if ($format === null) { $format = Zend_Locale_Format::getDateFormat($locale); } else if ((self::$_options['format_type'] == 'php') && !defined($format)) { $format = Zend_Locale_Format::<API key>($format); } $format = self::_getLocalizedToken($format, $locale); if (!is_array($date)) { try { $parsed = Zend_Locale_Format::getDate($date, array('locale' => $locale, 'date_format' => $format, 'format_type' => 'iso', 'fix_date' => false)); } catch (<API key> $e) { // Date can not be parsed return false; } } else { $parsed = $date; } if (((strpos($format, 'Y') !== false) or (strpos($format, 'y') !== false)) and (!isset($parsed['year']))) { // Year expected but not found return false; } if ((strpos($format, 'M') !== false) and (!isset($parsed['month']))) { // Month expected but not found return false; } if ((strpos($format, 'd') !== false) and (!isset($parsed['day']))) { // Day expected but not found return false; } if (((strpos($format, 'H') !== false) or (strpos($format, 'h') !== false)) and (!isset($parsed['hour']))) { // Hour expected but not found return false; } if ((strpos($format, 'm') !== false) and (!isset($parsed['minute']))) { // Minute expected but not found return false; } if ((strpos($format, 's') !== false) and (!isset($parsed['second']))) { // Second expected but not found return false; } // Set not given dateparts if (isset($parsed['hour']) === false) { $parsed['hour'] = 12; } if (isset($parsed['minute']) === false) { $parsed['minute'] = 0; } if (isset($parsed['second']) === false) { $parsed['second'] = 0; } if (isset($parsed['month']) === false) { $parsed['month'] = 1; } if (isset($parsed['day']) === false) { $parsed['day'] = 1; } if (isset($parsed['year']) === false) { $parsed['year'] = 1970; } if (self::isYearLeapYear($parsed['year'])) { $parsed['year'] = 1972; } else { $parsed['year'] = 1971; } $date = new self($parsed, null, $locale); $timestamp = $date->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $parsed['month'], $parsed['day'], $parsed['year']); if ($parsed['year'] != $date->date('Y', $timestamp)) { // Given year differs from parsed year return false; } if ($parsed['month'] != $date->date('n', $timestamp)) { // Given month differs from parsed month return false; } if ($parsed['day'] != $date->date('j', $timestamp)) { // Given day differs from parsed day return false; } if ($parsed['hour'] != $date->date('G', $timestamp)) { // Given hour differs from parsed hour return false; } if ($parsed['minute'] != $date->date('i', $timestamp)) { // Given minute differs from parsed minute return false; } if ($parsed['second'] != $date->date('s', $timestamp)) { // Given second differs from parsed second return false; } return true; } /** * Returns the ISO Token for all localized constants * * @param string $token Token to normalize * @param string $locale Locale to search * @return string */ protected static function _getLocalizedToken($token, $locale) { switch($token) { case self::ISO_8601 : return "yyyy-MM-ddThh:mm:ss"; break; case self::RFC_2822 : return "EEE, dd MMM yyyy HH:mm:ss"; break; case self::DATES : return Zend_Locale_Data::getContent($locale, 'date'); break; case self::DATE_FULL : return Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'full')); break; case self::DATE_LONG : return Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'long')); break; case self::DATE_MEDIUM : return Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'medium')); break; case self::DATE_SHORT : return Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'short')); break; case self::TIMES : return Zend_Locale_Data::getContent($locale, 'date'); break; case self::TIME_FULL : return Zend_Locale_Data::getContent($locale, 'time', array('gregorian', 'full')); break; case self::TIME_LONG : return Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'long')); break; case self::TIME_MEDIUM : return Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'medium')); break; case self::TIME_SHORT : return Zend_Locale_Data::getContent($locale, 'date', array('gregorian', 'short')); break; case self::DATETIME : return Zend_Locale_Data::getContent($locale, 'datetime'); break; case self::DATETIME_FULL : return Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'full')); break; case self::DATETIME_LONG : return Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'long')); break; case self::DATETIME_MEDIUM : return Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'medium')); break; case self::DATETIME_SHORT : return Zend_Locale_Data::getContent($locale, 'datetime', array('gregorian', 'short')); break; case self::ATOM : case self::RFC_3339 : case self::W3C : return "yyyy-MM-DD HH:mm:ss"; break; case self::COOKIE : case self::RFC_850 : return "EEEE, dd-MM-yyyy HH:mm:ss"; break; case self::RFC_822 : case self::RFC_1036 : case self::RFC_1123 : case self::RSS : return "EEE, dd MM yyyy HH:mm:ss"; break; } return $token; } }
package uk.ac.sussex.gdsc.analytics; /** * The dispatch status. */ public enum DispatchStatus { /** * The request has been processed. */ COMPLETE, /** * The request has errored during processing. */ ERROR, /** * The request not been processed because the tracker is set to ignore. */ IGNORED, /** * The request not been processed because the tracker is shutdown. */ SHUTDOWN, /** * The request not been processed because the tracker previously errored and disabled. */ DISABLED; }
<?php /** * La clase encapsula la logica de negocio asociada a la informacion adicional de los convenios. * * @package pragtico * @subpackage app.controllers */ class <API key> extends AppController { var $paginate = array( 'order' => array( 'Informacion.nombre' => 'asc' ) ); } ?>
/* The HMM-Based Speech Synthesis System (HTS): version 1.1b */ /* HTS Working Group */ /* Department of Computer Science */ /* Nagoya Institute of Technology */ /* and */ /* Interdisciplinary Graduate School of Science and Engineering */ /* Tokyo Institute of Technology */ /* distribute this software and its documentation without */ /* restriction, including without limitation the rights to use, */ /* sell copies of this work, and to permit persons to whom this */ /* work is furnished to do so, subject to the following conditions: */ /* 2. Any modifications must be clearly marked as such. */ /* NAGOYA INSTITUTE OF TECHNOLOGY, TOKYO INSITITUTE OF TECHNOLOGY, */ /* HTS WORKING GROUP, AND THE CONTRIBUTORS TO THIS WORK DISCLAIM */ /* ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL */ /* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */ /* SHALL NAGOYA INSTITUTE OF TECHNOLOGY, TOKYO INSITITUTE OF */ /* TECHNOLOGY, HTS WORKING GROUP, NOR THE CONTRIBUTORS BE LIABLE */ /* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY */ /* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, */ /* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS */ /* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR */ /* PERFORMANCE OF THIS SOFTWARE. */ /* This is Zen's MLSA filter as ported by Toda to festvox vc */ /* and back ported into hts/festival so we can do MLSA filtering */ /* If I took more time I could probably make this use the same as */ /* as the other code in this directory -- awb@cs.cmu.edu 03JAN06 */ /* Mel-cepstral vocoder (pulse/noise excitation & MLSA filter) */ /* 2003/12/26 by Heiga Zen */ /* Extracted from HTS and slightly modified */ /* by Tomoki Toda (tomoki@ics.nitech.ac.jp) */ /* June 2004 */ /* Integrate as a Voice Conversion module */ #include "cst_alloc.h" #include "cst_string.h" #include "cst_math.h" #include "cst_track.h" #include "cst_wave.h" #include "cst_audio.h" #ifdef UNDER_CE #define SPEED_HACK /* This is one of those other things you shouldn't do, but it makes CG voices in flowm fast enough on my phone */ #define double float #endif #include "cst_vc.h" #include "cst_cg.h" #include "cst_mlsa.h" static cst_wave *synthesis_body(const cst_track *params, const cst_track *str, double fs, double framem, cst_cg_db *cg_db, <API key> *asi); cst_wave *mlsa_resynthesis(const cst_track *params, const cst_track *str, cst_cg_db *cg_db, <API key> *asi) { /* Resynthesizes a wave from given track */ cst_wave *wave = 0; int sr = 16000; double shift; if (params->num_frames > 1) shift = 1000.0*(params->times[1]-params->times[0]); else shift = 5.0; wave = synthesis_body(params,str,sr,shift,cg_db,asi); return wave; } static cst_wave *synthesis_body(const cst_track *params, /* f0 + mcep */ const cst_track *str, double fs, /* sampling frequency (Hz) */ double framem, /* FFT length */ cst_cg_db *cg_db, <API key> *asi) { long t, pos; int framel, i; double f0; VocoderSetup vs; cst_wave *wave = 0; double *mcep; int stream_mark; int rc = <API key>; int num_mcep; num_mcep = params->num_channels-1; framel = (int)(framem * fs / 1000.0); init_vocoder(fs, framel, num_mcep, &vs, cg_db); if (str != NULL) vs.gauss = MFALSE; /* synthesize waveforms by MLSA filter */ wave = new_wave(); cst_wave_resize(wave,params->num_frames * (framel + 2),1); #ifdef SPEED_HACK /* This is a SPECTACULAR hack -- basically resample the original */ /* files to 8KHz but label them as 16KHz and do the full build */ /* then after synthesis get them to be played at 8KHz -- it works */ wave->sample_rate = 8000; #else wave->sample_rate = fs; #endif mcep = cst_alloc(double,num_mcep+1); for (t = 0, stream_mark = pos = 0; (rc == <API key>) && (t < params->num_frames); t++) { f0 = (double)params->frames[t][0]; for (i=1; i<num_mcep+1; i++) mcep[i-1] = params->frames[t][i]; mcep[i-1] = 0; vocoder(f0, mcep, str, t, num_mcep, cg_db, &vs, wave, &pos); if (asi && (pos-stream_mark > asi->min_buffsize)) { rc=(*asi->asc)(wave,stream_mark,pos-stream_mark,0,asi->userdata); stream_mark = pos; } } wave->num_samples = pos; if (asi && (rc == <API key>)) { /* drain the last part of the waveform */ (*asi->asc)(wave,stream_mark,pos-stream_mark,1,asi->userdata); } /* memory free */ cst_free(mcep); free_vocoder(&vs); return wave; } static void init_vocoder(double fs, int framel, int m, VocoderSetup *vs, cst_cg_db *cg_db) { /* initialize global parameter */ vs->fprd = framel; vs->iprd = 1; vs->seed = 1; #ifdef SPEED_HACK /* This makes it about 25% faster and sounds basically the same */ vs->pd = 4; #else vs->pd = 5; #endif vs->next =1; vs->gauss = MTRUE; /* Pade' approximants */ vs->pade[ 0]=1.0; vs->pade[ 1]=1.0; vs->pade[ 2]=0.0; vs->pade[ 3]=1.0; vs->pade[ 4]=0.0; vs->pade[ 5]=0.0; vs->pade[ 6]=1.0; vs->pade[ 7]=0.0; vs->pade[ 8]=0.0; vs->pade[ 9]=0.0; vs->pade[10]=1.0; vs->pade[11]=0.4999273; vs->pade[12]=0.1067005; vs->pade[13]=0.01170221; vs->pade[14]=0.0005656279; vs->pade[15]=1.0; vs->pade[16]=0.4999391; vs->pade[17]=0.1107098; vs->pade[18]=0.01369984; vs->pade[19]=0.0009564853; vs->pade[20]=0.00003041721; vs->rate = fs; vs->c = cst_alloc(double,3 * (m + 1) + 3 * (vs->pd + 1) + vs->pd * (m + 2)); vs->p1 = -1; vs->sw = 0; vs->x = 0x55555555; /* for postfiltering */ vs->mc = NULL; vs->o = 0; vs->d = NULL; vs->irleng= 64; // for MIXED EXCITATION vs->ME_order = cg_db->ME_order; vs->ME_num = cg_db->ME_num; vs->hpulse = cst_alloc(double,vs->ME_order); vs->hnoise = cst_alloc(double,vs->ME_order); vs->xpulsesig = cst_alloc(double,vs->ME_order); vs->xnoisesig = cst_alloc(double,vs->ME_order); vs->h = cg_db->me_h; return; } static double plus_or_minus_one() { /* Randomly return 1 or -1 */ /* not sure rand() is portable */ if (rand() > RAND_MAX/2.0) return 1.0; else return -1.0; } static void vocoder(double p, double *mc, const cst_track *str, int t, int m, cst_cg_db *cg_db, VocoderSetup *vs, cst_wave *wav, long *pos) { double inc, x, e1, e2; int i, j, k; double xpulse, xnoise; double fxpulse, fxnoise; float gain=1.0; if (cg_db->gain != 0.0) gain = cg_db->gain; if (str != NULL) /* MIXED-EXCITATION */ { /* Copy in str's and build hpulse and hnoise for this frame */ for (i=0; i<vs->ME_order; i++) { vs->hpulse[i] = vs->hnoise[i] = 0.0; for (j=0; j<vs->ME_num; j++) { vs->hpulse[i] += str->frames[t][j] * vs->h[j][i]; vs->hnoise[i] += (1 - str->frames[t][j]) * vs->h[j][i]; } } } if (p != 0.0) p = vs->rate / p; /* f0 -> pitch */ if (vs->p1 < 0) { if (vs->gauss & (vs->seed != 1)) vs->next = srnd((unsigned)vs->seed); vs->p1 = p; vs->pc = vs->p1; vs->cc = vs->c + m + 1; vs->cinc = vs->cc + m + 1; vs->d1 = vs->cinc + m + 1; mc2b(mc, vs->c, m, cg_db->mlsa_alpha); if (cg_db->mlsa_beta > 0.0 && m > 1) { e1 = b2en(vs->c, m, cg_db->mlsa_alpha, vs); vs->c[1] -= cg_db->mlsa_beta * cg_db->mlsa_alpha * mc[2]; for (k=2;k<=m;k++) vs->c[k] *= (1.0 + cg_db->mlsa_beta); e2 = b2en(vs->c, m, cg_db->mlsa_alpha, vs); vs->c[0] += log(e1/e2)/2; } return; } mc2b(mc, vs->cc, m, cg_db->mlsa_alpha); if (cg_db->mlsa_beta>0.0 && m > 1) { e1 = b2en(vs->cc, m, cg_db->mlsa_alpha, vs); vs->cc[1] -= cg_db->mlsa_beta * cg_db->mlsa_alpha * mc[2]; for (k = 2; k <= m; k++) vs->cc[k] *= (1.0 + cg_db->mlsa_beta); e2 = b2en(vs->cc, m, cg_db->mlsa_alpha, vs); vs->cc[0] += log(e1 / e2) / 2.0; } for (k=0; k<=m; k++) vs->cinc[k] = (vs->cc[k] - vs->c[k]) * (double)vs->iprd / (double)vs->fprd; if (vs->p1!=0.0 && p!=0.0) { inc = (p - vs->p1) * (double)vs->iprd / (double)vs->fprd; } else { inc = 0.0; vs->pc = p; vs->p1 = 0.0; } for (j = vs->fprd, i = (vs->iprd + 1) / 2; j if (vs->p1 == 0.0) { if (vs->gauss) x = (double) nrandom(vs); else x = plus_or_minus_one(); if (str != NULL) /* MIXED EXCITATION */ { xnoise = x; xpulse = 0.0; } } else { if ((vs->pc += 1.0) >= vs->p1) { x = sqrt (vs->p1); vs->pc = vs->pc - vs->p1; } else x = 0.0; if (str != NULL) /* MIXED EXCITATION */ { xpulse = x; xnoise = plus_or_minus_one(); } } /* MIXED EXCITATION */ /* The real work -- apply shaping filters to pulse and noise */ if (str != NULL) { fxpulse = fxnoise = 0.0; for (k=vs->ME_order-1; k>0; k { fxpulse += vs->hpulse[k] * vs->xpulsesig[k]; fxnoise += vs->hnoise[k] * vs->xnoisesig[k]; vs->xpulsesig[k] = vs->xpulsesig[k-1]; vs->xnoisesig[k] = vs->xnoisesig[k-1]; } fxpulse += vs->hpulse[0] * xpulse; fxnoise += vs->hnoise[0] * xnoise; vs->xpulsesig[0] = xpulse; vs->xnoisesig[0] = xnoise; x = fxpulse + fxnoise; /* excitation is pulse plus noise */ } #ifdef SPEED_HACK /* 8KHz voices are too quiet */ x *= exp(vs->c[0])*2.0; #else x *= exp(vs->c[0])*gain; #endif x = mlsadf(x, vs->c, m, cg_db->mlsa_alpha, vs->pd, vs->d1, vs); wav->samples[*pos] = (short)x; *pos += 1; if (!--i) { vs->p1 += inc; for (k = 0; k <= m; k++) vs->c[k] += vs->cinc[k]; i = vs->iprd; } } vs->p1 = p; memmove(vs->c,vs->cc,sizeof(double)*(m+1)); return; } static double mlsadf(double x, double *b, int m, double a, int pd, double *d, VocoderSetup *vs) { vs->ppade = &(vs->pade[pd*(pd+1)/2]); x = mlsadf1 (x, b, m, a, pd, d, vs); x = mlsadf2 (x, b, m, a, pd, &d[2*(pd+1)], vs); return(x); } static double mlsadf1(double x, double *b, int m, double a, int pd, double *d, VocoderSetup *vs) { double v, out = 0.0, *pt, aa; register int i; aa = 1 - a*a; pt = &d[pd+1]; for (i=pd; i>=1; i d[i] = aa*pt[i-1] + a*d[i]; pt[i] = d[i] * b[1]; v = pt[i] * vs->ppade[i]; x += (1 & i) ? v : -v; out += v; } pt[0] = x; out += x; return(out); } static double mlsadf2 (double x, double *b, int m, double a, int pd, double *d, VocoderSetup *vs) { double v, out = 0.0, *pt, aa; register int i; aa = 1 - a*a; pt = &d[pd * (m+2)]; for (i=pd; i>=1; i pt[i] = mlsafir (pt[i-1], b, m, a, &d[(i-1)*(m+2)]); v = pt[i] * vs->ppade[i]; x += (1&i) ? v : -v; out += v; } pt[0] = x; out += x; return(out); } static double mlsafir (double x, double *b, int m, double a, double *d) { double y = 0.0; double aa; register int i; aa = 1 - a*a; d[0] = x; d[1] = aa*d[0] + a*d[1]; for (i=2; i<= m; i++) { d[i] = d[i] + a*(d[i+1]-d[i-1]); y += d[i]*b[i]; } for (i=m+1; i>1; i d[i] = d[i-1]; return(y); } static double nrandom (VocoderSetup *vs) { if (vs->sw == 0) { vs->sw = 1; do { vs->r1 = 2.0 * rnd(&vs->next) - 1.0; vs->r2 = 2.0 * rnd(&vs->next) - 1.0; vs->s = vs->r1 * vs->r1 + vs->r2 * vs->r2; } while (vs->s > 1 || vs->s == 0); vs->s = sqrt (-2 * log(vs->s) / vs->s); return(vs->r1*vs->s); } else { vs->sw = 0; return (vs->r2*vs->s); } } static double rnd (unsigned long *next) { double r; *next = *next * 1103515245L + 12345; r = (*next / 65536L) % 32768L; return(r/RANDMAX); } static unsigned long srnd ( unsigned long seed ) { return(seed); } /* mc2b : transform mel-cepstrum to MLSA digital fillter coefficients */ static void mc2b (double *mc, double *b, int m, double a) { b[m] = mc[m]; for (m--; m>=0; m--) b[m] = mc[m] - a * b[m+1]; return; } static double b2en (double *b, int m, double a, VocoderSetup *vs) { double en; int k; if (vs->o<m) { if (vs->mc != NULL) cst_free(vs->mc); vs->mc = cst_alloc(double,(m + 1) + 2 * vs->irleng); vs->cep = vs->mc + m+1; vs->ir = vs->cep + vs->irleng; } b2mc(b, vs->mc, m, a); freqt(vs->mc, m, vs->cep, vs->irleng-1, -a, vs); c2ir(vs->cep, vs->irleng, vs->ir, vs->irleng); en = 0.0; for (k=0;k<vs->irleng;k++) en += vs->ir[k] * vs->ir[k]; return(en); } /* b2bc : transform MLSA digital filter coefficients to mel-cepstrum */ static void b2mc (double *b, double *mc, int m, double a) { double d, o; d = mc[m] = b[m]; for (m--; m>=0; m--) { o = b[m] + a * d; d = b[m]; mc[m] = o; } return; } /* freqt : frequency transformation */ static void freqt (double *c1, int m1, double *c2, int m2, double a, VocoderSetup *vs) { register int i, j; double b; if (vs->d==NULL) { vs->size = m2; vs->d = cst_alloc(double,vs->size + vs->size + 2); vs->g = vs->d+vs->size+1; } if (m2>vs->size) { cst_free(vs->d); vs->size = m2; vs->d = cst_alloc(double,vs->size + vs->size + 2); vs->g = vs->d+vs->size+1; } b = 1-a*a; for (i=0; i<m2+1; i++) vs->g[i] = 0.0; for (i=-m1; i<=0; i++) { if (0 <= m2) vs->g[0] = c1[-i]+a*(vs->d[0]=vs->g[0]); if (1 <= m2) vs->g[1] = b*vs->d[0]+a*(vs->d[1]=vs->g[1]); for (j=2; j<=m2; j++) vs->g[j] = vs->d[j-1]+a*((vs->d[j]=vs->g[j])-vs->g[j-1]); } memmove(c2,vs->g,sizeof(double)*(m2+1)); return; } /* c2ir : The minimum phase impulse response is evaluated from the minimum phase cepstrum */ static void c2ir (double *c, int nc, double *h, int leng) { register int n, k, upl; double d; h[0] = exp(c[0]); for (n=1; n<leng; n++) { d = 0; upl = (n>=nc) ? nc-1 : n; for (k=1; k<=upl; k++) d += k*c[k]*h[n-k]; h[n] = d/n; } return; } static void free_vocoder(VocoderSetup *vs) { cst_free(vs->c); cst_free(vs->mc); cst_free(vs->d); vs->c = NULL; vs->mc = NULL; vs->d = NULL; vs->ppade = NULL; vs->cc = NULL; vs->cinc = NULL; vs->d1 = NULL; vs->g = NULL; vs->cep = NULL; vs->ir = NULL; cst_free(vs->hpulse); cst_free(vs->hnoise); cst_free(vs->xpulsesig); cst_free(vs->xnoisesig); return; }
// @flow import { install } from 'redux-loop'; import createHistory from 'history/createMemoryHistory'; import { routerMiddleware } from 'react-router-redux'; import { applyMiddleware, createStore } from 'redux'; import { composeWithDevTools } from '<API key>'; import { initialState, reducer } from './reducers'; export const history = createHistory(); const composeEnhancers = composeWithDevTools( { realtime: true, port: 8000, hostname: 'localhost' } ); const enhancer = composeEnhancers( install(), applyMiddleware(routerMiddleware(history)), ); export const store = createStore(reducer, initialState, enhancer);