code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
import logging from abc import ABCMeta, abstractmethod from collections import deque from typing import List, Union, Iterable, Sequence log = logging.getLogger(__name__) class NoSensorsFoundException(RuntimeError): pass class Controller(metaclass=ABCMeta): @abstractmethod def run(self): raise NotImplementedError @abstractmethod def enable(self): raise NotImplementedError @abstractmethod def disable(self): raise NotImplementedError @abstractmethod def valid(self) -> bool: raise NotImplementedError class InputDevice(metaclass=ABCMeta): """ Abstract class for input devices. """ def __init__(self, name): self.name = name self.values = ValueBuffer(name, 128) @abstractmethod def get_value(self) -> float: raise NotImplementedError class OutputDevice(metaclass=ABCMeta): """ Abstract class for output devices. """ def __init__(self, name): self.name = name self.values = ValueBuffer(name, 128) def set_value(self, value: Union[int, float]): self.values.update(value) @abstractmethod def apply(self): raise NotImplementedError @abstractmethod def enable(self): raise NotImplementedError @abstractmethod def disable(self): raise NotImplementedError class PassthroughController(Controller): def __init__(self, inputs=Sequence[InputDevice], outputs=Sequence[OutputDevice], speeds=None): self.inputs = list(inputs) self.outputs = list(outputs) def run(self): for idx, input_reader in enumerate(self.inputs): output = self.outputs[idx] output.name = input_reader.name output.values.name = input_reader.name output.set_value(input_reader.get_value()) output.apply() log.debug('ran loop') def apply_candidates(self): return self.outputs def enable(self): for output_dev in self.outputs: output_dev.enable() def disable(self): for output_dev in self.outputs: output_dev.disable() def valid(self) -> bool: return bool(self.inputs and self.outputs) and len(self.inputs) == len(self.outputs) class DummyInput(InputDevice): def __init__(self): super().__init__('dummy') self.temp = 0 def get_value(self): return self.temp def set_value(self, value): self.temp = value class DummyOutput(OutputDevice): def __init__(self): super().__init__('dummy') self.speed = None self.enabled = False def apply(self): if self.enabled: self.speed = round(self.values.mean()) def enable(self): self.enabled = True def disable(self): self.enabled = False def mean(seq: Iterable) -> float: if not isinstance(seq, Iterable): raise ValueError('provided sequence MUST be iterable') if not isinstance(seq, Sequence): seq = list(seq) if len(seq) == 1: return float(seq[0]) if len(seq) == 0: raise ValueError('sequence must have at least one value.') return sum(seq) / len(seq) def lerp(value: Union[float, int], input_min: Union[float, int], input_max: Union[float, int], output_min: Union[float, int], output_max: Union[float, int]) -> float: if value <= input_min: return float(output_min) if value >= input_max: return float(output_max) return (output_min * (input_max - value) + output_max * (value - input_min)) / (input_max - input_min) def lerp_range(seq: Iterable[Union[float, int]], input_min, input_max, output_min, output_max) -> List[float]: return [lerp(val, input_min, input_max, output_min, output_max) for val in seq] class ValueBuffer: def __init__(self, name, default_value=0.0): self.name = name self.buffer = deque(maxlen=32) self._default_value = default_value def update(self, value: float): self.buffer.append(value) def mean(self) -> float: try: return mean(self.buffer) except (ValueError, ZeroDivisionError): return self._default_value
vrga/pyFanController
pyfc/common.py
Python
mit
4,243
import { injectable, inject } from "inversify"; import { TYPES } from "../ioc/types"; const cacheKey = "AleksaDiscordServerSelection"; @injectable() export class ServerSelectorService { constructor( @inject(TYPES.IConfig) private _config: IConfig, @inject(TYPES.Logger) private _logger: ILogger, @inject(TYPES.IBasicCache) private _cache: IBasicCache, ) { } /** * Change to the new server * @param name */ public async changeServer(name: string): Promise<void> { const servers: IServer[] = this._config.app.aleksa.discord.servers; const matches = servers.filter(s => s.name.indexOf(name) > -1); const selection = matches.length > 0 ? matches[0] : servers[0]; this._logger.info(`Changing server to ${name}`); // Ensure never expired this._cache.set(cacheKey, JSON.stringify(selection), 0); } /** * Get the current selected server */ public async getServer(): Promise<IServer> { if(await this._cache.has(cacheKey)) { return JSON.parse(await this._cache.get(cacheKey)) as IServer; } return this._config.app.aleksa.discord.servers[0] as IServer; } } export interface IServer { name: string; guildId: string; channelId: string; userId: string; }
arijoon/vendaire-discord-bot
src/aleksa/server-selector.service.ts
TypeScript
mit
1,262
// PS4Macro (File: Forms/MainForm.cs) // // Copyright (c) 2018 Komefai // // Visit http://komefai.com for more information // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using PS4Macro.Classes; using PS4Macro.Classes.GlobalHooks; using PS4Macro.Classes.Remapping; using PS4RemotePlayInterceptor; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace PS4Macro.Forms { enum ControlMode { Macro, Script, Remapper, StatusChecker } public partial class MainForm : Form { private const string CURRENT_TICK_DEFAULT_TEXT = "-"; private GlobalKeyboardHook m_GlobalKeyboardHook; private GlobalMouseHook m_GlobalMouseHook; private MacroPlayer m_MacroPlayer; private Remapper m_Remapper; private StatusChecker m_StatusChecker; private ControlMode m_ControlMode; private PS4MacroAPI.ScriptBase m_SelectedScript; private ScriptHost m_ScriptHost; private SaveLoadHelper m_SaveLoadHelper; private Process m_RemotePlayProcess; /* Constructor */ public MainForm() { InitializeComponent(); // Setup global keyboard hook m_GlobalKeyboardHook = new GlobalKeyboardHook(); m_GlobalKeyboardHook.KeyboardPressed += OnKeyPressed; // Setup global mouse hook m_GlobalMouseHook = new GlobalMouseHook(); m_GlobalMouseHook.MouseEvent += OnMouseEvent; // Create macro player m_MacroPlayer = new MacroPlayer(); m_MacroPlayer.Loop = true; m_MacroPlayer.RecordShortcut = true; m_MacroPlayer.PropertyChanged += MacroPlayer_PropertyChanged; // Create remapper m_Remapper = new Remapper(); // Create status checker m_StatusChecker = new StatusChecker(); // Set control mode SetControlMode(ControlMode.Macro); // Create save/load helper m_SaveLoadHelper = new SaveLoadHelper(this, m_MacroPlayer); m_SaveLoadHelper.PropertyChanged += SaveLoadHelper_PropertyChanged; // Initialize interceptor InitInterceptor(); } private void InitInterceptor() { // Set controller emulation based on settings Interceptor.EmulateController = Program.Settings.EmulateController; emulatedToolStripStatusLabel.Visible = Program.Settings.EmulateController; // Enable watchdog based on settings if (!Program.Settings.AutoInject) { Interceptor.InjectionMode = InjectionMode.Compatibility; } // Inject if not bypassed if (!Program.Settings.BypassInjection) { // Attempt to inject into PS4 Remote Play try { int pid = Interceptor.Inject(); m_RemotePlayProcess = Process.GetProcessById(pid); // Set process ForwardRemotePlayProcess(); } // Injection failed catch (InterceptorException ex) { // Only handle when PS4 Remote Play is in used by another injection if (ex.InnerException != null && ex.InnerException.Message.Equals("STATUS_INTERNAL_ERROR: Unknown error in injected C++ completion routine. (Code: 15)")) { MessageBox.Show("The process has been injected by another executable. Restart PS4 Remote Play and try again.", "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } else { // Handle exception if watchdog is disabled if (!Program.Settings.AutoInject) { MessageBox.Show(string.Format("[{0}] - {1}", ex.GetType(), ex.Message), "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } } } // Start watchdog to automatically inject when possible if (Program.Settings.AutoInject) { Interceptor.Watchdog.Start(); // Watchdog callbacks Interceptor.Watchdog.OnInjectionSuccess = () => { ForwardRemotePlayProcess(); }; Interceptor.Watchdog.OnInjectionFailure = () => { }; } } } private void SetControlMode(ControlMode controlMode) { m_ControlMode = controlMode; if (m_ControlMode == ControlMode.Macro) { // Stop script and remove if (m_ScriptHost != null && m_ScriptHost.IsRunning) { m_ScriptHost.Stop(); m_ScriptHost = null; } // Setup callback to interceptor Interceptor.Callback = new InterceptionDelegate(m_MacroPlayer.OnReceiveData); recordButton.Enabled = true; recordToolStripMenuItem.Enabled = true; loopCheckBox.Enabled = true; loopCheckBox.Checked = m_MacroPlayer.Loop; loopToolStripMenuItem.Enabled = true; recordOnTouchToolStripMenuItem.Enabled = true; scriptButton.Enabled = false; saveToolStripMenuItem.Enabled = true; saveAsToolStripMenuItem.Enabled = true; clearMacroToolStripMenuItem.Enabled = true; trimMacroToolStripMenuItem.Enabled = true; } else if (m_ControlMode == ControlMode.Script) { // Stop macro player if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record(); m_MacroPlayer.Stop(); // Setup callback to interceptor Interceptor.Callback = new InterceptionDelegate(m_ScriptHost.OnReceiveData); recordButton.Enabled = false; recordToolStripMenuItem.Enabled = false; loopCheckBox.Enabled = false; loopCheckBox.Checked = false; loopToolStripMenuItem.Enabled = false; recordOnTouchToolStripMenuItem.Enabled = false; scriptButton.Enabled = true; saveToolStripMenuItem.Enabled = false; saveAsToolStripMenuItem.Enabled = false; clearMacroToolStripMenuItem.Enabled = false; trimMacroToolStripMenuItem.Enabled = false; currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT; } else if (m_ControlMode == ControlMode.Remapper) { // Stop macro player if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record(); m_MacroPlayer.Stop(); // Stop script if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop(); // Setup callback to interceptor Interceptor.Callback = new InterceptionDelegate(m_Remapper.OnReceiveData); } else if (m_ControlMode == ControlMode.StatusChecker) { // Stop macro player if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record(); m_MacroPlayer.Stop(); // Stop script if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop(); // Setup callback to interceptor Interceptor.Callback = new InterceptionDelegate(m_StatusChecker.OnReceiveData); } } private void TemporarilySetControlMode(ControlMode controlMode, Action action) { // Store current control mode and temporarily set it ControlMode oldControlMode = m_ControlMode; SetControlMode(controlMode); // Invoke action action?.Invoke(); // Restore control mode SetControlMode(oldControlMode); } private void ForwardRemotePlayProcess() { m_Remapper.RemotePlayProcess = m_RemotePlayProcess; m_StatusChecker.RemotePlayProcess = m_RemotePlayProcess; } public void LoadMacro(string path) { SetControlMode(ControlMode.Macro); m_MacroPlayer.LoadFile(path); } public void LoadScript(string path) { var script = PS4MacroAPI.Internal.ScriptUtility.LoadScript(path); m_SelectedScript = script; m_ScriptHost = new ScriptHost(this, m_SelectedScript); m_ScriptHost.PropertyChanged += ScriptHost_PropertyChanged; SetControlMode(ControlMode.Script); } private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e) { if (m_ControlMode == ControlMode.Remapper) { m_Remapper.OnKeyPressed(sender, e); } else if (m_ControlMode == ControlMode.StatusChecker) { m_StatusChecker.OnKeyPressed(sender, e); } } private void OnMouseEvent(object sender, GlobalMouseHookEventArgs e) { if (m_ControlMode == ControlMode.Remapper) { m_Remapper.OnMouseEvent(sender, e); } else if (m_ControlMode == ControlMode.StatusChecker) { m_StatusChecker.OnMouseEvent(sender, e); } } private void MainForm_Load(object sender, EventArgs e) { // Load startup file if (!string.IsNullOrWhiteSpace(Program.Settings.StartupFile)) m_SaveLoadHelper.DirectLoad(Program.Settings.StartupFile); } /* Macro Player */ #region MacroPlayer_PropertyChanged private void UpdateCurrentTick() { BeginInvoke((MethodInvoker)delegate { // Invalid sequence if (m_MacroPlayer.Sequence == null || m_MacroPlayer.Sequence.Count <= 0) { currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT; } // Valid sequence else { currentTickToolStripStatusLabel.Text = string.Format("{0}/{1}", m_MacroPlayer.CurrentTick.ToString(), m_MacroPlayer.Sequence.Count.ToString() ); } }); } private void MacroPlayer_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsPlaying": { playButton.ForeColor = m_MacroPlayer.IsPlaying ? Color.Green : DefaultForeColor; break; } case "IsPaused": { playButton.ForeColor = m_MacroPlayer.IsPaused ? DefaultForeColor : playButton.ForeColor; break; } case "IsRecording": { recordButton.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor; currentTickToolStripStatusLabel.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor; break; } case "CurrentTick": { UpdateCurrentTick(); break; } case "Sequence": { UpdateCurrentTick(); break; } case "Loop": { loopCheckBox.Checked = m_MacroPlayer.Loop; loopToolStripMenuItem.Checked = m_MacroPlayer.Loop; break; } case "RecordShortcut": { recordOnTouchToolStripMenuItem.Checked = m_MacroPlayer.RecordShortcut; break; } } } #endregion /* Script Host */ #region ScriptHost_PropertyChanged private void ScriptHost_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsRunning": { playButton.ForeColor = m_ScriptHost.IsRunning ? Color.Green : DefaultForeColor; break; } case "IsPaused": { if (m_ScriptHost.IsPaused && m_ScriptHost.IsRunning) { playButton.ForeColor = DefaultForeColor; } else if (!m_ScriptHost.IsPaused && m_ScriptHost.IsRunning) { playButton.ForeColor = Color.Green; } break; } } } #endregion /* Save/Load Helper */ #region SaveLoadHelper_PropertyChanged private void SaveLoadHelper_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "CurrentFile") { if (m_SaveLoadHelper.CurrentFile == null) { fileNameToolStripStatusLabel.Text = SaveLoadHelper.DEFAULT_FILE_NAME; currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT; } else { fileNameToolStripStatusLabel.Text = System.IO.Path.GetFileName(m_SaveLoadHelper.CurrentFile); } } } #endregion /* Playback buttons methods */ #region Playback Buttons private void playButton_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Play(); } else if (m_ControlMode == ControlMode.Script) { m_ScriptHost.Play(); } } private void pauseButton_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Pause(); } else if (m_ControlMode == ControlMode.Script) { m_ScriptHost.Pause(); } } private void stopButton_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Stop(); } else if (m_ControlMode == ControlMode.Script) { m_ScriptHost.Stop(); } } private void recordButton_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Record(); } } private void loopCheckBox_CheckedChanged(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Loop = loopCheckBox.Checked; } } #endregion /* Script buttons methods */ #region Script Buttons private void scriptButton_Click(object sender, EventArgs e) { m_ScriptHost.ShowForm(this); } #endregion /* Menu strip methods */ #region Menu Strip #region File private void newToolStripMenuItem_Click(object sender, EventArgs e) { SetControlMode(ControlMode.Macro); m_MacroPlayer.Clear(); m_SaveLoadHelper.ClearCurrentFile(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { m_SaveLoadHelper.Load(); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { m_SaveLoadHelper.Save(); } private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { m_SaveLoadHelper.SaveAs(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } #endregion #region Edit private void clearMacroToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Clear(); } } private void trimMacroToolStripMenuItem_Click(object sender, EventArgs e) { m_MacroPlayer.Stop(); var oldSequenceLength = m_MacroPlayer.Sequence.Count; m_MacroPlayer.Sequence = MacroUtility.TrimMacro(m_MacroPlayer.Sequence); // Show results var difference = oldSequenceLength - m_MacroPlayer.Sequence.Count; MessageBox.Show( $"{difference} frames removed" + "\n\n" + $"Before: {oldSequenceLength} frames" + "\n" + $"After: {m_MacroPlayer.Sequence.Count} frames", "Trim Macro", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion #region Playback private void playToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Play(); } } private void pauseToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Pause(); } } private void stopToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Stop(); } } private void recordToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Record(); } } private void loopToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.Loop = !loopToolStripMenuItem.Checked; } } private void recordOnTouchToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ControlMode == ControlMode.Macro) { m_MacroPlayer.RecordShortcut = !recordOnTouchToolStripMenuItem.Checked; } } #endregion #region Tools private void screenshotToolStripMenuItem_Click(object sender, EventArgs e) { var backgroundMode = !(ModifierKeys == Keys.Shift); var frame = PS4MacroAPI.Internal.ScriptUtility.CaptureFrame(backgroundMode); var folder = "screenshots"; // Create folder if not exist Directory.CreateDirectory(folder); if (frame != null) { var fileName = folder + @"\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"; frame.Save(fileName); Console.WriteLine($"{DateTime.Now.ToString()} - Screenshot saved to {Path.GetFullPath(fileName)}"); } else { MessageBox.Show("Unable to capture screenshot!"); } } private void imageHashToolToolStripMenuItem_Click(object sender, EventArgs e) { new ImageHashForm().Show(this); } private void resizeRemotePlayToolStripMenuItem_Click(object sender, EventArgs e) { new ResizeRemotePlayForm().ShowDialog(this); } private void macroCompressorToolStripMenuItem_Click(object sender, EventArgs e) { new MacroCompressorForm().ShowDialog(this); } private void remapperToolStripMenuItem_Click(object sender, EventArgs e) { TemporarilySetControlMode(ControlMode.Remapper, () => { new RemapperForm(m_Remapper).ShowDialog(this); }); } #endregion #region Help private void statusCheckerToolStripMenuItem_Click(object sender, EventArgs e) { TemporarilySetControlMode(ControlMode.StatusChecker, () => { m_StatusChecker.SetActive(true); new StatusCheckerForm(m_StatusChecker).ShowDialog(this); m_StatusChecker.SetActive(false); }); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { var aboutForm = new AboutForm(); aboutForm.ShowDialog(this); } #endregion #endregion /* Status strip methods */ #region Status Strip #endregion } }
komefai/PS4Macro
PS4Macro/Forms/MainForm.cs
C#
mit
23,676
# 2016_Facebook_Test
kendall-lewis/2016_Facebook_Test
README.md
Markdown
mit
21
TAG?=latest .PHONY: build build: ./build.sh .PHONY: build-gateway build-gateway: (cd gateway; ./build.sh latest-dev) .PHONY: test-ci test-ci: ./contrib/ci.sh .PHONY: ci-armhf-build ci-armhf-build: (cd gateway; ./build.sh $(TAG) ; cd ../auth/basic-auth ; ./build.sh $(TAG)) .PHONY: ci-armhf-push ci-armhf-push: (cd gateway; ./push.sh $(TAG) ; cd ../auth/basic-auth ; ./push.sh $(TAG)) .PHONY: ci-arm64-build ci-arm64-build: (cd gateway; ./build.sh $(TAG) ; cd ../auth/basic-auth ; ./build.sh $(TAG)) .PHONY: ci-arm64-push ci-arm64-push: (cd gateway; ./push.sh $(TAG) ; cd ../auth/basic-auth ; ./push.sh $(TAG))
rgee0/faas
Makefile
Makefile
mit
624
let fs = require("fs"); let path = require("path"); let cp = require("child_process"); function runCommand(folder, args) { cp.spawn("npm", args, { env: process.env, cwd: folder, stdio: "inherit" }); } function getPackages(category) { let folder = path.join(__dirname, category); return fs .readdirSync(folder) .map(function(dir) { let fullPath = path.join(folder, dir); // check for a package.json file if (!fs.existsSync(path.join(fullPath, "package.json"))) { return; } return fullPath; }) .filter(function(pkg) { return pkg !== undefined; }); } function runCommandInCategory(category, args) { let pkgs = getPackages(category); pkgs.forEach(function(pkg) { runCommand(pkg, args); }); } let CATEGORIES = ["react", "vue", "svelte", "misc"]; let category = process.argv[2]; let args = process.argv.slice(3); if (category === "all") { CATEGORIES.forEach(function(c) { runCommandInCategory(c, args); }); } else { runCommandInCategory(category, args); }
pshrmn/curi
examples/updateCategory.js
JavaScript
mit
1,046
// // AppDelegate.h // wufeng_cocoapods // // Created by tomodel on 2017/3/4. // Copyright © 2017年 tomodel. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
wufeng880707/wufeng_test
wufeng_cocoapods/AppDelegate.h
C
mit
283
// download the contents of a url package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { res, err := http.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } robots, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", robots) }
andrew/go-experiments
get.go
GO
mit
333
# DOMHooks Hooks functions' execution to DOM queries. DOMHooks is an utility function meant for DOM contextual scripting. By using it you can pair a specific DOM selector (or HTML class selector) with a function which needs to be executed just on that context. Example: ```javascript //old pattern jQuery(document).ready(function ($) { var $foo = $('#foo'); if ($foo.length) { $foo.doSomething(); //... } }); //with DOMHooks $.domHooks({ //no need to wrap in a DOMReady function! '#foo': function (selector, $foo) { //selector === '#foo' $foo.doSomething(); } }); ``` ## Getting Started Via [Bower](https://github.com/twitter/bower)... ``` bower install jquery.domhooks ``` ... or download the [production version][min] or the [development version][max]. [min]: https://raw.github.com/dwightjack/domhooks/master/dist/domhooks.min.js [max]: https://raw.github.com/dwightjack/domhooks/master/dist/domhooks.js In your web page: ```html <script src="jquery.js"></script> <script src="/path/to/domhooks.min.js"></script> <script> //no need to wrap in a DOMReady function! $.domHooks(/* args... */); </script> ``` ## Documentation ### Usage `$.domHooks` accepts up to three arguments: * `type`: Type of hook, either `'ready'`, `'html'` or `'available'`. (see below for details) * `query`: Query to execute, either a CSS selector (`'ready'` and `'available'` types) or a class name (`'html'` type) * `callback`: Function to execute when `query` is matched. The function accepts two arguments: the `query` itself and a jQuery object referencing to it Basic usage example: ```javascript $.domHook('ready', '#foo', function () { /* ... */}); ``` You may also pass `query` in the form of an hash `{'selector': callback}`: ```javascript //same as before but shorter $.domHook('ready', { '#foo': function () { /* ... */} }); ``` Or you may omit the `type` argument completely, a `'ready'` hook type will always be implied: ```javascript //even shorter, but just for 'ready' hooks $.domHook({ '#foo': function () { /* ... */} }); ``` ### Settings **Breaking changes!!!** **Up to v0.1.0b `.pollsMax` and `.pollsInterval` where called `.polls_max` and `.polls_interval`.** `$.domHooks` exposes also two options used by the `'available'` hook type: * `$.domHooks.settings.pollsMax`: The number of polls after which the hook gets discarted (defaults to `40`) * `$.domHooks.settings.pollsInterval`: The interval in ms between each poll (defaults to `25`) _Note that these settings are globals to every function call, and they may prejudice the overall performances of the page._ ### Query types **ready** hooks got parsed automatically on DOM Ready. Hooks added after DOM Ready are parsed right away. They accept CSS selector as query string. **html** hooks got parsed as soon as they are added, since the `html` element always exists before the DOM is ready. They accept a single class name as query string (use [.hasClass](http://api.jquery.com/hasClass/) internally). **available** hooks got parsed as soon as they are added and try to match a DOM element _BEFORE_ the DOM is ready. They work very similarly to the [available event in YUI](http://yuilibrary.com/yui/docs/event/domready.html#available), by polling the DOM for a given element at regular intervals. If the query isn't matched they fail silently. _Since these hooks are expensive in terms of performances, use them sparingly._ ## Release History * 0.1.2 Added [Bower](https://github.com/twitter/bower) support * 0.1.1 Bugfixes * 0.1.0b Initial release
dwightjack/domhooks
README.md
Markdown
mit
3,560
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ColorPickerModule } from 'angular2-color-picker'; // components import { ShellComponent } from './components/shell'; import { HelloComponent } from './components/hello'; import { OpenFolderComponent } from './components/folder'; import { SettingsComponent } from './components/settings'; import { AboutComponent } from './components/about'; // pipes import { SVGPipe } from './pipes/SVGPipe'; // services import { IpcRendererService } from './services/ipcRender'; import { StorageService } from './services/storage'; import { ComponentService } from './services/componentService'; // directives import { WebviewDirective } from './directives/webview'; // routes import { appRoutes } from './routes'; @NgModule({ imports: [ BrowserModule, CommonModule, FormsModule, ReactiveFormsModule, ColorPickerModule, RouterModule.forRoot(appRoutes) ], declarations: [ ShellComponent, HelloComponent, OpenFolderComponent, SettingsComponent, AboutComponent, SVGPipe, WebviewDirective ], bootstrap: [ShellComponent], providers: [IpcRendererService, StorageService, ComponentService] }) export class Module { }
vijayantkatyal/svg-bits
src/module.ts
TypeScript
mit
1,406
--- layout: post author: Luís Cruz title: 16 Guidelines for Effective Data Visualizations in Academic Papers summary: "This article presents basic guidelines to help create effective visualizations. There are no golden rules, but there are some basic guidelines that I find useful based on my experience as an academic. I wrote this article having academic writing in mind, but it is certainly useful for any type of communication." image: "img/blog/og_image.jpg" show_image: True bibtex: |- @misc{cruz2021effective, title = {16 Guidelines for Effective Data Visualizations in Academic Papers}, author = {Lu\'{i}s Cruz}, year = {2021}, howpublished={\url{http://luiscruz.github.io/2021/03/01/effective-visualizations.html}}, note = {Blog post.} } --- <span class="first-letter">I</span>n any research field, we academics devote a considerable part of our work to deliver high-quality articles. We put our best efforts to create engaging narratives that communicate our latest findings. This is a quintessential requirement to publish our research in top-tier academic conferences. Many academics have written about writing best practices or mere tips to help junior researchers avoid common mistakes. These are quite useful. For example, it is quite common to see students misusing hyphen, en dash, and em dash properly ([Wikipedia can help you there](https://nps.edu/web/gwc/dashes-and-hyphens)). If you are interested in learning about writing tips, [Mark Harman's Draft Guidelines] and [Arie van Derusen's Recommendations] are definitely great reads. But a good article is not only made of text. It typically comes with figures that help presenting results and are nicely tied to the narrative. Very often, figures are the only way researchers have to present results without creating a big mess of boring numbers in a table. When done properly, figures speak for themselves, even before someone reads the whole document. This is very important because we want to give readers (including reviewers!) a good first impression. While reading academic papers, I started being triggered by some visualizations that did not feel right. Sometimes it was really difficult to understand them, even after reading the whole text. Since I never had any formal education on this topic, I decided to learn more about it. ## Tufte's Visualization Principles While reading about this, I realised that there is one main person that keeps being referenced: [Edward Tufte] with his work written in 1986 about the principles for effective information visualizations. I immediately bought a second-hand copy of *The Visual Display of Quantitative Information* and read it straight away. ![The Visual Display of Quantitative Information by Edward Tufte (1986).](/img/blog/tufte_book.jpg){: class="center-block" width="200px" } <p class="text-center text-muted"><small>The Visual Display of Quantitative Information by Edward Tufte (1986).</small></p> The first thing I learned from it was that there are no "golden rules" that work for all your visualizations. Visualization are very heterogenous. They communicate all types of data using color, shapes, angles, size, shade, and other visual variables. The second thing I learned was that, while analyzing "golden rules", you develop the critical thinking and intuition that helps you create effective information visualizations. Here are the principles for graphical excellence that Edward Tufte proposes in his book: 1. Above all else, show the data. Create the simplest graph that conveys the information you want to present. 2. Maximize the data-ink ratio. Every bit of ink requires a reason. Nearly always, that reason should be to present new information 3. Erase non-data-ink. 4. Erase redundant data-ink. 5. Revise and edit. The above mentioned data-ink ratio is a metric proposed by Tufte to measure the amount of ink that a graphic uses to exclusively represent data/information. All the pixels that do not meet this requirement are considered non-data ink (this was written in 1986 -- *ink* was a more popular term than *pixels* at the time). What I like about these principles is that they highlight the fact that **graphical excellence is an iterative process**. In every iteration, we rethink whether each pixel in the visualization is really necessary. Ultimately, **in every visualization we must make sure that we are presenting the data and its message** — nothing else. There is actually a name for all those superfluous elements that should be left out of the visualization: **chartjunk**. A typical example of chartjunk are the 3D effects — they simply add pixels to the image without revealing any new pattern of the data. ![Example of chartjunk provided in Edward Tufte's book.](/img/blog/chartjunk.jpg){: class="center-block" width="300px" } <p class="text-center text-muted"><small>Example of chartjunk provided in Edward Tufte's book.</small></p> There are many other relevant concepts in Tufte's book (e.g., graphical integrity) but we have to move on. I recommend reading the book as it is a quick-read and full of practical examples. The main thing I earned from reading the book was critical thinking. Now, whenever I look into a data visualization, I start reasoning about whether it is presented in the most effective way. ## The Guidelines Although there are no "golden rules", one should keep in mind some basic guidelines that work most of the time. They are useful as long as we use them wisely, always having in mind that *above all else*, we want to *show the data*. So, here is a list of all the guidelines I was able to collect from different sources. You may find these referred at the end of this post. **Guideline #1 – *Visualizations ought to be self-explanatory*.** If you require the reader to go back and forth between the text and the figure, you are asking for an extra effort. Simple things help fix this. For example, having a clear title or caption is half-way to having an easy-to-read figure. Moreover, all axis should be carefully labelled and presented with the respective units of measurement. **Guideline #2 – Turn off the box around the figure.** The same for the boxes connecting the axes. This is so common, and I actually find it strange that most libraries draw these boxes by default (e.g., python visualization library [Matplotlib]). **Guideline #3 – Only have one x- and one y-axis.** It is very tempting to use two y-axes to compare different variables and to present data patterns from different angles. Not only it makes the visualization overwhelming and difficult to understand, but also it may inadvertently pose spurious correlations. [Tyler Vigen's work] brilliantly exposes this issue, using this strategy to establish correlations between variables that are totally unrelated. **Guideline #4 – Use visual variables (color, shape, shade) only for data variation.** **Guideline #5 – Axes must start at a meaningful baseline.** E.g., bar charts should start at zero (most of the time). When this guideline is not followed, some data patterns will most likely be distorted. See the example in the figure below. ![The value of B looks 3 times bigger than A. The y-axis is starting at Y=900.](/img/blog/axis_zero.png){: class="center-block" width="400px" } The height of the bar of B looks **three times bigger** than the bar of A – an increase of 300%. However, from A to B the data only increases 20% (my math: `(1200-1000)/1000 * 100%`). The y-axis is starting at 900 instead of starting from its natural baseline: **0**. This distortion is often used to amplify results, misleading the reader. The same graph without distortion would look as follows: ![The value of B looks 3 times bigger than A. The y-axis is starting at Y=900.](/img/blog/axis_zero_fixed.png){: class="center-block" width="400px" } **Guideline #6 – Never use different colors to represent the same kind of data.** It is tempting to use different colors only for aesthetic purposes. The downside is that it inherently asks our brain to understand the reason for that variation. This is a **waste** of energy you shouldn't ask from your readers. **Guideline #7 – Label elements directly, avoiding indirect look-up.** Avoid requiring your reader to go back and forth through the different elements of your graph (and sometimes text) to understand your figure. Remember what I said about waste?… For example, avoid using a legend when you can label that information directly in the objects without making the graph more complicated. This is, of course, one of those rules with many exceptions. Never forget to be critical about guidelines! The figure below shows two bar plots: the first does not follow this guideline; the second applies this guideline by labelling the values directly on top of each bar. *Which one do you think is easier to read?* ![Two bar plots: the first with an axis legend; the second with the values labeled directly in the bar.](/img/blog/labels.png){: class="center-block" width="500px" } <p class="text-center text-muted" markdown='1'> <small>Plots from Ryan Sleeper's article *[Data-Ink Ratio Animation and How to Apply it in Tableau]*.</small> </p> **Guideline #8 – Text labels should never be rotated (nor vertical).** E.g., use a horizontal bar chart when category names are too long. This seems like a tiny detail, but I recommend you to try it the next time you create a visualization. Details matter. **Guideline #9 – Highlight what's important.** An image is worth a thousand words. And your visualization is no exception. But you need to guide the reader to a few messages you find essential . You don't want your readers to waste energy processing irrelevant messages while overlooking the most important ones. **Guideline #10 – Use bold type/lines only to emphasize something.** This one follows the previous guideline. Keep your reader focused and straight to the point. **Guideline #11 – Don’t use 3D effects.** I hope I don't need to explain this one. 🙃 **Guideline #12 – Avoid pie charts (and donut charts).** It is difficult to compare many slices in a pie chart. Very simple charts are the exception. **Guideline #13 – Sort data for easier comparisons.** E.g., in a pie chart or bar chart, it is easier to compare the sizes of the different bars if they are sorted according to their size. **Guideline #14 – Don’t be afraid of creating separate graphs.** If your graph is getting overly complex, think of ways of dividing it in multiple graphs. A nice way of doing this is by thinking about the messages you really want to convey in the figure. Then, you need to divide those messages in two groups and illustrate these groups in separate graphs. **Guideline #15 – Use line plots only when variables are ordinal or numerical.** Line plots connect data points sequentially and show something typically called **trend** between those data points. If the variable has no particular order but we show a trend between sequential data points, we might be sending a wrong message. **Guideline #16 – Care for colorblindness.** It is estimated that colorblindness affects 8% of men worldwide. Thus, it is important to make sure that the color you use to highlight data patterns is perceptible by everyone. For most people affected by this condition, red and green are indistinguishable – use these colors with care. Sometimes it is hard to avoid using red and green, as they are typically used to denote good and bad, success and failure, etc. In these cases, you may want to pick red and green colors that differ in their saturation level. Test your images with tools like [Coblis]. ## Wrap-up And that's all, folks. Don't forget that *for every rule there is an exception* – after all, that's what makes it fun. Thanks for reading. I look forward to hearing about your thoughts and how these guidelines may or may not help you create data visualizations. [Connect on Twitter](https://twitter.com/luismcruz) and share your experience. ### Recommended Readings - Edward Tufte (1983). [The Visual Display of Quantitative Information](https://www.goodreads.com/book/show/17744.The_Visual_Display_of_Quantitative_Information). Graphics Press. - Cole Nussbaumer Knaflic (2015). [Storytelling with data](https://www.goodreads.com/book/show/26535513-storytelling-with-data). Wiley - Google. [Material Design Docs]. - Christa Kelleher, Thorsten Wagener (2010). [Ten guidelines for effective data visualization in scientific publications](https://doi.org/10.1016/j.envsoft.2010.12.006). - Ryan Sleeper. [Data-Ink Ratio Animation and How to Apply it in Tableau]. [Mark Harman's Draft Guidelines]: https://cragkhit.github.io/files/harman-writing-advice.pdf [Mary Shaw's minitutorial]: https://www.cs.cmu.edu/~Compose/shaw-icse03.pdf [Arie van Derusen's Recommendations]: https://avandeursen.com/2013/07/10/research-paper-writing-recommendations/ [Edward Tufte]: https://www.edwardtufte.com [Matplotlib]: https://matplotlib.org [Tyler Vigen's work]: https://www.tylervigen.com/spurious-correlations [Data-Ink Ratio Animation and How to Apply it in Tableau]: https://playfairdata.com/data-ink-ratio-animation-and-how-to-apply-it-in-tableau/ [Material Design Docs]: https://material.io/design/communication/data-visualization.html [Share your comments on Twitter]: https://twitter.com/intent/tweet?url={{site.url}}{{page.url}}&text=Check%20out%20these%20guidelines%20for%20information%20visualization!%20By%20@luismcruz [Coblis]: https://www.color-blindness.com/coblis-color-blindness-simulator/
luiscruz/luiscruz.github.io
_posts/2021-03-01-effective-visualizations.md
Markdown
mit
13,619
<?php $_pluginInfo=array( 'name'=>'Inet', 'version'=>'1.0.3', 'description'=>"Get the contacts from a Inet account", 'base_version'=>'1.8.0', 'type'=>'email', 'check_url'=>'http://inet.ua/index.php', 'requirement'=>'email', 'allowed_domains'=>array('/(inet.ua)/i','/(fm.com.ua)/i'), ); /** * Inet Plugin * * Imports user's contacts from Inet AddressBook * * @author OpenInviter * @version 1.0.0 */ class inet extends openinviter_base { private $login_ok=false; public $showContacts=true; public $internalError=false; protected $timeout=30; public $debug_array=array( 'initial_get'=>'login_username', 'login_post'=>'frame', 'url_redirect'=>'passport', 'url_export'=>'FORENAME', ); /** * Login function * * Makes all the necessary requests to authenticate * the current user to the server. * * @param string $user The current user. * @param string $pass The password for the current user. * @return bool TRUE if the current user was authenticated successfully, FALSE otherwise. */ public function login($user,$pass) { $this->resetDebugger(); $this->service='inet'; $this->service_user=$user; $this->service_password=$pass; if (!$this->init()) return false; $res=$this->get("http://inet.ua/index.php"); if ($this->checkResponse("initial_get",$res)) $this->updateDebugBuffer('initial_get',"http://inet.ua/index.php",'GET'); else { $this->updateDebugBuffer('initial_get',"http://inet.ua/index.php",'GET',false); $this->debugRequest(); $this->stopPlugin(); return false; } $user_array=explode('@',$user);$username=$user_array[0]; $form_action="http://newmail.inet.ua/login.php"; $post_elements=array('username'=>$username,'password'=>$pass,'server_id'=>0,'template'=>'v-webmail','language'=>'ru','login_username'=>$username,'servname'=>'inet.ua','login_password'=>$pass,'version'=>1,'x'=>rand(1,100),'y'=>rand(1,100)); $res=$this->post($form_action,$post_elements,true); if ($this->checkResponse('login_post',$res)) $this->updateDebugBuffer('login_post',$form_action,'POST',true,$post_elements); else { $this->updateDebugBuffer('login_post',$form_action,'POST',false,$post_elements); $this->debugRequest(); $this->stopPlugin(); return false; } $this->login_ok="http://newmail.inet.ua/download.php?act=process_export&method=csv&addresses=all"; return true; } /** * Get the current user's contacts * * Makes all the necesarry requests to import * the current user's contacts * * @return mixed The array if contacts if importing was successful, FALSE otherwise. */ public function getMyContacts() { if (!$this->login_ok) { $this->debugRequest(); $this->stopPlugin(); return false; } else $url=$this->login_ok; $res=$this->get($url); if ($this->checkResponse("url_export",$res)) $this->updateDebugBuffer('url_export',$url,'GET'); else { $this->updateDebugBuffer('url_export',$url,'GET',false); $this->debugRequest(); $this->stopPlugin(); return false; } $tempFile=explode(PHP_EOL,$res);$contacts=array();unset($tempFile[0]); foreach ($tempFile as $valuesTemp) { $values=explode('~',$valuesTemp); if (!empty($values[3])) $contacts[$values[3]]=array('first_name'=>(!empty($values[1])?$values[1]:false), 'middle_name'=>(!empty($values[2])?$values[2]:false), 'last_name'=>false, 'nickname'=>false, 'email_1'=>(!empty($values[3])?$values[3]:false), 'email_2'=>(!empty($values[4])?$values[4]:false), 'email_3'=>(!empty($values[5])?$values[5]:false), 'organization'=>false, 'phone_mobile'=>(!empty($values[8])?$values[8]:false), 'phone_home'=>(!empty($values[6])?$values[6]:false), 'pager'=>false, 'address_home'=>false, 'address_city'=>(!empty($values[11])?$values[11]:false), 'address_state'=>(!empty($values[12])?$values[12]:false), 'address_country'=>(!empty($values[14])?$values[14]:false), 'postcode_home'=>(!empty($values[13])?$values[13]:false), 'company_work'=>false, 'address_work'=>false, 'address_work_city'=>false, 'address_work_country'=>false, 'address_work_state'=>false, 'address_work_postcode'=>false, 'fax_work'=>false, 'phone_work'=>(!empty($values[7])?$values[7]:false), 'website'=>false, 'isq_messenger'=>false, 'skype_essenger'=>false, 'yahoo_essenger'=>false, 'msn_messenger'=>false, 'aol_messenger'=>false, 'other_messenger'=>false, ); } foreach ($contacts as $email=>$name) if (!$this->isEmail($email)) unset($contacts[$email]); return $this->returnContacts($contacts); } /** * Terminate session * * Terminates the current user's session, * debugs the request and reset's the internal * debudder. * * @return bool TRUE if the session was terminated successfully, FALSE otherwise. */ public function logout() { if (!$this->checkSession()) return false; $res=$this->get('http://newmail.inet.ua/logout.php?vwebmailsession=',true); $this->debugRequest(); $this->resetDebugger(); $this->stopPlugin(); return true; } } ?>
mbrung/lcOpenInviterPlugin
lib/extern/openInviter/plugins/inet.plg.php
PHP
mit
5,581
package org.workcraft.plugins.circuit; import org.workcraft.annotations.DisplayName; import org.workcraft.annotations.Hotkey; import org.workcraft.annotations.SVGIcon; import org.workcraft.dom.Node; import org.workcraft.dom.visual.BoundingBoxHelper; import org.workcraft.dom.visual.DrawRequest; import org.workcraft.formula.BooleanFormula; import org.workcraft.formula.visitors.FormulaRenderingResult; import org.workcraft.formula.visitors.FormulaToGraphics; import org.workcraft.gui.tools.Decoration; import org.workcraft.observation.PropertyChangedEvent; import org.workcraft.observation.StateEvent; import org.workcraft.observation.StateObserver; import org.workcraft.plugins.circuit.renderers.ComponentRenderingResult.RenderType; import org.workcraft.serialisation.NoAutoSerialisation; import org.workcraft.utils.ColorUtils; import org.workcraft.utils.Hierarchy; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.font.FontRenderContext; import java.awt.geom.*; import java.io.IOException; import java.util.Collection; import java.util.HashSet; @DisplayName("Input/output port") @Hotkey(KeyEvent.VK_P) @SVGIcon("images/circuit-node-port.svg") public class VisualFunctionContact extends VisualContact implements StateObserver { private static final double size = 0.3; private static FontRenderContext context = new FontRenderContext(AffineTransform.getScaleInstance(1000.0, 1000.0), true, true); private static Font functionFont; private FormulaRenderingResult renderedSetFunction = null; private FormulaRenderingResult renderedResetFunction = null; private static double functionFontSize = CircuitSettings.getFunctionFontSize(); static { try { functionFont = Font.createFont(Font.TYPE1_FONT, ClassLoader.getSystemResourceAsStream("fonts/eurm10.pfb")); } catch (FontFormatException | IOException e) { e.printStackTrace(); } } public VisualFunctionContact(FunctionContact contact) { super(contact); } @Override public FunctionContact getReferencedComponent() { return (FunctionContact) super.getReferencedComponent(); } @NoAutoSerialisation public BooleanFormula getSetFunction() { return getReferencedComponent().getSetFunction(); } @NoAutoSerialisation public void setSetFunction(BooleanFormula setFunction) { if (getParent() instanceof VisualFunctionComponent) { VisualFunctionComponent p = (VisualFunctionComponent) getParent(); p.invalidateRenderingResult(); } renderedSetFunction = null; getReferencedComponent().setSetFunction(setFunction); } @NoAutoSerialisation public BooleanFormula getResetFunction() { return getReferencedComponent().getResetFunction(); } @NoAutoSerialisation public void setForcedInit(boolean value) { getReferencedComponent().setForcedInit(value); } @NoAutoSerialisation public boolean getForcedInit() { return getReferencedComponent().getForcedInit(); } @NoAutoSerialisation public void setInitToOne(boolean value) { getReferencedComponent().setInitToOne(value); } @NoAutoSerialisation public boolean getInitToOne() { return getReferencedComponent().getInitToOne(); } @NoAutoSerialisation public void setResetFunction(BooleanFormula resetFunction) { if (getParent() instanceof VisualFunctionComponent) { VisualFunctionComponent p = (VisualFunctionComponent) getParent(); p.invalidateRenderingResult(); } renderedResetFunction = null; getReferencedComponent().setResetFunction(resetFunction); } public void invalidateRenderedFormula() { renderedSetFunction = null; renderedResetFunction = null; } private Font getFunctionFont() { return functionFont.deriveFont((float) CircuitSettings.getFunctionFontSize()); } private FormulaRenderingResult getRenderedSetFunction() { if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) { functionFontSize = CircuitSettings.getContactFontSize(); renderedSetFunction = null; } BooleanFormula setFunction = getReferencedComponent().getSetFunction(); if (setFunction == null) { renderedSetFunction = null; } else if (renderedSetFunction == null) { renderedSetFunction = FormulaToGraphics.render(setFunction, context, getFunctionFont()); } return renderedSetFunction; } private Point2D getSetFormulaOffset() { double xOffset = size; double yOffset = -size / 2; FormulaRenderingResult renderingResult = getRenderedSetFunction(); if (renderingResult != null) { Direction dir = getDirection(); if (!(getParent() instanceof VisualFunctionComponent)) { dir = dir.flip(); } if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) { xOffset = -(size + renderingResult.boundingBox.getWidth()); } } return new Point2D.Double(xOffset, yOffset); } private Rectangle2D getSetBoundingBox() { Rectangle2D bb = null; FormulaRenderingResult setRenderingResult = getRenderedSetFunction(); if (setRenderingResult != null) { bb = BoundingBoxHelper.move(setRenderingResult.boundingBox, getSetFormulaOffset()); Direction dir = getDirection(); if (!(getParent() instanceof VisualFunctionComponent)) { dir = dir.flip(); } if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) { AffineTransform rotateTransform = new AffineTransform(); rotateTransform.quadrantRotate(-1); bb = BoundingBoxHelper.transform(bb, rotateTransform); } } return bb; } private FormulaRenderingResult getRenderedResetFunction() { if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) { functionFontSize = CircuitSettings.getContactFontSize(); renderedResetFunction = null; } BooleanFormula resetFunction = getReferencedComponent().getResetFunction(); if (resetFunction == null) { renderedResetFunction = null; } else if (renderedResetFunction == null) { renderedResetFunction = FormulaToGraphics.render(resetFunction, context, getFunctionFont()); } return renderedResetFunction; } private Point2D getResetFormulaOffset() { double xOffset = size; double yOffset = size / 2; FormulaRenderingResult renderingResult = getRenderedResetFunction(); if (renderingResult != null) { Direction dir = getDirection(); if (!(getParent() instanceof VisualFunctionComponent)) { dir = dir.flip(); } if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) { xOffset = -(size + renderingResult.boundingBox.getWidth()); } yOffset = size / 2 + renderingResult.boundingBox.getHeight(); } return new Point2D.Double(xOffset, yOffset); } private Rectangle2D getResetBoundingBox() { Rectangle2D bb = null; FormulaRenderingResult renderingResult = getRenderedResetFunction(); if (renderingResult != null) { bb = BoundingBoxHelper.move(renderingResult.boundingBox, getResetFormulaOffset()); Direction dir = getDirection(); if (!(getParent() instanceof VisualFunctionComponent)) { dir = dir.flip(); } if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) { AffineTransform rotateTransform = new AffineTransform(); rotateTransform.quadrantRotate(-1); bb = BoundingBoxHelper.transform(bb, rotateTransform); } } return bb; } private void drawArrow(Graphics2D g, int arrowType, double arrX, double arrY) { double s = CircuitSettings.getFunctionFontSize(); g.setStroke(new BasicStroke((float) s / 25)); double s1 = 0.75 * s; double s2 = 0.45 * s; double s3 = 0.30 * s; if (arrowType == 1) { // arrow down Line2D line = new Line2D.Double(arrX, arrY - s1, arrX, arrY - s3); Path2D path = new Path2D.Double(); path.moveTo(arrX - 0.05, arrY - s3); path.lineTo(arrX + 0.05, arrY - s3); path.lineTo(arrX, arrY); path.closePath(); g.fill(path); g.draw(line); } else if (arrowType == 2) { // arrow up Line2D line = new Line2D.Double(arrX, arrY, arrX, arrY - s2); Path2D path = new Path2D.Double(); path.moveTo(arrX - 0.05, arrY - s2); path.lineTo(arrX + 0.05, arrY - s2); path.lineTo(arrX, arrY - s1); path.closePath(); g.fill(path); g.draw(line); } } private void drawFormula(Graphics2D g, int arrowType, Point2D offset, FormulaRenderingResult renderingResult) { if (renderingResult != null) { Direction dir = getDirection(); if (!(getParent() instanceof VisualFunctionComponent)) { dir = dir.flip(); } AffineTransform savedTransform = g.getTransform(); if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) { AffineTransform rotateTransform = new AffineTransform(); rotateTransform.quadrantRotate(-1); g.transform(rotateTransform); } double dXArrow = -0.15; if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) { dXArrow = renderingResult.boundingBox.getWidth() + 0.15; } drawArrow(g, arrowType, offset.getX() + dXArrow, offset.getY()); g.translate(offset.getX(), offset.getY()); renderingResult.draw(g); g.setTransform(savedTransform); } } @Override public void draw(DrawRequest r) { if (needsFormulas()) { Graphics2D g = r.getGraphics(); Decoration d = r.getDecoration(); g.setColor(ColorUtils.colorise(getForegroundColor(), d.getColorisation())); FormulaRenderingResult renderingResult; renderingResult = getRenderedSetFunction(); if (renderingResult != null) { Point2D offset = getSetFormulaOffset(); drawFormula(g, 2, offset, renderingResult); } renderingResult = getRenderedResetFunction(); if (renderingResult != null) { Point2D offset = getResetFormulaOffset(); drawFormula(g, 1, offset, renderingResult); } } super.draw(r); } private boolean needsFormulas() { boolean result = false; Node parent = getParent(); if (parent != null) { // Primary input port if (!(parent instanceof VisualCircuitComponent) && isInput()) { result = true; } // Output port of a BOX-rendered component if ((parent instanceof VisualFunctionComponent) && isOutput()) { VisualFunctionComponent component = (VisualFunctionComponent) parent; if (component.getRenderType() == RenderType.BOX) { result = true; } } } return result; } @Override public Rectangle2D getBoundingBoxInLocalSpace() { Rectangle2D bb = super.getBoundingBoxInLocalSpace(); if (needsFormulas()) { bb = BoundingBoxHelper.union(bb, getSetBoundingBox()); bb = BoundingBoxHelper.union(bb, getResetBoundingBox()); } return bb; } private Collection<VisualFunctionContact> getAllContacts() { HashSet<VisualFunctionContact> result = new HashSet<>(); Node root = Hierarchy.getRoot(this); if (root != null) { result.addAll(Hierarchy.getDescendantsOfType(root, VisualFunctionContact.class)); } return result; } @Override public void notify(StateEvent e) { if (e instanceof PropertyChangedEvent) { PropertyChangedEvent pc = (PropertyChangedEvent) e; String propertyName = pc.getPropertyName(); if (propertyName.equals(FunctionContact.PROPERTY_SET_FUNCTION) || propertyName.equals(FunctionContact.PROPERTY_RESET_FUNCTION)) { invalidateRenderedFormula(); } if (propertyName.equals(Contact.PROPERTY_NAME)) { for (VisualFunctionContact vc : getAllContacts()) { vc.invalidateRenderedFormula(); } } } super.notify(e); } }
tuura/workcraft
workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualFunctionContact.java
Java
mit
13,140
/*++ Copyright (c) 2011 Microsoft Corporation Module Name: smt_arith.h Abstract: Arithmetic solver for smt::solver Author: Leonardo de Moura (leonardo) 2011-06-25. Revision History: --*/ #ifndef _SMT_ARITH_H_ #define _SMT_ARITH_H_ #include"ast.h" #include"smt_solver_types.h" #include"params.h" #include"statistics.h" class model; namespace smt { class arith { struct imp; imp * m_imp; params_ref m_params; public: arith(ast_manager & m, params_ref const & p); ~arith(); void updt_params(params_ref const & p); void assert_axiom(expr * t, bool neg); void mk_atom(expr * t, atom_id id); void asserted(atom_id id, bool is_true); bool inconsistent() const; void push(); void pop(unsigned num_scopes); void set_cancel(bool f); void simplify(); void display(std::ostream & out) const; void reset(); void preprocess(); void collect_statistics(statistics & st) const; void reset_statistics(); lbool check(); void mk_model(model * md); }; }; #endif
sukwon0709/byterun
byterun/z3str2/z3/lib/smt_arith.h
C
mit
1,158
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True
levilucio/SyVOLT
ExFamToPerson/contracts/unit/HUnitDaughter2Woman_ConnectedLHS.py
Python
mit
2,107
--- layout: post title: iOS Localization date: 2014-10-25 categories: iOS --- This post contains some of my thoughts and experiences from localizing iOS applications. ##Format specifiers After many mistakes when localizing and having to change stuff later I've arrived at the conclusion that you should use the string format specifier (`%@`) for *everything*. The following example should give you an idea of why. {% highlight objc %} NSString *format = NSLocalizedString(@"I have %d red candies.", nil); NSString *result = [NSString stringWithFormat:format, 5]; // "I have 5 red candies". {% endhighlight %} There are two problems with using integer format (`%d`) here: 1. Sooner or later we might want to put something other than an integer in there, like spelling out "five" or using a fractional number like 5.5. 2. Some languages don't use decimal integers like we do. A language could theoretically use base 4, or use [different characters](http://en.wikipedia.org/wiki/Eastern_Arabic_numerals) for numbers. I'll explain how to deal with the number formatting in a second. Had we used `%@` instead of `%d`, both of the above problems could be solved without ordering new, specific translations. ##Combining strings Combining different localized strings is something I've seen happen every now and then. For instance, if we already have localizations for the strings `@"Eat"` and `@"Candy"`, it could be very tempting to do something like this to reduce translation costs: {% highlight objc %} NSString *eat = NSLocalizedString(@"Eat", nil); NSString *candy = NSLocalizedString(@"Candy", nil); NSString *consumeButtonText = [NSString stringWithFormat:@"%@ %@", eat, candy]; // "Eat Candy" {% endhighlight %} The problem is that in some languages, the order of words will be inverted. It only gets worse if we combine several words or sentences. I recommend that you spend some more resources on adding all the possible sentences to your localization files, and the translations will be more correct. ##Formatting numbers Each and every number presented in the UI should be formatted. This guarantees that the application displays numbers correctly even if different locales use different characters or number systems. {% highlight objc %} NSNumberFormatter *formatter = [NSNumberFormatter new]; formatter.numberStyle = NSNumberFormatterDecimalStyle; NSInteger aNumber = 74679; NSString *formattedNumber = [formatter stringFromNumber:@(aNumber)]; {% endhighlight %} `formattedNumber` will differ depending on the current locale: {% highlight objc %} // en "74,679" // sv "74 679" // ar "٧٤٬٦٧٩" {% endhighlight %} Since `NSNumberFormatter` is heavy to initialize, I usually keep a few static formatters in a utility class configured for different format styles. Formatting numbers also have other benefits, for example, not having to write code to round floats or display percentages. If you give a formatter with `NSNumberFormatterPercentageStyle` a float like `0.53467`, it will nicely output `53%`for you. (Or whatever a percentage number should look like in the current locale). `NSNumberFormatter` really is an amazing class, and I recommend everyone to at least skim through its documentation. ##Autolayout Autolayout is a great tool to aid us in our quests for perfect localizations. Different languages use different amount of characters to express the same things, and having UI elements automatically make room for text is a real time saver. It's especially helpful for supporting right-to-left (RTL) languages. Every view that layouts using leading or trailing attributes will be properly laid out together with labels containing right-to-left text. Most of the time, Autolayout takes care of everything we need for supporting RTL languages. But when something comes up that needs to be done manually (or if we don't use Autolayout at all), we can always branch code like this: {% highlight objc %} UIUserInterfaceLayoutDirection layoutDirection = [UIApplication sharedApplication].userInterfaceLayoutDirection; if (layoutDirection == UIUserInterfaceLayoutDirectionRightToLeft) { // Code to handle RTL language } {% endhighlight %}
accatyyc/accatyyc.github.io
_posts/2014-10-25-ios-localization.md
Markdown
mit
4,201
Crawler demo project ==================== A little(-ish) thingy to show off what I can do (when overengineering things at midnight). This was made with a tight deadline, relative to the level I built it at, so I punted a lot of things. Usage: ------ - with docker: 1. run ./build.sh (or cat it and run each command individually) 2. run `docker run -ti -P --rm --name central lahwran/crawler-coord`. the important parts there are `--name central` and `lahwran/crawler-coord`; you can background it if you're into such things. (I'm not.) Note that it's a huge pain to talk to docker instances from your mac if using boot2docker, which is why `lahwran/crawler-curl` exists. 3. run as many of `docker run -ti --rm --link central:coord lahwran/crawler-drone` as you want drones. the important parts there are `--link central:coord` - don't change `coord` - and `lahwran/crawler-drone`. the coordination node will dictate parallelism per drone, and defaults to two requests in flight at once on each drone. (add --help to your invocation of either -coord or -drone to get more information.) 4. if necessary, run something like `docker run -ti --rm --link central:coord lahwran/crawler-curl curl -X POST --data-binary @- http://coord:8080/`. this will allow you to control the central api even if your mac vm won't map it correctly. 5. yay, images! - without docker is also possible, install requirements.txt with pip and then look at `python -m crawler.main --help`. Known issues ------------ - Sometimes you get a TLS error from the drone. I decided it wasn't worth the time for a demo project to figure out why, especially considering how much I overdid the rest of it and how much time that took. - I was originally going to try to do unicode support, but I slipped up in at least one place, and it started looking like it'd take too much time to fix that, so I just tore out all the b markers and the unicode_literal future import and left it python 2 style. API --- ###### `POST /` send a newline-separated list of urls, not specially encoded (sorry, these seed urls can't have newlines). Returns a json-encoded job id. ###### `GET /status/<job-id>` returns some json information about the job. looks like: { "result_count": 131, "crawled_urls": { "finished": 169, "in_progress": 7, "waiting_in_queue": 0} } } ###### `GET /status/all` Return statuses for all running jobs. `{job id: job status as above}`. ###### `GET /results/<job-id>` Return a json list of image urls that have been discovered by this job. Notes ----- The goal here was to create a crawler to find images, that can parallelize by running multiple instances of it in docker. Here are some thoughts I had along the way: - Images or urls from image tags or image-like urls: I considered three different ways to determine if a url was an image; I ended up deciding on the simplest and most error prone, matching a regex against the url's path, but I also thought about calling HEAD on each url and checking the mimetype. As that would be effectively another level deep of spidering, I decided against it. I also considered filtering based on what urls were found in image tags, but many urls that are images are also found in links, so I decided against that as well, as it would leave some out. I considered a hybrid that had different levels of confidence, but that seemed like overcomplication for a demo project. - Cerealization: I considered Cap'n proto initially, but I hadn't actually used that before, so I decided to stick with what I had done before. However, I was a bit embarrassed about my habit of using json-on-a-line protocols, so I tried to just do line-command based; that didn't work out too well, as it turned out that urls have newlines in them in the wild! So I added json back in to escape the urls in transit. - Architecture: I initially wanted to use an entirely peer to peer queue system, but such a thing would be Very Hard(tm) to make, and since I didn't find it anywhere already in existence, I decided to skip it. ZeroMQ seemed to come pretty close, but it wasn't quite a task queue, as far as I could tell. However, I did get someone on irc thinking I was crazy for even asking, so maybe that's an indication I misunderstood so badly that they didn't even bother to explain. - Code reuse: I wrote this entirely in twisted, and as such decided to use a fair number of little chunks of code I'd written to make the way I do things in twisted a bit nicer. I marked them sufficiently to be clear they were not written for this project; it still holds up as a demo project done in a short period of time. - Use of docker: I'm still not sure I got it quite right in terms of using docker idiomatically, but I think I got pretty close, if I didn't nail it. This was my first time using docker in anything, and it was fairly confusing to rush through at high velocity - what would normally have been minor bumps were compressed together into a small timespan, and felt much bigger. - Use of external systems: Because docker was used for this, I could have used pre-prepared external services (say, postgres, redis, mongodb, blah blah). I am not generally a fan of small projects using big databases like that, because in my experience they typically take a good deal of spinup time. In the spirit of "use boring technology", I try to use what I know, rather than jumping into new things just-because, which is a thing to do when not in "get it done now" mode. (yay personal projects!) I also didn't want to add overhead for communication, and since I didn't have a good handle on the performance characteristics of the databases I'd used less and definitely did not want to use the one database I do understand reasonably well (postgres), I chose to write my own protocol that I was fully in control of. - Saving: because I didn't use an existing database, saving didn't come for free. I decided to not include any automatic saving of the results, leaving it as a crawling system that is focused on its responsibilities and lets some other client save the results when it's ready to do so. - Performance: While I designed this using habits I have to increase performance in the little things - multiple requests in flight at once, an http library that supports connection pooling, keeping live connections between the drones and central, etc - there are probably large-scale ways that it could be much faster. For instance, it won't run in pypy, because used LXML. Or similarly, I suspect I could probably optimize the xpath that I'm using - I'm not familiar with the xpath execution thingy, but it seems reasonable to worry that it might be O(n*m), where n is the number of nodes and m is the number of tags I'm searching for. - Robots.txt parsing: I considered doing robots.txt parsing and filtering urls by it, but ended up deciding that figuring out how to provide the funky parameters that the recent robots parsing library wanted would be too much effort for the time I had. It'd be a cool next feature, though. The library I looked at was https://github.com/seomoz/reppy.
lahwran/distributed-crawler
readme.md
Markdown
mit
7,512
module Lib where import Data.Function (on) import Data.List (findIndices, minimumBy, transpose) import Data.Maybe (isJust, isNothing) data Shape = Nought | Cross deriving (Read, Show, Eq) type Cell = Maybe Shape type Board = [Cell] boardSize = 3 emptyBoard = replicate (boardSize * boardSize) Nothing makeBoard :: String -> Board makeBoard = map charToCell . take (boardSize * boardSize) where charToCell 'o' = Just Nought charToCell 'x' = Just Cross charToCell _ = Nothing nextMove :: Board -> Shape -> Board nextMove brd shp = minimumBy (compare `on` opponentScore) (nextBoards brd shp) where opponentScore brd' = scoreFor brd' (opponent shp) isWinFor :: Board -> Shape -> Bool isWinFor brd shp = any winningSlice allSlices where winningSlice = all (== Just shp) allSlices = rows brd ++ cols brd ++ diagonals brd isLossFor :: Board -> Shape -> Bool isLossFor brd shp = isWinFor brd (opponent shp) isDraw :: Board -> Bool isDraw brd = isFull brd && noWin Nought && noWin Cross where noWin = not . isWinFor brd isFull :: Board -> Bool isFull = all isJust nextBoards :: Board -> Shape -> [Board] nextBoards brd shp = map makeMove emptyIdxs where makeMove n = fillCell brd n (Just shp) emptyIdxs = findIndices isNothing brd fillCell :: Board -> Int -> Cell -> Board fillCell brd n cell | n >= (boardSize * boardSize) = brd | otherwise = before ++ [cell] ++ (drop 1 after) where (before, after) = splitAt n brd scoreFor :: Board -> Shape -> Int scoreFor brd shp | isWinFor brd shp = 1 | isLossFor brd shp = -1 | isDraw brd = 0 | otherwise = -(minimum $ map opponentScore (nextBoards brd shp)) where opponentScore brd' = scoreFor brd' (opponent shp) rows :: Board -> [[Cell]] rows brd = map row [0..boardSize-1] where row n = take boardSize . drop (n * boardSize) $ brd cols :: Board -> [[Cell]] cols = transpose . rows diagonals :: Board -> [[Cell]] diagonals brd = map extract [topLeft, topRight] where extract = map (brd !!) topLeft = map (\n -> n * (boardSize + 1)) [0..boardSize-1] topRight = map (\n -> (n + 1) * (boardSize - 1)) [0..boardSize-1] opponent :: Shape -> Shape opponent Nought = Cross opponent Cross = Nought
leocassarani/noughts-and-crosses
src/Lib.hs
Haskell
mit
2,262
<?php /* TwigBundle:Exception:traces.html.twig */ class __TwigTemplate_9109da3b5a8f9508fb31e1e2c4868542dc8f79b94134ac992407a779404545e3 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<div class=\"block\"> "; // line 2 if (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) > 0)) { // line 3 echo " <h2> <span><small>["; // line 4 echo twig_escape_filter($this->env, (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) - (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position"))) + 1), "html", null, true); echo "/"; echo twig_escape_filter($this->env, ((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) + 1), "html", null, true); echo "]</small></span> "; // line 5 echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class", array())); echo ": "; echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message", array()), "html", null, true))); echo "&nbsp; "; // line 6 ob_start(); // line 7 echo " <a href=\"#\" onclick=\"toggle('traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "', 'traces'); switchIcons('icon-traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-open', 'icon-traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-close'); return false;\"> <img class=\"toggle\" id=\"icon-traces-"; // line 8 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("inline") : ("none")); echo "\" /> <img class=\"toggle\" id=\"icon-traces-"; // line 9 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("none") : ("inline")); echo "\" /> </a> "; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); // line 12 echo " </h2> "; } else { // line 14 echo " <h2>Stack Trace</h2> "; } // line 16 echo " <a id=\"traces-link-"; // line 17 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "\"></a> <ol class=\"traces list-exception\" id=\"traces-"; // line 18 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("block") : ("none")); echo "\"> "; // line 19 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array())); foreach ($context['_seq'] as $context["i"] => $context["trace"]) { // line 20 echo " <li> "; // line 21 $this->loadTemplate("TwigBundle:Exception:trace.html.twig", "TwigBundle:Exception:traces.html.twig", 21)->display(array("prefix" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "i" => $context["i"], "trace" => $context["trace"])); // line 22 echo " </li> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 24 echo " </ol> </div> "; } public function getTemplateName() { return "TwigBundle:Exception:traces.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 101 => 24, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 39 => 6, 33 => 5, 27 => 4, 24 => 3, 22 => 2, 19 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("<div class=\"block\"> {% if count > 0 %} <h2> <span><small>[{{ count - position + 1 }}/{{ count + 1 }}]</small></span> {{ exception.class|abbr_class }}: {{ exception.message|nl2br|format_file_from_text }}&nbsp; {% spaceless %} <a href=\"#\" onclick=\"toggle('traces-{{ position }}', 'traces'); switchIcons('icon-traces-{{ position }}-open', 'icon-traces-{{ position }}-close'); return false;\"> <img class=\"toggle\" id=\"icon-traces-{{ position }}-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: {{ 0 == count ? 'inline' : 'none' }}\" /> <img class=\"toggle\" id=\"icon-traces-{{ position }}-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: {{ 0 == count ? 'none' : 'inline' }}\" /> </a> {% endspaceless %} </h2> {% else %} <h2>Stack Trace</h2> {% endif %} <a id=\"traces-link-{{ position }}\"></a> <ol class=\"traces list-exception\" id=\"traces-{{ position }}\" style=\"display: {{ 0 == count ? 'block' : 'none' }}\"> {% for i, trace in exception.trace %} <li> {% include 'TwigBundle:Exception:trace.html.twig' with { 'prefix': position, 'i': i, 'trace': trace } only %} </li> {% endfor %} </ol> </div> ", "TwigBundle:Exception:traces.html.twig", "C:\\inetpub\\wwwroot\\Cupon1\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle/Resources/views/Exception/traces.html.twig"); } }
cristian3040/Cupon
app/cache/dev/twig/89/89ed4a643ac881b9b276624f1e201f6f6459e825e3dad4b2ed9447cc114d4ee5.php
PHP
mit
9,187
Polaris::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_assets = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found). config.i18n.fallbacks = true # Mailer settings config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'smtp.gmail.com', port: 587, domain: 'mail.google.com', authentication: 'plain', enable_starttls_auto: true, user_name: 'contato@codepolaris.com', password: 'CodePolaris' } # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new end
marcosserpa/codepolaris
config/environments/production.rb
Ruby
mit
3,572
var models=require('../models/models.js'); // Autoload :id de comentarios exports.load=function (req,res,next,commentId) { models.Comment.find({ where:{ id:Number(commentId) } }).then(function (comment) { if(comment){ req.comment=comment; next(); }else{ next(new Error('No existe commentId=' +commentId)) } }).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/new exports.new=function (req,res) { res.render('comments/new.ejs',{quizid:req.params.quizId, errors:[]}); }; //POST /quizes/:quizId/comments exports.create=function (req,res) { var comment =models.Comment.build( { texto:req.body.comment.texto, QuizId:req.params.quizId, }); comment .validate() .then( function (err) { if(err){ res.render('comments/new.ejs', {comment:comment,quizid:req.params.quizId,errors:err.errors}); }else{ comment //save :guarda en DB campo texto .save() .then(function () { res.redirect('/quizes/'+req.params.quizId); }); } } ).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/:commentId/publish exports.publish=function (req,res) { req.comment.publicado=true; req.comment.save({fields:["publicado"]}).then( function () { res.redirect('/quizes/'+req.params.quizId); }).catch(function (error) { next(error); }); };
armero1989/quiz-2016
controllers/comment_controller.js
JavaScript
mit
1,348
package net.dirtyfilthy.bouncycastle.asn1.nist; import net.dirtyfilthy.bouncycastle.asn1.DERObjectIdentifier; import net.dirtyfilthy.bouncycastle.asn1.sec.SECNamedCurves; import net.dirtyfilthy.bouncycastle.asn1.sec.SECObjectIdentifiers; import net.dirtyfilthy.bouncycastle.asn1.x9.X9ECParameters; import net.dirtyfilthy.bouncycastle.util.Strings; import java.util.Enumeration; import java.util.Hashtable; /** * Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2 */ public class NISTNamedCurves { static final Hashtable objIds = new Hashtable(); static final Hashtable names = new Hashtable(); static void defineCurve(String name, DERObjectIdentifier oid) { objIds.put(name, oid); names.put(oid, name); } static { // TODO Missing the "K-" curves defineCurve("B-571", SECObjectIdentifiers.sect571r1); defineCurve("B-409", SECObjectIdentifiers.sect409r1); defineCurve("B-283", SECObjectIdentifiers.sect283r1); defineCurve("B-233", SECObjectIdentifiers.sect233r1); defineCurve("B-163", SECObjectIdentifiers.sect163r2); defineCurve("P-521", SECObjectIdentifiers.secp521r1); defineCurve("P-384", SECObjectIdentifiers.secp384r1); defineCurve("P-256", SECObjectIdentifiers.secp256r1); defineCurve("P-224", SECObjectIdentifiers.secp224r1); defineCurve("P-192", SECObjectIdentifiers.secp192r1); } public static X9ECParameters getByName( String name) { DERObjectIdentifier oid = (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name)); if (oid != null) { return getByOID(oid); } return null; } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters getByOID( DERObjectIdentifier oid) { return SECNamedCurves.getByOID(oid); } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DERObjectIdentifier getOID( String name) { return (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name)); } /** * return the named curve name represented by the given object identifier. */ public static String getName( DERObjectIdentifier oid) { return (String)names.get(oid); } /** * returns an enumeration containing the name strings for curves * contained in this structure. */ public static Enumeration getNames() { return objIds.keys(); } }
dirtyfilthy/dirtyfilthy-bouncycastle
net/dirtyfilthy/bouncycastle/asn1/nist/NISTNamedCurves.java
Java
mit
2,937
<?php // Include the API require '../../lastfmapi/lastfmapi.php'; // Get the session auth data $file = fopen('../auth.txt', 'r'); // Put the auth data into an array $authVars = array( 'apiKey' => trim(fgets($file)), 'secret' => trim(fgets($file)), 'username' => trim(fgets($file)), 'sessionKey' => trim(fgets($file)), 'subscriber' => trim(fgets($file)) ); $config = array( 'enabled' => true, 'path' => '../../lastfmapi/', 'cache_length' => 1800 ); // Pass the array to the auth class to eturn a valid auth $auth = new lastfmApiAuth('setsession', $authVars); $apiClass = new lastfmApi(); $tagClass = $apiClass->getPackage($auth, 'tag', $config); // Setup the variables $methodVars = array( 'tag' => 'Emo' ); if ( $albums = $tagClass->getTopAlbums($methodVars) ) { echo '<b>Data Returned</b>'; echo '<pre>'; print_r($albums); echo '</pre>'; } else { die('<b>Error '.$tagClass->error['code'].' - </b><i>'.$tagClass->error['desc'].'</i>'); } ?>
SimonTalaga/MusicalTastesViz
vendor/lastfm/examples/tag.gettopalbums/index.php
PHP
mit
960
BuildTearDown { throw "forced error" } Task default -depends Compile,Test,Deploy Task Compile { "Compiling;" } Task Test -depends Compile { "Testing;" } Task Deploy -depends Test { "Deploying;" }
psake/psake
specs/buildteardown_failure_should_fail.ps1
PowerShell
mit
216
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <link href='https://fonts.googleapis.com/css?family=Chivo:900' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen"> <link rel="stylesheet" type="text/css" href="stylesheets/pygment_trac.css" media="screen"> <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print"> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <title>Davidstrada.GitHub.io by DavidStrada</title> </head> <body> <div id="container"> <div class="inner"> <header> <h1>Davidstrada.GitHub.io</h1> <h2></h2> </header> <section id="downloads" class="clearfix"> <a href="https://github.com/DavidStrada" id="view-on-github" class="button"><span>View on GitHub</span></a> </section> <hr> <section id="main_content"> <h3> <a id="welcome-to-github-pages" class="anchor" href="#welcome-to-github-pages" aria-hidden="true"><span class="octicon octicon-link"></span></a>Welcome to GitHub Pages.</h3> <p>This automatic page generator is the easiest way to create beautiful pages for all of your projects. Author your page content here using GitHub Flavored Markdown, select a template crafted by a designer, and publish. After your page is generated, you can check out the new branch:</p> <pre><code>$ cd your_repo_root/repo_name $ git fetch origin $ git checkout gh-pages </code></pre> <p>If you're using the GitHub for Mac, simply sync your repository and you'll see the new branch.</p> <h3> <a id="designer-templates" class="anchor" href="#designer-templates" aria-hidden="true"><span class="octicon octicon-link"></span></a>Designer Templates</h3> <p>We've crafted some handsome templates for you to use. Go ahead and continue to layouts to browse through them. You can easily go back to edit your page before publishing. After publishing your page, you can revisit the page generator and switch to another theme. Your Page content will be preserved if it remained markdown format.</p> <h3> <a id="rather-drive-stick" class="anchor" href="#rather-drive-stick" aria-hidden="true"><span class="octicon octicon-link"></span></a>Rather Drive Stick?</h3> <p>If you prefer to not use the automatic generator, push a branch named <code>gh-pages</code> to your repository to create a page manually. In addition to supporting regular HTML content, GitHub Pages support Jekyll, a simple, blog aware static site generator written by our own Tom Preston-Werner. Jekyll makes it easy to create site-wide headers and footers without having to copy them across every page. It also offers intelligent blog support and other advanced templating features.</p> <h3> <a id="authors-and-contributors" class="anchor" href="#authors-and-contributors" aria-hidden="true"><span class="octicon octicon-link"></span></a>Authors and Contributors</h3> <p>You can <a href="https://github.com/blog/821" class="user-mention">@mention</a> a GitHub username to generate a link to their profile. The resulting <code>&lt;a&gt;</code> element will link to the contributor's GitHub Profile. For example: In 2007, Chris Wanstrath (<a href="https://github.com/defunkt" class="user-mention">@defunkt</a>), PJ Hyett (<a href="https://github.com/pjhyett" class="user-mention">@pjhyett</a>), and Tom Preston-Werner (<a href="https://github.com/mojombo" class="user-mention">@mojombo</a>) founded GitHub.</p> <h3> <a id="support-or-contact" class="anchor" href="#support-or-contact" aria-hidden="true"><span class="octicon octicon-link"></span></a>Support or Contact</h3> <p>Having trouble with Pages? Check out the documentation at <a href="https://help.github.com/pages">https://help.github.com/pages</a> or contact <a href="mailto:support@github.com">support@github.com</a> and we’ll help you sort it out.</p> </section> <footer> This page was generated by <a href="http://pages.github.com">GitHub Pages</a>. Tactile theme by <a href="https://twitter.com/jasonlong">Jason Long</a>. </footer> </div> </div> </body> </html>
DavidStrada/davidstrada.github.io
index.html
HTML
mit
4,311
package com.cosmos.kafka.client.producer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import java.util.Properties; import java.util.Random; import static org.apache.kafka.clients.producer.ProducerConfig.*; /** * Producer using multiple partition */ public class MultipleBrokerProducer implements Runnable { private KafkaProducer<Integer, String> producer; private String topic; public MultipleBrokerProducer(String topic) { final Properties props = new Properties(); props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093,localhost:9094"); props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerSerializer"); props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(PARTITIONER_CLASS_CONFIG, "org.apache.kafka.clients.producer.internals.DefaultPartitioner"); props.put(ACKS_CONFIG, "1"); this.producer = new KafkaProducer<>(props); this.topic = topic; } @Override public void run() { System.out.println("Sending 1000 messages"); Random rnd = new Random(); int i = 1; while (i <= 1000) { int key = rnd.nextInt(255); String message = String.format("Message for key - [%d]: %d", key, i); System.out.printf("Send: %s\n", message); this.producer.send(new ProducerRecord<>(this.topic, key, message)); i++; try { Thread.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } producer.close(); } }
dantin/kafka-demo
kafka-producer/src/main/java/com/cosmos/kafka/client/producer/MultipleBrokerProducer.java
Java
mit
1,747
// // FAQViewController.h // AKG // // Created by Fabian Ehlert on 01.02.14. // Copyright (c) 2014 Fabian Ehlert. All rights reserved. // #import <UIKit/UIKit.h> @interface FAQViewController : UIViewController @end
fabianehlert/AKG-Bensheim-iOS
AKG/FAQViewController.h
C
mit
222
#David Hickox #Feb 15 17 #Squares (counter update) #descriptions, description, much descripticve #variables # limit, where it stops # num, sentry variable #creates array if needbe #array = [[0 for x in range(h)] for y in range(w)] #imports date time and curency handeling because i hate string formating (this takes the place of #$%.2f"%) import locale locale.setlocale( locale.LC_ALL, '' ) #use locale.currency() for currency formating print("Welcome to the (insert name here bumbblefack) Program\n") limit = float(input("How many squares do you want? ")) num = 1 print("number\tnumber^2") while num <= limit: #prints the number and squares it then seperates by a tab print (num,num**2,sep='\t') #increments num += 1 input("\nPress Enter to Exit")
dwhickox/NCHS-Programming-1-Python-Programs
Chap 3/Squares.py
Python
mit
778
<?php namespace Minsal\GinecologiaBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * SrgTipoConsultaPf * * @ORM\Table(name="srg_tipo_consulta_pf") * @ORM\Entity */ class SrgTipoConsultaPf { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="SEQUENCE") * @ORM\SequenceGenerator(sequenceName="srg_tipo_consulta_pf_id_seq", allocationSize=1, initialValue=1) */ private $id; /** * @var string * * @ORM\Column(name="tipo_consulta_pf", type="string", length=20, nullable=true) */ private $tipoConsultaPf; /** * @ORM\OneToMany(targetEntity="SrgSeguimientoSubsecuente", mappedBy="idTipoConsultaPf", cascade={"all"}, orphanRemoval=true)) **/ private $SrgSeguimientoSubsecuente; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set tipoConsultaPf * * @param string $tipoConsultaPf * @return SrgTipoConsultaPf */ public function setTipoConsultaPf($tipoConsultaPf) { $this->tipoConsultaPf = $tipoConsultaPf; return $this; } /** * Get tipoConsultaPf * * @return string */ public function getTipoConsultaPf() { return $this->tipoConsultaPf; } /** * Constructor */ public function __construct() { $this->SrgSeguimientoSubsecuente = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add SrgSeguimientoSubsecuente * * @param \Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente * @return SrgTipoConsultaPf */ public function addSrgSeguimientoSubsecuente(\Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente) { $this->SrgSeguimientoSubsecuente[] = $srgSeguimientoSubsecuente; return $this; } /** * Remove SrgSeguimientoSubsecuente * * @param \Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente */ public function removeSrgSeguimientoSubsecuente(\Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente) { $this->SrgSeguimientoSubsecuente->removeElement($srgSeguimientoSubsecuente); } /** * Get SrgSeguimientoSubsecuente * * @return \Doctrine\Common\Collections\Collection */ public function getSrgSeguimientoSubsecuente() { return $this->SrgSeguimientoSubsecuente; } public function __toString() { return $this->id? (string) $this->id: ''; } }
sisreg/siap
src/Minsal/GinecologiaBundle/Entity/SrgTipoConsultaPf.php
PHP
mit
2,743
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jprover: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.1 / jprover - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> jprover <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-04 18:52:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-04 18:52:19 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/jprover&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/JProver&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: decision procedure&quot; &quot;keyword: first-order logic&quot; &quot;keyword: intuitionistic logic&quot; &quot;keyword: theorem proving&quot; &quot;keyword: proof search&quot; &quot;category: Miscellaneous/Coq Extensions&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; &quot;date: 2002-04 (contribution since January 2009)&quot; ] authors: [ &quot;Huang Guan-Shieng&quot; ] bug-reports: &quot;https://github.com/coq-contribs/jprover/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/jprover.git&quot; synopsis: &quot;A theorem prover for first-order intuitionistic logic&quot; description: &quot;&quot;&quot; JProver is a theorem prover for first-order intuitionistic logic. It is originally implemented by Stephan Schmitt and then integrated into MetaPRL by Aleksey Nogin. After this, Huang Guan-Shieng extracted the necessary ML-codes from MetaPRL and then adapted it to Coq.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/jprover/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=d7a8888e2da482827e2bc958d6902b89&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-jprover.8.6.0 coq.8.13.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1). The following dependencies couldn&#39;t be met: - coq-jprover -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-jprover.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.07.1-2.0.6/released/8.13.1/jprover/8.6.0.html
HTML
mit
7,364
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>icharate: 41 s</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.9.1 / icharate - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> icharate <small> 8.9.0 <span class="label label-success">41 s</span> </small> </h1> <p><em><script>document.write(moment("2020-08-24 17:47:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-24 17:47:06 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.12 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.9.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/http://www.labri.fr/perso/anoun/Icharate&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Icharate&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: Multimodal Categorial Grammars&quot; &quot;keyword: Syntax/Semantics Interface&quot; &quot;keyword: Higher Order Logic&quot; &quot;keyword: Meta-Linguistics&quot; &quot;category: Computer Science/Formal Languages Theory and Automata&quot; &quot;date: 2003-2006&quot; ] authors: [ &quot;Houda Anoun &lt;anoun@labri.fr&gt;&quot; &quot;Pierre Casteran &lt;casteran@labri.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/icharate/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/icharate.git&quot; synopsis: &quot;Icharate: A logical Toolkit for Multimodal Categorial Grammars&quot; description: &quot;&quot;&quot; The logical toolkit ICHARATE is built upon a formalization of multimodal categorial grammars in Coq proof assistant. This toolkit aims at facilitating the study of these complicated formalisms by allowing users to build interactively the syntactic derivations of different sentences, compute their semantic interpretations and also prove universal properties of entire classes of grammars using a collection of already established derived rules. Several tactics are defined to ease the interaction with users.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/icharate/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=fe48c0335d136d85a028b467f073194b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-icharate.8.9.0 coq.8.9.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-icharate.8.9.0 coq.8.9.1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>5 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-icharate.8.9.0 coq.8.9.1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>41 s</dd> </dl> <h2>Installation size</h2> <p>Total: 5 M</p> <ul> <li>1 M <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_bruijn.vo</code></li> <li>657 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/basics.vo</code></li> <li>257 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/apply_rule_props.vo</code></li> <li>234 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/derivedRulesNatDed.vo</code></li> <li>195 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_ex.vo</code></li> <li>183 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsDed.vo</code></li> <li>126 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/basics.glob</code></li> <li>123 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_reduction.vo</code></li> <li>112 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/apply_rule_props.glob</code></li> <li>108 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_ex.glob</code></li> <li>104 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/derivedRulesNatDed.glob</code></li> <li>91 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_bruijn.glob</code></li> <li>83 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/final_sem.vo</code></li> <li>79 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/listAux.vo</code></li> <li>76 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/permutation.vo</code></li> <li>71 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_coq.vo</code></li> <li>68 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_reduction.glob</code></li> <li>66 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsDed.glob</code></li> <li>60 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/derivSem.vo</code></li> <li>58 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1s.vo</code></li> <li>58 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unaries.vo</code></li> <li>54 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_props.vo</code></li> <li>52 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDed.vo</code></li> <li>51 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/polarity.vo</code></li> <li>50 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/seqNatDed.vo</code></li> <li>50 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/crossDep.vo</code></li> <li>49 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1.vo</code></li> <li>48 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/polEx.vo</code></li> <li>47 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/dep_ex.vo</code></li> <li>46 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/medialEx.vo</code></li> <li>45 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/sequent.vo</code></li> <li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/semLex.vo</code></li> <li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDedGram.vo</code></li> <li>39 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/medialExtraction.vo</code></li> <li>38 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unbounDep.vo</code></li> <li>37 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/struct_tacs.vo</code></li> <li>37 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/basics.v</code></li> <li>33 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/polTac.vo</code></li> <li>33 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/listAux.glob</code></li> <li>32 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/permutation.glob</code></li> <li>30 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/interp_coq.vo</code></li> <li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex3.vo</code></li> <li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/logic_const.vo</code></li> <li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsDed.v</code></li> <li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/notations.vo</code></li> <li>27 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_bruijn.v</code></li> <li>27 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/apply_rule_props.v</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDed.glob</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/derivedRulesNatDed.v</code></li> <li>22 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_reduction.v</code></li> <li>21 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_ex.v</code></li> <li>21 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/polarity.glob</code></li> <li>19 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/sequent.glob</code></li> <li>18 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_props.glob</code></li> <li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_coq.glob</code></li> <li>14 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1s.glob</code></li> <li>14 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unaries.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/crossDep.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/semLex.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/derivSem.glob</code></li> <li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/listAux.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/final_sem.glob</code></li> <li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDedGram.glob</code></li> <li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/permutation.v</code></li> <li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/polEx.glob</code></li> <li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/seqNatDed.glob</code></li> <li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/medialEx.glob</code></li> <li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unbounDep.glob</code></li> <li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/dep_ex.glob</code></li> <li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1.glob</code></li> <li>7 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_coq.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/polarity.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/medialExtraction.glob</code></li> <li>5 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDed.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/interp_coq.glob</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unaries.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/derivSem.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_props.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/struct_tacs.glob</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/crossDep.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/seqNatDed.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/final_sem.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/semLex.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/sequent.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/struct_tacs.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/logic_const.glob</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1s.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDedGram.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unbounDep.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/polTac.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/medialExtraction.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/dep_ex.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/polEx.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/medialEx.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex3.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsSeq.vo</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/notations.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/notations.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/polTac.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/interp_coq.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/logic_const.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsSeq.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex3.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsSeq.glob</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-icharate.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.05.0-2.0.6/released/8.9.1/icharate/8.9.0.html
HTML
mit
20,055
using System; using AppStudio.Uwp; namespace DJNanoShow.ViewModels { public class PrivacyViewModel : ObservableBase { public Uri Url { get { return new Uri(UrlText, UriKind.RelativeOrAbsolute); } } public string UrlText { get { return "http://1drv.ms/1llJOkM"; } } } }
wasteam/DJNanoSampleApp
W10/DJNanoShow.W10/ViewModels/PrivacyViewModel.cs
C#
mit
435
import React, { PropTypes } from 'react'; import TodoItem from './TodoItem'; const TodoList = ({todos}) => ( <ul className="todo-list"> {todos.map(todo => <TodoItem key={todo.id} {...todo} /> )} </ul> ); TodoList.propTypes = { todos: PropTypes.array.isRequired } export default TodoList;
johny/react-redux-todo-app
src/components/TodoList.js
JavaScript
mit
312
<?php namespace Podlove\Settings\Dashboard; use Podlove\Model; class FileValidation { public static function content() { global $wpdb; $sql = ' SELECT p.post_status, mf.episode_id, mf.episode_asset_id, mf.size, mf.id media_file_id FROM `'.Model\MediaFile::table_name().'` mf JOIN `'.Model\Episode::table_name().'` e ON e.id = mf.`episode_id` JOIN `'.$wpdb->posts."` p ON e.`post_id` = p.`ID` WHERE p.`post_type` = 'podcast' AND p.post_status in ('private', 'draft', 'publish', 'pending', 'future') "; $rows = $wpdb->get_results($sql, ARRAY_A); $media_files = []; foreach ($rows as $row) { if (!isset($media_files[$row['episode_id']])) { $media_files[$row['episode_id']] = ['post_status' => $row['post_status']]; } $media_files[$row['episode_id']][$row['episode_asset_id']] = [ 'size' => $row['size'], 'media_file_id' => $row['media_file_id'], ]; } $podcast = Model\Podcast::get(); $episodes = $podcast->episodes(['post_status' => ['private', 'draft', 'publish', 'pending', 'future']]); $assets = Model\EpisodeAsset::all(); $header = [__('Episode', 'podlove-podcasting-plugin-for-wordpress')]; foreach ($assets as $asset) { $header[] = $asset->title; } $header[] = __('Status', 'podlove-podcasting-plugin-for-wordpress'); \Podlove\load_template('settings/dashboard/file_validation', [ 'episodes' => $episodes, 'assets' => $assets, 'media_files' => $media_files, 'header' => $header, ]); } }
podlove/podlove-publisher
lib/settings/dashboard/file_validation.php
PHP
mit
1,726
/* * Copyright (c) 2016. Xiaomu Tech.(Beijing) LLC. All rights reserved. */ package de.mpg.mpdl.labcam.code.common.widget; /** * Created by yingli on 10/19/15. */ public class Constants { public static final String STATUS_SUCCESS = "SUCCESS"; public static final String KEY_CLASS_NAME = "key_class_name"; /************************** SHARED_PREFERENCES **********************************/ public static final String SHARED_PREFERENCES = "myPref"; // name of shared preferences public static final String API_KEY = "apiKey"; public static final String USER_ID = "userId"; public static final String USER_NAME = "username"; public static final String FAMILY_NAME = "familyName"; public static final String GIVEN_NAME = "givenName"; public static final String PASSWORD = "password"; public static final String EMAIL = "email"; public static final String SERVER_NAME = "serverName"; public static final String OTHER_SERVER = "otherServer"; public static final String COLLECTION_ID = "collectionID"; public static final String OCR_IS_ON = "ocrIsOn"; public static final String IS_ALBUM = "isAlbum"; }
MPDL/MPDL-Cam
app/src/main/java/de/mpg/mpdl/labcam/code/common/widget/Constants.java
Java
mit
1,174
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2017 Christian Boulanger License: MIT: https://opensource.org/licenses/MIT See the LICENSE file in the project's top-level directory for details. Authors: * Christian Boulanger (info@bibliograph.org, @cboulanger) ************************************************************************ */ const process = require("process"); const path = require("upath"); const semver = require("semver"); const fs = qx.tool.utils.Promisify.fs; /** * Installs a package */ qx.Class.define("qx.tool.cli.commands.package.Migrate", { extend: qx.tool.cli.commands.Package, statics: { /** * Flag to prevent recursive call to process() */ migrationInProcess: false, /** * Return the Yargs configuration object * @return {{}} */ getYargsCommand: function() { return { command: "migrate", describe: "migrates the package system to a newer version.", builder: { "verbose": { alias: "v", describe: "Verbose logging" }, "quiet": { alias: "q", describe: "No output" } } }; } }, members: { /** * Announces or applies a migration * @param {Boolean} announceOnly If true, announce the migration without * applying it. */ process: async function(announceOnly=false) { const self = qx.tool.cli.commands.package.Migrate; if (self.migrationInProcess) { return; } self.migrationInProcess = true; let needFix = false; // do not call this.base(arguments) here! let pkg = qx.tool.cli.commands.Package; let cwd = process.cwd(); let migrateFiles = [ [ path.join(cwd, pkg.lockfile.filename), path.join(cwd, pkg.lockfile.legacy_filename) ], [ path.join(cwd, pkg.cache_dir), path.join(cwd, pkg.legacy_cache_dir) ], [ path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.package_cache_name), path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.legacy_package_cache_name) ] ]; if (this.checkFilesToRename(migrateFiles).length) { let replaceInFiles = [{ files: path.join(cwd, ".gitignore"), from: pkg.legacy_cache_dir + "/", to: pkg.cache_dir + "/" }]; await this.migrate(migrateFiles, replaceInFiles, announceOnly); if (announceOnly) { needFix = true; } else { if (!this.argv.quiet) { qx.tool.compiler.Console.info("Fixing path names in the lockfile..."); } this.argv.reinstall = true; await (new qx.tool.cli.commands.package.Upgrade(this.argv)).process(); } } // Migrate all manifest in a package const registryModel = qx.tool.config.Registry.getInstance(); let manifestModels =[]; if (await registryModel.exists()) { // we have a qooxdoo.json index file containing the paths of libraries in the repository await registryModel.load(); let libraries = registryModel.getLibraries(); for (let library of libraries) { manifestModels.push((new qx.tool.config.Abstract(qx.tool.config.Manifest.config)).set({baseDir: path.join(cwd, library.path)})); } } else if (fs.existsSync(qx.tool.config.Manifest.config.fileName)) { manifestModels.push(qx.tool.config.Manifest.getInstance()); } for (const manifestModel of manifestModels) { await manifestModel.set({warnOnly: true}).load(); manifestModel.setValidate(false); needFix = false; let s = ""; if (!qx.lang.Type.isArray(manifestModel.getValue("info.authors"))) { needFix = true; s += " missing info.authors\n"; } if (!semver.valid(manifestModel.getValue("info.version"))) { needFix = true; s += " missing or invalid info.version\n"; } let obj = { "info.qooxdoo-versions": null, "info.qooxdoo-range": null, "provides.type": null, "requires.qxcompiler": null, "requires.qooxdoo-sdk": null, "requires.qooxdoo-compiler": null }; if (manifestModel.keyExists(obj)) { needFix = true; s += " obsolete entry:\n"; for (let key in obj) { if (obj[key]) { s += " " + key + "\n"; } } } if (needFix) { if (announceOnly) { qx.tool.compiler.Console.warn("*** Manifest(s) need to be updated:\n" + s); } else { manifestModel .transform("info.authors", authors => { if (authors === "") { return []; } else if (qx.lang.Type.isString(authors)) { return [{name: authors}]; } else if (qx.lang.Type.isObject(authors)) { return [{ name: authors.name, email: authors.email }]; } else if (qx.lang.Type.isArray(authors)) { return authors.map(r => qx.lang.Type.isObject(r) ? { name: r.name, email: r.email } : { name: r } ); } return []; }) .transform("info.version", version => { let coerced = semver.coerce(version); if (coerced === null) { qx.tool.compiler.Console.warn(`*** Version string '${version}' could not be interpreted as semver, changing to 1.0.0`); return "1.0.0"; } return String(coerced); }) .unset("info.qooxdoo-versions") .unset("info.qooxdoo-range") .unset("provides.type") .unset("requires.qxcompiler") .unset("requires.qooxdoo-compiler") .unset("requires.qooxdoo-sdk"); await manifestModel.save(); if (!this.argv.quiet) { qx.tool.compiler.Console.info(`Updated settings in ${manifestModel.getRelativeDataPath()}.`); } } } // check framework and compiler dependencies // if none are given in the Manifest, use the present framework and compiler const compiler_version = qx.tool.compiler.Version.VERSION; const compiler_range = manifestModel.getValue("requires.@qooxdoo/compiler") || compiler_version; const framework_version = await this.getLibraryVersion(await this.getGlobalQxPath()); const framework_range = manifestModel.getValue("requires.@qooxdoo/framework") || framework_version; if ( !semver.satisfies(compiler_version, compiler_range) || !semver.satisfies(framework_version, framework_range)) { needFix = true; if (announceOnly) { qx.tool.compiler.Console.warn(`*** Mismatch between installed framework version (${framework_version}) and/or compiler version (${compiler_version}) and the declared dependencies in the Manifest.`); } else { manifestModel .setValue("requires.@qooxdoo/compiler", "^" + compiler_version) .setValue("requires.@qooxdoo/framework", "^" + framework_version); manifestModel.setWarnOnly(false); // now model should validate await manifestModel.save(); if (!this.argv.quiet) { qx.tool.compiler.Console.info(`Updated dependencies in ${manifestModel.getRelativeDataPath()}.`); } } } manifestModel.setValidate(true); } if (!announceOnly) { let compileJsonFilename = path.join(process.cwd(), "compile.json"); let replaceInFiles = [{ files: compileJsonFilename, from: "\"qx/browser\"", to: "\"@qooxdoo/qx/browser\"" }]; await this.migrate([compileJsonFilename], replaceInFiles); } let compileJsFilename = path.join(process.cwd(), "compile.js"); if (await fs.existsAsync(compileJsFilename)) { let data = await fs.readFileAsync(compileJsFilename, "utf8"); if (data.indexOf("module.exports") < 0) { qx.tool.compiler.Console.warn("*** Your compile.js appears to be missing a `module.exports` statement - please see https://git.io/fjBqU for more details"); } } self.migrationInProcess = false; if (needFix) { if (announceOnly) { qx.tool.compiler.Console.error(`*** Try executing 'qx package migrate' to apply the changes. Alternatively, upgrade or downgrade framework and/or compiler to match the library dependencies.`); process.exit(1); } qx.tool.compiler.Console.info("Migration completed."); } else if (!announceOnly && !this.argv.quiet) { qx.tool.compiler.Console.info("Everything is up-to-date. No migration necessary."); } } } });
johnspackman/qxcompiler
source/class/qx/tool/cli/commands/package/Migrate.js
JavaScript
mit
9,371
/* * FTGL - OpenGL font library * * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __FTCharmap__ #define __FTCharmap__ #include <XMFreeType/ft2build.h> #include FT_FREETYPE_H #include FT_GLYPH_H #include <FTGL/ftgles.h> #include "FTCharToGlyphIndexMap.h" /** * FTCharmap takes care of specifying the encoding for a font and mapping * character codes to glyph indices. * * It doesn't preprocess all indices, only on an as needed basis. This may * seem like a performance penalty but it is quicker than using the 'raw' * freetype calls and will save significant amounts of memory when dealing * with unicode encoding * * @see "Freetype 2 Documentation" * */ class FTFace; class FTCharmap { public: /** * Constructor */ FTCharmap(FTFace* face); /** * Destructor */ virtual ~FTCharmap(); /** * Queries for the current character map code. * * @return The current character map code. */ FT_Encoding Encoding() const { return ftEncoding; } /** * Sets the character map for the face. If an error occurs the object is not modified. * Valid encodings as at Freetype 2.0.4 * ft_encoding_none * ft_encoding_symbol * ft_encoding_unicode * ft_encoding_latin_2 * ft_encoding_sjis * ft_encoding_gb2312 * ft_encoding_big5 * ft_encoding_wansung * ft_encoding_johab * ft_encoding_adobe_standard * ft_encoding_adobe_expert * ft_encoding_adobe_custom * ft_encoding_apple_roman * * @param encoding the Freetype encoding symbol. See above. * @return <code>true</code> if charmap was valid and set * correctly. */ bool CharMap(FT_Encoding encoding); /** * Get the FTGlyphContainer index of the input character. * * @param characterCode The character code of the requested glyph in * the current encoding eg apple roman. * @return The FTGlyphContainer index for the character or zero * if it wasn't found */ unsigned int GlyphListIndex(const unsigned int characterCode); /** * Get the font glyph index of the input character. * * @param characterCode The character code of the requested glyph in * the current encoding eg apple roman. * @return The glyph index for the character. */ unsigned int FontIndex(const unsigned int characterCode); /** * Set the FTGlyphContainer index of the character code. * * @param characterCode The character code of the requested glyph in * the current encoding eg apple roman. * @param containerIndex The index into the FTGlyphContainer of the * character code. */ void InsertIndex(const unsigned int characterCode, const size_t containerIndex); /** * Queries for errors. * * @return The current error code. Zero means no error. */ FT_Error Error() const { return err; } private: /** * Current character map code. */ FT_Encoding ftEncoding; /** * The current Freetype face. */ const FT_Face ftFace; /** * A structure that maps glyph indices to character codes * * < character code, face glyph index> */ typedef FTCharToGlyphIndexMap CharacterMap; CharacterMap charMap; /** * Precomputed font indices. */ static const unsigned int MAX_PRECOMPUTED = 128; unsigned int charIndexCache[MAX_PRECOMPUTED]; /** * Current error code. */ FT_Error err; }; #endif // __FTCharmap__
mcodegeeks/OpenKODE-Framework
01_Develop/libXMGraphics/Source/FTGLES/FTCharmap.h
C
mit
5,264
--- layout: post title: "CSS居中布局" date: 2017-05-13 15:16:45 author: "Joan" tags: ["css"] --- > 参考链接:https://css-tricks.com/centering-css-complete-guide/ ## 一、水平居中 ### 1.inline 元素 ``` .center-children { text-align: center; } ``` `text-align` 属性规定元素中的文本的水平对齐方式。该属性需要添加在 inline 元素的父元素上。 ### 2.block 块级元素 ``` .center-me { margin: 0 auto; } ``` 使用这种方法的时候元素 width 不能为 auto。当 width 没有设置的时候 block 元素将占满整行。 ### 3.多个 block 元素 #### 方法1:inline 方法 ``` .inline-block-center { text-align: center; } .inline-block-center div { display: inline-block; text-align: left; } ``` 第一种方法将多个块的属性设置为 `inline-block`,然后使用 inline 元素水平居中的方法。 #### 方法2:flex 布局 ``` .flex-center { display: flex; justify-content: center; } ``` 第二种方法,直接使用 `flex` 布局。这样的好处在于不用将 block 元素设置为 inline 元素。 简单介绍一下 `flex` 布局:`flex-direction` 属性决定了主轴的方向,`row` 水平方向(默认)或者 `column` 垂直方向。而 `justify-content` 属性定义了项目在主轴上的对齐方式。 ## 二、垂直居中 ### 1.inline 元素 #### 单行 inline 元素 ``` .link { padding-top: 30px; padding-bottom: 30px; } ``` 最简单的方法就是让上下内边距相等,但如果内边距不确定的情况下就无法使用这种方法了。 ``` .center-text-trick { height: 100px; line-height: 100px; white-space: nowrap; } ``` 这种方法适用于只有一行文字的时候。使 `line-height` 行高与内联元素的高度相等。`white-space` 属性指定元素内的空白怎样处理,`nowrap` 表示不会换行。 #### 多行 inline 元素 ``` .flex-center-vertically { display: flex; justify-content: center; flex-direction: column; height: 400px; } ``` 使用 `flex` 布局,设置 `flex-direction` 排列方向为垂直。这个方法的一个很重要的问题就是:需要知道父级元素的高度。如果不定义父级元素的高度,那么父级元素会根据内部元素自动调整自身高度,那么也就不会有居中的问题了。 **PS:在很多情况下,这种自适应还是很有用处的。**但是主轴不同时,情况有可能会有所不同。当主轴方向为水平方向的时候,每一行子元素的高度将是一致的,也就是说子元素很可能会被拉长,除非固定每个子元素的高度。父级元素没有指定高度与宽度的话,高度将会自动包裹住所有行,宽度则是100%。因此,**当每一行的高度都需要根据子元素内部包含的东西自适应的时候,需要将主轴设置为垂直方向。** ### 2.block 块级元素 #### 知道元素高度—— margin 负值 ``` .parent { position: relative; } .child { position: absolute; top: 50%; height: 100px; margin-top: -50px; } ``` 首先把元素放置到父元素一半的高度上,即 top:50%。然后再把块元素向上移动高度的一半。最终元素就垂直居中了。 将 margin 负值设置为总高度的一半(如果设置了 padding 或者 border,那么要记得计算进去),达到向上移动一半高度的效果。 #### 不知道元素高度—— transform ``` .parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); } ``` CSS3 中的新属性 `transform`,这个属性翻译过来就是变形、转换,它可以帮助我们对元素进行 2D 或者 3D 转换。`translate` 值定义了平移量,其参数的百分比相对的是元素本身而不是父元素。 PS:translate 常译为“翻译”,但在这里它的意思是“平移”。 #### 布局方法—— flex ``` .parent { display: flex; flex-direction: column; justify-content: center; } ``` ## 三、水平垂直居中 其实与水平居中的方法差不多,有三种分别是:`margin` 负值; `transform` 属性平移;以及 `flex` 布局。代码如下: ``` .parent { position: relative; } .child { width: 300px; height: 100px; padding: 20px; position: absolute; top: 50%; left: 50%; margin: -70px 0 0 -170px; } ``` ``` .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } ``` ``` .parent { display: flex; justify-content: center; align-items: center; } ``` ## 总结 当需要居中的元素是 `inline` 内联元素的时候,比如居中一些文字,那么则需要用到一些文字属性,比如 `text-align` 以及 `inline-height`。 当需要居中的属性为 `block` 块级元素的时候,使用 `transform` 或者 `flex` 会更方便一些。如果内部涉及的元素比较多,使用 `flex` 会更好。
WJoan/WJoan.github.io
_posts/2017-05-13-css-center.markdown
Markdown
mit
4,975
package gavilan.irc; import java.util.Set; import javax.annotation.PreDestroy; import org.pircbotx.PircBotX; public interface TwitchCore { void doGreet(ChatMessage cm); Set<String> getPendings(); void message(String channel, String message); void onMessage(ChatMessage cm); @PreDestroy void shutdown(); void startAll(PircBotX pircBotX); }
gavilancomun/irc-explorer
src/main/java/gavilan/irc/TwitchCore.java
Java
mit
366
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * Documento * * @ORM\Table(name="documentos") * @ORM\Entity */ class Documento { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var text * * @ORM\Column(name="descripcion", type="text",nullable=true) */ private $descripcion; /** * @var \DateTime * * @ORM\Column(name="fecha_ingreso", type="date") */ private $fechaIngreso; /** * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Expediente",inversedBy="documentos") * @ORM\JoinColumn(name="expediente_id", referencedColumnName="id") */ private $expediente; /** * @ORM\ManyToOne(targetEntity="TipoDocumentoExpediente",inversedBy="documentos") * @ORM\JoinColumn(name="tipo_documento_expediente_id", referencedColumnName="id") */ private $tipoDocumentoExpediente; /** * @ORM\OneToMany(targetEntity="AppBundle\Entity\Hoja", mappedBy="documento",cascade={"persist", "remove"}) * @ORM\OrderBy({"numero" = "ASC"}) */ private $hojas; /** * @var datetime $creado * * @Gedmo\Timestampable(on="create") * @ORM\Column(name="creado", type="datetime") */ private $creado; /** * @var datetime $actualizado * * @Gedmo\Timestampable(on="update") * @ORM\Column(name="actualizado",type="datetime") */ private $actualizado; /** * @var integer $creadoPor * * @Gedmo\Blameable(on="create") * @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario") * @ORM\JoinColumn(name="creado_por", referencedColumnName="id", nullable=true) */ private $creadoPor; /** * @var integer $actualizadoPor * * @Gedmo\Blameable(on="update") * @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario") * @ORM\JoinColumn(name="actualizado_por", referencedColumnName="id", nullable=true) */ private $actualizadoPor; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set descripcion * * @param string $descripcion * * @return Documento */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } /** * Set fechaIngreso * * @param \DateTime $fechaIngreso * * @return Documento */ public function setFechaIngreso($fechaIngreso) { $this->fechaIngreso = $fechaIngreso; return $this; } /** * Get fechaIngreso * * @return \DateTime */ public function getFechaIngreso() { return $this->fechaIngreso; } /** * Set orden * * @param integer $orden * * @return Documento */ public function setOrden($orden) { $this->orden = $orden; return $this; } /** * Get orden * * @return integer */ public function getOrden() { return $this->orden; } /** * Constructor */ public function __construct() { $this->hojas = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Set creado * * @param \DateTime $creado * * @return Documento */ public function setCreado($creado) { $this->creado = $creado; return $this; } /** * Get creado * * @return \DateTime */ public function getCreado() { return $this->creado; } /** * Set actualizado * * @param \DateTime $actualizado * * @return Documento */ public function setActualizado($actualizado) { $this->actualizado = $actualizado; return $this; } /** * Get actualizado * * @return \DateTime */ public function getActualizado() { return $this->actualizado; } /** * Set expediente * * @param \AppBundle\Entity\Expediente $expediente * * @return Documento */ public function setExpediente(\AppBundle\Entity\Expediente $expediente = null) { $this->expediente = $expediente; return $this; } /** * Get expediente * * @return \AppBundle\Entity\Expediente */ public function getExpediente() { return $this->expediente; } /** * Add hoja * * @param \AppBundle\Entity\Hoja $hoja * * @return Documento */ public function addHoja(\AppBundle\Entity\Hoja $hoja) { $this->hojas[] = $hoja; return $this; } /** * Remove hoja * * @param \AppBundle\Entity\Hoja $hoja */ public function removeHoja(\AppBundle\Entity\Hoja $hoja) { $this->hojas->removeElement($hoja); } /** * Get hojas * * @return \Doctrine\Common\Collections\Collection */ public function getHojas() { return $this->hojas; } /** * Set creadoPor * * @param \UsuariosBundle\Entity\Usuario $creadoPor * * @return Documento */ public function setCreadoPor(\UsuariosBundle\Entity\Usuario $creadoPor = null) { $this->creadoPor = $creadoPor; return $this; } /** * Get creadoPor * * @return \UsuariosBundle\Entity\Usuario */ public function getCreadoPor() { return $this->creadoPor; } /** * Set actualizadoPor * * @param \UsuariosBundle\Entity\Usuario $actualizadoPor * * @return Documento */ public function setActualizadoPor(\UsuariosBundle\Entity\Usuario $actualizadoPor = null) { $this->actualizadoPor = $actualizadoPor; return $this; } /** * Get actualizadoPor * * @return \UsuariosBundle\Entity\Usuario */ public function getActualizadoPor() { return $this->actualizadoPor; } /** * Set tipoDocumentoExpediente * * @param \AppBundle\Entity\TipoDocumentoExpediente $tipoDocumentoExpediente * * @return Documento */ public function setTipoDocumentoExpediente(\AppBundle\Entity\TipoDocumentoExpediente $tipoDocumentoExpediente = null) { $this->tipoDocumentoExpediente = $tipoDocumentoExpediente; return $this; } /** * Get tipoDocumentoExpediente * * @return \AppBundle\Entity\TipoDocumentoExpediente */ public function getTipoDocumentoExpediente() { return $this->tipoDocumentoExpediente; } }
johnnykatz/colegio
src/AppBundle/Entity/Documento.php
PHP
mit
7,069
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Immune System")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Immune System")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("58cabef6-9a10-46c5-918c-bbc68318c99a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
preslavc/SoftUni
Programming Fundamentals/More Exercises/Dictionaries and Lists/Immune System/Properties/AssemblyInfo.cs
C#
mit
1,397
package com.github.visgeek.utils.collections; import java.util.Iterator; class LinqConcateIterator<T> implements Iterator<T> { // コンストラクター public LinqConcateIterator(Iterable<T> source, Iterable<? extends T> second) { this.second = second; this.itr = source.iterator(); this.isSwitched = false; } // フィールド private final Iterable<? extends T> second; private Iterator<? extends T> itr; private boolean isSwitched; // プロパティ // メソッド @Override public boolean hasNext() { boolean result = false; result = this.itr.hasNext(); if (!this.isSwitched) { if (!result) { this.itr = this.second.iterator(); result = this.itr.hasNext(); this.isSwitched = true; } } return result; } @Override public T next() { return this.itr.next(); } // スタティックフィールド // スタティックイニシャライザー // スタティックメソッド }
visGeek/JavaVisGeekCollections
src/src/main/java/com/github/visgeek/utils/collections/LinqConcateIterator.java
Java
mit
1,003
# 微型调查问卷平台 实现一个简易版的问卷管理系统,有如下功能: ### 问卷管理列表 > - 有一个头部可以显示logo,不需要实现登录等操作 > - 问卷管理列表页面默认为首页 > - 有一个表格用于展示所有已创建的问卷 > - 列表中包括列有:问卷名称,问卷状态(未发布,发布中,已结束),和操作区域(编辑、删除、查看数据) > - 问卷状态为未发布时,可以做的操作为编辑、删除、查看问卷 > - 问卷状态为发布中和已结束时,可以做的操作为查看数据、查看问卷 > - 表格最左侧有批量选择(多选)的checkbox,多选后,可以进行批量删除功能,checkbox样式用默认即可,不需要按照设计图的样式 > - 当一个问卷都没有的时候,表格不展现,页面显示大大的新建问卷按钮 ### 问卷新建及编辑 > - 点击问卷管理列表中的新建按钮后,进入到问卷新建页面 > - 点击问卷列表中某个问卷行的编辑按钮后,进入到问卷的编辑页面 > - 新建页面和编辑页面基本相同 > - 问卷有一个标题字段,点击后可以进入编辑状态 > - 可以针对问卷中的问题进行增删改操作,每个问卷最少一个问题,最多十个问题 > - 问题类型包括:单选题、多选题、单行文本题 > - 可以对所有问题进行位置改变(上移、下移),复用,删除的操作 > - 最上面的问题没有上移操作,最下面的问题没有下移操作 > - 点击复用时,在被复用的问题紧接着的下方新增一个和被复用完全一样的问题(包括选项) > - 对于单选题和多选题,可以对问题的选项进行增、删、改、排序操作 > - 文本题可以设定是必填还是非必填的问题 > - 有一个问卷调查填写截止时间,使用一个日历组件来进行时间的选择,日期选择不能早于当前日期 > - 保存问卷可以进行问卷的保存 > - 发布问卷可以使得问卷状态变为发布中的状态 > - 当点击发布时,如果截止日期早于当前日期,则需要提示修改截止日期 ### 删除问卷 > - 在问卷管理列表中点击某个问卷的删除按钮后,弹出一个浮出层,让用户二次确认是否删除该问卷,如果用户点击是,则删除掉该问卷 ### 查看问卷 > - 在问卷管理列表中点击查看问卷的按钮后,在新窗口中打开该问卷的页面,该页面是可供用户进行问卷填写的页面,在问卷未发布状态和已结束状态时,问卷提交是无效的。 > - 该页面在移动端需要进行良好的兼容支持 ### 查看数据 > - 在问卷管理列表中点击查看数据按钮后,进入到一个数据报告页面,用图表形式呈现各个单选题和多选题的选择情况 > - 如设计稿中呈现,每一个问题在右侧用某种图表来呈现答题情况,自行选择合适的图表,设计稿中仅为示意,图表样式不需要和设计稿一致。推荐单选题使用饼状图,多选题使用条形图 > - 文本题用一个百分比图展现有效回答占比即可 > - 返回按钮点击后返回列表页面
shauvet/vue-questionnaire
README.md
Markdown
mit
3,235
package de.csmath.QT; import java.util.Collection; import java.util.List; /** * This class builds a FTypeAtom from given parameters. * @author lpfeiler */ public class FTypeAtomBuilder extends QTAtomBuilder { /** * @see FTypeAtom#majBrand */ private int majBrand = 0; /** * @see FTypeAtom#minVersion */ private int minVersion = 0; /** * @see FTypeAtom#compBrands */ private Collection<Integer> compBrands; /** * Constructs a FTypeAtomBuilder. * @param size the size of the FTypeAtom in the file * @param type the type of the atom, should be set to 'ftyp' */ public FTypeAtomBuilder(int size, int type) { super(size, type); } /** * Returns a new FTypeAtom. * @return a new FTypeAtom */ public FTypeAtom build() { return new FTypeAtom(size,type,majBrand,minVersion,compBrands); } /** * Sets the major brand. * @see FTypeAtom#majBrand * @param majBrand the major brand * @return a reference to this object */ public FTypeAtomBuilder withMajBrand(int majBrand) { this.majBrand = majBrand; return this; } /** * Sets the minor version. * @see FTypeAtom#minVersion * @param minVersion the minor version * @return a reference to this object */ public FTypeAtomBuilder withMinVersion(int minVersion) { this.minVersion = minVersion; return this; } /** * Sets the compatible brands. * @param compBrands a collection of compatible brands * @return a reference to this object */ public FTypeAtomBuilder withCompBrands(Collection<Integer> compBrands) { this.compBrands = compBrands; return this; } }
lpcsmath/QTReader
src/main/java/de/csmath/QT/FTypeAtomBuilder.java
Java
mit
1,783
<!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Workweek Template: Tyler Kirkham Andrews</title> <meta name="description" content="Workweek lets you build your own portfolio with built-in invoicing and payment processing. "> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <!-- Place favicon.ico in the root directory --> <link rel="stylesheet" href="css/stylesheet.css"> <link rel="stylesheet" href="codrops/css/component.css"> <script src="js/vendor/modernizr-2.8.3.min.js"></script> <!-- Font Awesome --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <!-- Stylesheet for Lightbox plugin --> <link rel="stylesheet" href="js/Minimal-jQuery-Image-Gallery-Lightbox-Plugin-maxGallery/css/css.css"> </head> <body> <!-- needed for facebook like button --> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <!--[if lt IE 8]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <!-- Add your site or application content here --> <!-- HEADER --> <div class="header sidebar"> <div class="logo"> <!-- <img src="" alt="Anna James Photography Logo" width="200"> --> <h1><a href="index.html">Tyler Andrews</a></h1> </div> <div class="nav"> <div class="nav-menu"> <ul class="reset"> <li> <a href="index.html">Work</a> </li> <li> <a href="index-about.html">About</a> </li> <li> <a href="http://hellotylo.tumblr.com/">Blog</a> </li> <li> <a href="contact.html">Contact</a> </li> </ul> <div class="social-icons"> <a href="http://instagram.com/hellotylo"> <i class="fa fa-instagram"></i> </a> <a href="http://twitter.com/workweekhq"> <i class="fa fa-twitter"></i> </a> </div> </div> </div> </div> <!-- MAIN BODY --> <div class="main"> <!-- BEGIN new slider thing --> <!-- PORTFOLIO --> <div class="section portfolio"> <div class="gallery"> <a href="img/10.jpg" class="gallery__item"> <img src="img/10.jpg" alt="" class="gallery__item-img" data-id="0" data-title="Neue Wall"> <i class="gallery__item-cover"></i> </a> <a href="img/7.jpg" class="gallery__item"> <img src="img/7.jpg" alt="" class="gallery__item-img" data-id="1" data-title="Exhibit Cards"> <i class="gallery__item-cover"></i> </a> <a href="img/8.jpg" class="gallery__item"> <img src="img/8.jpg" alt="" class="gallery__item-img" data-id="2" data-title="Neue Poster 1"> <i class="gallery__item-cover"></i> </a> <a href="img/9.jpg" class="gallery__item"> <img src="img/9.jpg" alt="" class="gallery__item-img" data-id="3" data-title="Neue Poster 2"> <i class="gallery__item-cover"></i> </a> <hr> </div> <!-- SLIDER --> <div class="slider" style="display: none;"> <table class="slider__table"> <tr> <td class="slider__table-td"> <!-- <div class="slider__table-td-item-number"> </div> --> <div class="slider__table-td-inner"> <img src="img/0.jpg" alt="" class="slider__cur-img"> </div> <div class="slider__table-td-item-title"> </div> </td> </tr> </table> <a href="#prev" class="slider__btn slider__btn_prev"></a> <a href="#next" class="slider__btn slider__btn_next"></a> <i class="slider__btn_close"></i> </div> <!-- NEW PORTFOLIO with just thumbs -- adding to bottom of each project page. for easy navigation --> <div class="section portfolio"> <div class="row"> <div class="four columns"> <a href="project-1.html" class="thumbnail" style="background-image: url(img/2-1.jpg)"></a> </div> <div class="four columns"> <a href="project-2.html" class="thumbnail" style="background-image: url(img/10.jpg)"></a> </div> <div class="four columns"> <a href="project-3.html" class="thumbnail" style="background-image: url(img/11.jpg)"></a> </div> </div> <div class="row"> <div class="four columns"> <a href="project-4.html" class="thumbnail" style="background-image: url(img/14.jpg)"></a> </div> <div class="four columns"> <a href="project-5.html" class="thumbnail" style="background-image: url(img/16.jpg)"></a> </div> <div class="four columns"> <a href="project-6.html" class="thumbnail" style="background-image: url(img/19.jpg)"></a> </div> </div> <div class="row"> <div class="four columns"> <a href="project-7.html" class="thumbnail" style="background-image: url(img/3.jpg)"></a> </div> <div class="four columns"> <a href="project-8.html" class="thumbnail" style="background-image: url(http://static1.squarespace.com/static/5331a702e4b03a785d938a57/5333a407e4b01acd1d7e6b5c/533cbb23e4b0a2d81388a175/1396488997535/2.jpg?format=1000w)"></a> </div> <div class="four columns"> <a href="project-9.html" class="thumbnail" style="background-image: url(img/20.jpg)"></a> </div> </div> </div> </div> </div> <!-- FOOTER --> <div class="footer"> </div> <!-- Scripts --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> <!-- Gallery Lightbox plugin --> <script src="js/Minimal-jQuery-Image-Gallery-Lightbox-Plugin-maxGallery/js/js.js"></script> <!-- Google Analytics --> <script> (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]= function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date; e=o.createElement(i);r=o.getElementsByTagName(i)[0]; e.src='https://www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e,r)}(window,document,'script','ga')); ga('create','UA-XXXX-XXXX','auto');ga('send','pageview'); </script> </body> </html>
brettbradleycampbell/workweek-landing
demo/template-2b/project-2.html
HTML
mit
7,716
package personifiler.cluster; import static org.junit.Assert.*; import org.junit.Test; import personifiler.util.TestUtils; /** * Tests for {@link RandIndex} * * @author Allen Cheng */ public class TestRandIndex { /** * Tests that the rand index of a cluster is between 0.0 and 1.0 */ @Test public void testRandIndex() { ClusterPeople cluster = new ClusterPeople(TestUtils.getSampleFeatureMatrix()); double randIndex = cluster.randIndex(TestUtils.getSampleGroundTruth()); assertTrue(randIndex >= 0.0 && randIndex <= 1.0); } }
allen12/Personifiler
test/personifiler/cluster/TestRandIndex.java
Java
mit
554
namespace Azure.Security.Attestation { public partial class AttestationAdministrationClient : System.IDisposable { protected AttestationAdministrationClient() { } public AttestationAdministrationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } public AttestationAdministrationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Security.Attestation.AttestationClientOptions options) { } public System.Uri Endpoint { get { throw null; } } public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult> AddPolicyManagementCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 newSigningCertificate, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult>> AddPolicyManagementCertificateAsync(System.Security.Cryptography.X509Certificates.X509Certificate2 newSigningCertificate, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual Azure.Security.Attestation.AttestationResponse<string> GetPolicy(Azure.Security.Attestation.AttestationType attestationType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<string>> GetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesResult> GetPolicyManagementCertificates(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesResult>> GetPolicyManagementCertificatesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult> RemovePolicyManagementCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificateToRemove, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult>> RemovePolicyManagementCertificateAsync(System.Security.Cryptography.X509Certificates.X509Certificate2 certificateToRemove, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult> ResetPolicy(Azure.Security.Attestation.AttestationType attestationType, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult>> ResetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult> SetPolicy(Azure.Security.Attestation.AttestationType attestationType, string policyToSet, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult>> SetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, string policyToSet, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AttestationClient : System.IDisposable { protected AttestationClient() { } public AttestationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } public AttestationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Security.Attestation.AttestationClientOptions options) { } public System.Uri Endpoint { get { throw null; } } public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult> AttestOpenEnclave(System.ReadOnlyMemory<byte> report, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult>> AttestOpenEnclaveAsync(System.ReadOnlyMemory<byte> report, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult> AttestSgxEnclave(System.ReadOnlyMemory<byte> quote, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult>> AttestSgxEnclaveAsync(System.ReadOnlyMemory<byte> quote, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<System.BinaryData> AttestTpm(System.BinaryData request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<System.BinaryData>> AttestTpmAsync(System.BinaryData request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner>> GetSigningCertificates(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner>>> GetSigningCertificatesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AttestationClientOptions : Azure.Core.ClientOptions { public AttestationClientOptions(Azure.Security.Attestation.AttestationClientOptions.ServiceVersion version = Azure.Security.Attestation.AttestationClientOptions.ServiceVersion.V2020_10_01, Azure.Security.Attestation.TokenValidationOptions tokenOptions = null) { } public enum ServiceVersion { V2020_10_01 = 1, } } public partial class AttestationResponse<T> : Azure.Response<T> where T : class { internal AttestationResponse() { } public Azure.Security.Attestation.AttestationToken Token { get { throw null; } } public override T Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } } public partial class AttestationResult { internal AttestationResult() { } public object Confirmation { get { throw null; } } public byte[] DeprecatedEnclaveHeldData { get { throw null; } } public byte[] DeprecatedEnclaveHeldData2 { get { throw null; } } public bool? DeprecatedIsDebuggable { get { throw null; } } public string DeprecatedMrEnclave { get { throw null; } } public string DeprecatedMrSigner { get { throw null; } } public byte[] DeprecatedPolicyHash { get { throw null; } } public float? DeprecatedProductId { get { throw null; } } public string DeprecatedRpData { get { throw null; } } public object DeprecatedSgxCollateral { get { throw null; } } public float? DeprecatedSvn { get { throw null; } } public string DeprecatedTee { get { throw null; } } public string DeprecatedVersion { get { throw null; } } public byte[] EnclaveHeldData { get { throw null; } } public System.DateTimeOffset Expiration { get { throw null; } } public object InittimeClaims { get { throw null; } } public bool? IsDebuggable { get { throw null; } } public System.DateTimeOffset IssuedAt { get { throw null; } } public System.Uri Issuer { get { throw null; } } public string MrEnclave { get { throw null; } } public string MrSigner { get { throw null; } } public string Nonce { get { throw null; } } public System.DateTimeOffset NotBefore { get { throw null; } } public object PolicyClaims { get { throw null; } } public byte[] PolicyHash { get { throw null; } } public float? ProductId { get { throw null; } } public object RuntimeClaims { get { throw null; } } public object SgxCollateral { get { throw null; } } public float? Svn { get { throw null; } } public string UniqueIdentifier { get { throw null; } } public string VerifierType { get { throw null; } } public string Version { get { throw null; } } } public partial class AttestationSigner { public AttestationSigner(System.Security.Cryptography.X509Certificates.X509Certificate2[] signingCertificates, string certificateKeyId) { } public string CertificateKeyId { get { throw null; } } public System.Collections.Generic.IReadOnlyList<System.Security.Cryptography.X509Certificates.X509Certificate2> SigningCertificates { get { throw null; } } } public partial class AttestationToken { protected AttestationToken() { } public AttestationToken(Azure.Security.Attestation.TokenSigningKey signingKey) { } public AttestationToken(object body) { } public AttestationToken(object body, Azure.Security.Attestation.TokenSigningKey signingKey) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] protected internal AttestationToken(string token) { } public virtual string Algorithm { get { throw null; } } public virtual string CertificateThumbprint { get { throw null; } } public virtual string ContentType { get { throw null; } } public virtual bool? Critical { get { throw null; } } public virtual System.DateTimeOffset? ExpirationTime { get { throw null; } } public virtual System.DateTimeOffset? IssuedAtTime { get { throw null; } } public virtual string Issuer { get { throw null; } } public virtual string KeyId { get { throw null; } } public virtual System.Uri KeyUrl { get { throw null; } } public virtual System.DateTimeOffset? NotBeforeTime { get { throw null; } } public virtual Azure.Security.Attestation.AttestationSigner SigningCertificate { get { throw null; } } public virtual string TokenBody { get { throw null; } } public virtual System.ReadOnlyMemory<byte> TokenBodyBytes { get { throw null; } } public virtual string TokenHeader { get { throw null; } } public virtual System.ReadOnlyMemory<byte> TokenHeaderBytes { get { throw null; } } public virtual System.ReadOnlyMemory<byte> TokenSignatureBytes { get { throw null; } } public virtual string Type { get { throw null; } } public virtual System.Security.Cryptography.X509Certificates.X509Certificate2[] X509CertificateChain { get { throw null; } } public virtual string X509CertificateSha256Thumbprint { get { throw null; } } public virtual string X509CertificateThumbprint { get { throw null; } } public virtual System.Uri X509Url { get { throw null; } } public virtual T GetBody<T>() where T : class { throw null; } public override string ToString() { throw null; } public virtual bool ValidateToken(Azure.Security.Attestation.TokenValidationOptions options, System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner> attestationSigningCertificates, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<bool> ValidateTokenAsync(Azure.Security.Attestation.TokenValidationOptions options, System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner> attestationSigningCertificates, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct AttestationType : System.IEquatable<Azure.Security.Attestation.AttestationType> { private readonly object _dummy; private readonly int _dummyPrimitive; public AttestationType(string value) { throw null; } public static Azure.Security.Attestation.AttestationType OpenEnclave { get { throw null; } } public static Azure.Security.Attestation.AttestationType SgxEnclave { get { throw null; } } public static Azure.Security.Attestation.AttestationType Tpm { get { throw null; } } public bool Equals(Azure.Security.Attestation.AttestationType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Security.Attestation.AttestationType left, Azure.Security.Attestation.AttestationType right) { throw null; } public static implicit operator Azure.Security.Attestation.AttestationType (string value) { throw null; } public static bool operator !=(Azure.Security.Attestation.AttestationType left, Azure.Security.Attestation.AttestationType right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CertificateModification : System.IEquatable<Azure.Security.Attestation.CertificateModification> { private readonly object _dummy; private readonly int _dummyPrimitive; public CertificateModification(string value) { throw null; } public static Azure.Security.Attestation.CertificateModification IsAbsent { get { throw null; } } public static Azure.Security.Attestation.CertificateModification IsPresent { get { throw null; } } public bool Equals(Azure.Security.Attestation.CertificateModification other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Security.Attestation.CertificateModification left, Azure.Security.Attestation.CertificateModification right) { throw null; } public static implicit operator Azure.Security.Attestation.CertificateModification (string value) { throw null; } public static bool operator !=(Azure.Security.Attestation.CertificateModification left, Azure.Security.Attestation.CertificateModification right) { throw null; } public override string ToString() { throw null; } } public partial class PolicyCertificatesModificationResult { internal PolicyCertificatesModificationResult() { } public Azure.Security.Attestation.CertificateModification? CertificateResolution { get { throw null; } } public string CertificateThumbprint { get { throw null; } } } public partial class PolicyCertificatesResult { public PolicyCertificatesResult() { } public System.Collections.Generic.IReadOnlyList<System.Security.Cryptography.X509Certificates.X509Certificate2> GetPolicyCertificates() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PolicyModification : System.IEquatable<Azure.Security.Attestation.PolicyModification> { private readonly object _dummy; private readonly int _dummyPrimitive; public PolicyModification(string value) { throw null; } public static Azure.Security.Attestation.PolicyModification Removed { get { throw null; } } public static Azure.Security.Attestation.PolicyModification Updated { get { throw null; } } public bool Equals(Azure.Security.Attestation.PolicyModification other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Security.Attestation.PolicyModification left, Azure.Security.Attestation.PolicyModification right) { throw null; } public static implicit operator Azure.Security.Attestation.PolicyModification (string value) { throw null; } public static bool operator !=(Azure.Security.Attestation.PolicyModification left, Azure.Security.Attestation.PolicyModification right) { throw null; } public override string ToString() { throw null; } } public partial class PolicyResult { public PolicyResult() { } public Azure.Security.Attestation.PolicyModification PolicyResolution { get { throw null; } } public Azure.Security.Attestation.AttestationSigner PolicySigner { get { throw null; } } public byte[] PolicyTokenHash { get { throw null; } } } public partial class StoredAttestationPolicy { public StoredAttestationPolicy() { } public string AttestationPolicy { get { throw null; } set { } } } public partial class TokenSigningKey { public TokenSigningKey(System.Security.Cryptography.AsymmetricAlgorithm signer, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public TokenSigningKey(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm Signer { get { throw null; } } } public partial class TokenValidationOptions { public TokenValidationOptions(bool validateToken = true, bool validateExpirationTime = true, bool validateNotBeforeTime = true, bool validateIssuer = false, string expectedIssuer = null, int timeValidationSlack = 0, System.Func<Azure.Security.Attestation.AttestationToken, Azure.Security.Attestation.AttestationSigner, bool> validationCallback = null) { } public string ExpectedIssuer { get { throw null; } } public long TimeValidationSlack { get { throw null; } } public bool ValidateExpirationTime { get { throw null; } } public bool ValidateIssuer { get { throw null; } } public bool ValidateNotBeforeTime { get { throw null; } } public bool ValidateToken { get { throw null; } } public System.Func<Azure.Security.Attestation.AttestationToken, Azure.Security.Attestation.AttestationSigner, bool> ValidationCallback { get { throw null; } } } public partial class TpmAttestationRequest { public TpmAttestationRequest() { } public System.ReadOnlyMemory<byte> Data { get { throw null; } set { } } } public partial class TpmAttestationResponse { internal TpmAttestationResponse() { } public System.ReadOnlyMemory<byte> Data { get { throw null; } } } }
ayeletshpigelman/azure-sdk-for-net
sdk/attestation/Azure.Security.Attestation/api/Azure.Security.Attestation.netstandard2.0.cs
C#
mit
22,286
// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY const daggy = require('daggy') const compose = (f, g) => x => f(g(x)) const id = x => x //===============Define Coyoneda========= // create constructor with props 'x' and 'f' // 'x' is our value, 'f' is a function const Coyoneda = daggy.tagged('x', 'f') // map composes the function Coyoneda.prototype.map = function(f) { return Coyoneda(this.x, compose(f, this.f)) } Coyoneda.prototype.lower = function() { return this.x.map(this.f) } // lift starts off Coyoneda with the 'id' function Coyoneda.lift = x => Coyoneda(x, id) //===============Map over a non-Functor - Set ========= // Set does not have a 'map' method const set = new Set([1, 1, 2, 3, 3, 4]) console.log("Set([1, 1, 2, 3, 3, 4]) : ", set) // Wrap set into Coyoneda with 'id' function const coyoResult = Coyoneda.lift(set) .map(x => x + 1) .map(x => `${x}!`) console.log( "Coyoneda.lift(set).map(x => x + 1).map(x => `${x}!`): ", coyoResult ) // equivalent to buildUpFn = coyoResult.f, ourSet = coyoResult.x const {f: builtUpFn, x: ourSet} = coyoResult console.log("builtUpFn is: ", builtUpFn, "; ourSet is: ", ourSet) ourSet .forEach(n => console.log(builtUpFn(n))) // 2! // 3! // 4! // 5! //===============Lift a functor in (Array) and achieve Loop fusion========= console.log( `Coyoneda.lift([1,2,3]).map(x => x * 2).map(x => x - 1).lower() : `, Coyoneda.lift([1,2,3]) .map(x => x * 2) .map(x => x - 1) .lower() ) // [ 1, 3, 5 ] //===============Make Any Type a Functor========= // Any object becomes a functor when placed in Coyoneda const Container = daggy.tagged('x') const tunacan = Container("tuna") const res = Coyoneda.lift(tunacan) .map(x => x.toUpperCase()) .map(x => x + '!') const {f: fn, x: can} = res console.log(fn(can.x)) // TUNA!
dmitriz/functional-examples
examples/coyoneda.js
JavaScript
mit
1,828
package org.coursera.androidcapstone.symptomchecker.repository; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface PatientRepository extends PagingAndSortingRepository<Patient, Long> { @Query("From Patient p where :doctor member p.doctors") public Page<Patient> findByDoctor(@Param("doctor") Doctor doctor, Pageable page); @Query("From Patient p where :doctor member p.doctors AND UPPER(fullName)=:fullName") public List<Patient> findByDoctorAndFullName(@Param("doctor") Doctor doctor, @Param("fullName") String fullName); }
emadhilo/capstone
SymptomCheckerService/src/main/java/org/coursera/androidcapstone/symptomchecker/repository/PatientRepository.java
Java
mit
860
<!doctype html> <html class="theme-next "> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/> <meta http-equiv="Cache-Control" content="no-transform" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta name="google-site-verification" content="h7BaHlqi6VjlciSt0RF-KHgIXZcGfx3L3gyQ9qfx_ek" /> <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/> <link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" /> <link href="/css/main.css?v=0.4.5.2" rel="stylesheet" type="text/css" /> <meta name="keywords" content="vim,tool," /> <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.4.5.2" /> <meta name="description" content="vim中常用的命令,日常更新 !ls 使用感叹号开头调用系统命令~ 切换当前光标所在字符的大小写 buffer相关:ls:bn :bnext:bp :bprev:bd :bdelete:b1 :buffer1:bufdo cmd 在所有缓冲区执行命令 参数列表:args 列出参数列表或者设置参数列表:args **/*.postfix:write :w:edit! :e!放弃修改重新载入文件"> <meta name="keywords" content="vim,tool"> <meta property="og:type" content="article"> <meta property="og:title" content="vim 常用的命令模式"> <meta property="og:url" content="http://blog.wuxu92.com/vim-commands/index.html"> <meta property="og:site_name" content="Wu Xu"> <meta property="og:description" content="vim中常用的命令,日常更新 !ls 使用感叹号开头调用系统命令~ 切换当前光标所在字符的大小写 buffer相关:ls:bn :bnext:bp :bprev:bd :bdelete:b1 :buffer1:bufdo cmd 在所有缓冲区执行命令 参数列表:args 列出参数列表或者设置参数列表:args **/*.postfix:write :w:edit! :e!放弃修改重新载入文件"> <meta property="og:locale" content="zh-Hans"> <meta property="og:updated_time" content="2018-04-14T11:19:13.386Z"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="vim 常用的命令模式"> <meta name="twitter:description" content="vim中常用的命令,日常更新 !ls 使用感叹号开头调用系统命令~ 切换当前光标所在字符的大小写 buffer相关:ls:bn :bnext:bp :bprev:bd :bdelete:b1 :buffer1:bufdo cmd 在所有缓冲区执行命令 参数列表:args 列出参数列表或者设置参数列表:args **/*.postfix:write :w:edit! :e!放弃修改重新载入文件"> <script type="text/javascript" id="hexo.configuration"> var CONFIG = { scheme: '', sidebar: 'hide', motion: false }; </script> <title> vim 常用的命令模式 | Wu Xu </title> </head> <body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"> <!--[if lte IE 8]> <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'> <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode"> <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari." style='margin-left:auto;margin-right:auto;display: block;'/> </a> </div> <![endif]--> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-72131273-1', 'auto'); ga('send', 'pageview'); </script> <div class="container one-column page-post-detail"> <div class="headband"></div> <div class="bottomband"></div> <!-- add by wuxu --> <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"> <div class="header-inner"><div class="site-meta "> <div class="custom-logo-site-title"> <a href="/" class="brand" rel="start"> <span class="logo-line-before"><i></i></span> <span class="site-title">Wu Xu</span> <span class="logo-line-after"><i></i></span> </a> </div> <p class="site-subtitle">关注C、Go、C++、JavaScript和Rust</p> </div> <div class="site-nav-toggle"> <button> <span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span> </button> </div> <nav class="site-nav"> <ul id="menu" class="menu "> <li class="menu-item menu-item-home"> <a href="/" rel="section"> <i class="menu-item-icon fa fa-home fa-fw"></i> <br /> 首页 </a> </li> <li class="menu-item menu-item-categories"> <a href="/categories" rel="section"> <i class="menu-item-icon fa fa-th fa-fw"></i> <br /> 分类 </a> </li> <li class="menu-item menu-item-tags"> <a href="/tags" rel="section"> <i class="menu-item-icon fa fa-tags fa-fw"></i> <br /> 标签 </a> </li> <li class="menu-item menu-item-archives"> <a href="/archives" rel="section"> <i class="menu-item-icon fa fa-archive fa-fw"></i> <br /> 归档 </a> </li> <li class="menu-item menu-item-about"> <a href="/about" rel="section"> <i class="menu-item-icon fa fa-user fa-fw"></i> <br /> 关于 </a> </li> </ul> </nav> </div> </header> <main id="main" class="main"> <div class="main-inner"> <div id="content" class="content"> <div id="posts" class="posts-expand"> <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h1 class="post-title" itemprop="name headline"> vim 常用的命令模式 </h1> <div class="post-meta"> <span class="post-time"> 发表于 <time itemprop="dateCreated" datetime="2015-07-18T12:34:50+08:00" content="2015-07-18"> 2015-07-18 </time> </span> <span class="post-category" > &nbsp; | &nbsp; 分类于 <span itemprop="about" itemscope itemtype="https://schema.org/Thing"> <a href="/categories/Linux/" itemprop="url" rel="index"> <span itemprop="name">Linux</span> </a> </span> </span> </div> </header> <div class="post-body"> <span itemprop="articleBody"><p>vim中常用的命令,日常更新 </p> <figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">!ls 使用感叹号开头调用系统命令</span><br><span class="line">~ 切换当前光标所在字符的大小写</span><br></pre></td></tr></table></figure> <h2 id="buffer相关"><a href="#buffer相关" class="headerlink" title="buffer相关"></a>buffer相关</h2><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">:ls</span><br><span class="line">:bn :bnext</span><br><span class="line">:bp :bprev</span><br><span class="line">:bd :bdelete</span><br><span class="line">:b1 :buffer1</span><br><span class="line">:bufdo cmd 在所有缓冲区执行命令</span><br></pre></td></tr></table></figure> <h2 id="参数列表"><a href="#参数列表" class="headerlink" title="参数列表"></a>参数列表</h2><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">:args 列出参数列表或者设置参数列表</span><br><span class="line">:args **/*.postfix</span><br><span class="line">:write :w</span><br><span class="line">:edit! :e!放弃修改重新载入文件</span><br><span class="line">:qall :qa</span><br><span class="line">:wall :wa</span><br></pre></td></tr></table></figure> <h2 id="多窗口"><a href="#多窗口" class="headerlink" title="多窗口"></a>多窗口</h2><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">:sp [file] 水平分割</span><br><span class="line">:vsp [filw] 垂直分割</span><br><span class="line">:clo &lt;C-w&gt;c 关闭当前窗口</span><br><span class="line">:no[ly] &lt;C-v&gt;o 关闭当前之外的所有窗口</span><br></pre></td></tr></table></figure> <p><strong>切换窗口</strong></p> <figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&lt;C-w&gt;&lt;C-w&gt; 在串口中切换,连续按两次Ctrl+w</span><br><span class="line">&lt;C-w&gt;h|j|k|l 切换到左/下/上/右的窗口</span><br></pre></td></tr></table></figure> <p><strong>改变窗口大小</strong></p> <figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&lt;C-w&gt;=</span><br><span class="line">&lt;C-w&gt;_ 最大化当前窗口的高度</span><br><span class="line">&lt;C-w&gt;| 最大化当前窗口的宽度</span><br><span class="line">[n]&lt;C-w&gt;_ 设置</span><br><span class="line">[n]&lt;C-w&gt;|</span><br></pre></td></tr></table></figure> <h2 id="标签"><a href="#标签" class="headerlink" title="标签"></a>标签</h2><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">:tabedit :tabe &#123;filename&#125; 如果filename为空则打开一个新的标签页</span><br><span class="line">:tabclose :tabc </span><br><span class="line">:tabonly :tabo 关闭当前标签之外的所有标签</span><br></pre></td></tr></table></figure> <p><strong>标签切换</strong></p> <figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">:tabnext :tabn &#123;N&#125; Ngt</span><br><span class="line">:tabn gt</span><br><span class="line">:tabp gT</span><br><span class="line">:tabmove [N] 移动标签页</span><br></pre></td></tr></table></figure> <h2 id="打开及保存文件"><a href="#打开及保存文件" class="headerlink" title="打开及保存文件"></a>打开及保存文件</h2><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">:edit full/path/name</span><br><span class="line">:edit %:h&lt;tab&gt;filename 使用缓冲区文件的完整路径打开文件, :h去掉当前文件名,tab键补全</span><br><span class="line">:edit path 打开文件管理窗口</span><br><span class="line">:find filename 在path下查找文件</span><br><span class="line">: set path+=/path/to/workspace 将工作区添加到vim的path中用于寻找</span><br><span class="line">:e 是 :edit的缩写</span><br><span class="line">:Explore :E 打开当前的目录管理器</span><br><span class="line">:Sexplore explore的切分</span><br><span class="line">:Vexplore</span><br></pre></td></tr></table></figure> <p><strong>文件操作</strong></p> <figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">:!mkdir -p %:h 前缓冲区创建目录,然后在:w,解决某些不能保存的问题</span><br><span class="line">:w !sudo tee % &gt; /dev/null 由于保存用非sudo打开的无权限文件的保存</span><br></pre></td></tr></table></figure> </span> </div> <footer class="post-footer"> <div class="post-tags"> <a href="/tags/vim/" rel="tag">#vim</a> <a href="/tags/tool/" rel="tag">#tool</a> </div> <div class="post-nav"> <div class="post-nav-next post-nav-item"> <a href="/go-iota-spc/" rel="next" title="Golang 中iota的用法"> <i class="fa fa-chevron-left"></i> Golang 中iota的用法 </a> </div> <div class="post-nav-prev post-nav-item"> <a href="/effective-go-note-1/" rel="prev" title="Effective Go笔记:函数,数据,初始化"> Effective Go笔记:函数,数据,初始化 <i class="fa fa-chevron-right"></i> </a> </div> </div> </footer> </article> <div class="post-spread"> </div> </div> </div> <div class="comments" id="comments"> </div> </div> <div class="sidebar-toggle"> <div class="sidebar-toggle-line-wrap"> <span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span> </div> </div> <aside id="sidebar" class="sidebar"> <div class="sidebar-inner"> <ul class="sidebar-nav motion-element"> <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" > 文章目录 </li> <li class="sidebar-nav-overview" data-target="site-overview"> 站点概览 </li> </ul> <section class="site-overview sidebar-panel "> <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" src="/images/avatar.jpg" alt="wuxu" itemprop="image"/> <p class="site-author-name" itemprop="name">wuxu</p> </div> <p class="site-description motion-element" itemprop="description">Wu Xu的个人博客</p> <nav class="site-state motion-element"> <div class="site-state-item site-state-posts"> <a href="/archives"> <span class="site-state-item-count">178</span> <span class="site-state-item-name">日志</span> </a> </div> <div class="site-state-item site-state-categories"> <a href="/categories"> <span class="site-state-item-count">25</span> <span class="site-state-item-name">分类</span> </a> </div> <div class="site-state-item site-state-tags"> <a href="/tags"> <span class="site-state-item-count">148</span> <span class="site-state-item-name">标签</span> </a> </div> </nav> <div class="links-of-author motion-element"> <span class="links-of-author-item"> <a href="https://github.com/wuxu92" target="_blank"> <i class="fa fa-github"></i> GitHub </a> </span> <span class="links-of-author-item"> <a href="https://twitter.com/wuxu92" target="_blank"> <i class="fa fa-twitter"></i> Twitter </a> </span> <span class="links-of-author-item"> <a href="http://weibo.com/kiwidock" target="_blank"> <i class="fa fa-weibo"></i> Weibo </a> </span> <span class="links-of-author-item"> <a href="http://douban.com/people/wuxu92" target="_blank"> <i class="fa fa-douban"></i> Douban </a> </span> <span class="links-of-author-item"> <a href="http://www.zhihu.com/people/wuxu92" target="_blank"> <i class="fa fa-zhihu"></i> Zhihu </a> </span> </div> <div class="cc-license motion-element" itemprop="license"> <a href="http://creativecommons.org/licenses/by-nc-sa/4.0" class="cc-opacity" target="_blank"> <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" /> </a> </div> <div class="links-of-author motion-element"> </div> </section> <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"> <div class="post-toc-indicator-top post-toc-indicator"> <i class="fa fa-angle-double-up"></i> </div> <div class="post-toc"> <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#buffer相关"><span class="nav-number">1.</span> <span class="nav-text">buffer相关</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参数列表"><span class="nav-number">2.</span> <span class="nav-text">参数列表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多窗口"><span class="nav-number">3.</span> <span class="nav-text">多窗口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#标签"><span class="nav-number">4.</span> <span class="nav-text">标签</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#打开及保存文件"><span class="nav-number">5.</span> <span class="nav-text">打开及保存文件</span></a></li></ol></div> </div> <div class="post-toc-indicator-bottom post-toc-indicator"> <i class="fa fa-angle-double-down"></i> </div> </section> </div> </aside> </main> <footer id="footer" class="footer"> <div class="footer-inner"> <div class="copyright" > &copy; 2014 - <span itemprop="copyrightYear">2020</span> <span class="with-love"> <i class="icon-next-heart fa fa-heart"></i> </span> <span class="author" itemprop="copyrightHolder">wuxu</span> </div> <div class="powered-by"> 由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动 </div> <div class="theme-info"> 主题 - <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next"> NexT </a> </div> </div> </footer> <div class="back-to-top"></div> </div> <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script> <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script> <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.2"></script> <script type="text/javascript" src="/js/helpers.js?v=0.4.5.2"></script> <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script> <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script> <script type="text/javascript" src="/js/motion.js?v=0.4.5.2" id="motion.global"></script> <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script> <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script> <script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.2" id="bootstrap.scrollspy.custom"></script> <script type="text/javascript" id="sidebar.toc.highlight"> $(document).ready(function () { var tocSelector = '.post-toc'; var $tocSelector = $(tocSelector); var activeCurrentSelector = '.active-current'; $tocSelector .on('activate.bs.scrollspy', function () { var $currentActiveElement = $(tocSelector + ' .active').last(); removeCurrentActiveClass(); $currentActiveElement.addClass('active-current'); $tocSelector[0].scrollTop = $currentActiveElement.position().top; }) .on('clear.bs.scrollspy', function () { removeCurrentActiveClass(); }); function removeCurrentActiveClass () { $(tocSelector + ' ' + activeCurrentSelector) .removeClass(activeCurrentSelector.substring(1)); } function processTOC () { getTOCMaxHeight(); toggleTOCOverflowIndicators(); } function getTOCMaxHeight () { var height = $('.sidebar').height() - $tocSelector.position().top - $('.post-toc-indicator-bottom').height(); $tocSelector.css('height', height); return height; } function toggleTOCOverflowIndicators () { tocOverflowIndicator( '.post-toc-indicator-top', $tocSelector.scrollTop() > 0 ? 'show' : 'hide' ); tocOverflowIndicator( '.post-toc-indicator-bottom', $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show' ) } $(document).on('sidebar.motion.complete', function () { processTOC(); }); $('body').scrollspy({ target: tocSelector }); $(window).on('resize', function () { if ( $('.sidebar').hasClass('sidebar-active') ) { processTOC(); } }); onScroll($tocSelector); function onScroll (element) { element.on('mousewheel DOMMouseScroll', function (event) { var oe = event.originalEvent; var delta = oe.wheelDelta || -oe.detail; this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30; event.preventDefault(); toggleTOCOverflowIndicators(); }); } function tocOverflowIndicator (indicator, action) { var $indicator = $(indicator); var opacity = action === 'show' ? 1 : 0; $indicator.velocity ? $indicator.velocity('stop').velocity({ opacity: opacity }, { duration: 100 }) : $indicator.stop().animate({ opacity: opacity }, 100); } }); </script> <script type="text/javascript" id="sidebar.nav"> $(document).ready(function () { var html = $('html'); var TAB_ANIMATE_DURATION = 200; var hasVelocity = $.isFunction(html.velocity); $('.sidebar-nav li').on('click', function () { var item = $(this); var activeTabClassName = 'sidebar-nav-active'; var activePanelClassName = 'sidebar-panel-active'; if (item.hasClass(activeTabClassName)) { return; } var currentTarget = $('.' + activePanelClassName); var target = $('.' + item.data('target')); hasVelocity ? currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () { target .velocity('stop') .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION) .addClass(activePanelClassName); }) : currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () { currentTarget.hide(); target .stop() .css({'opacity': 0, 'display': 'block'}) .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () { currentTarget.removeClass(activePanelClassName); target.addClass(activePanelClassName); }); }); item.siblings().removeClass(activeTabClassName); item.addClass(activeTabClassName); }); $('.post-toc a').on('click', function (e) { e.preventDefault(); var targetSelector = escapeSelector(this.getAttribute('href')); var offset = $(targetSelector).offset().top; hasVelocity ? html.velocity('stop').velocity('scroll', { offset: offset + 'px', mobileHA: false }) : $('html, body').stop().animate({ scrollTop: offset }, 500); }); // Expand sidebar on post detail page by default, when post has a toc. motionMiddleWares.sidebar = function () { var $tocContent = $('.post-toc-content'); if (CONFIG.sidebar === 'post') { if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) { displaySidebar(); } } }; }); </script> <script type="text/javascript" src="/js/bootstrap.js"></script> </body> </html>
wuxu92/wuxu92.github.io
vim-commands/index.html
HTML
mit
24,822
var map, boroughSearch = [], theaterSearch = [], museumSearch = []; /* Basemap Layers */ var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png"); var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png"); var mbTerrainReg = L.tileLayer("https://{s}.tiles.mapbox.com/v3/aj.um7z9lus/{z}/{x}/{y}.png"); var mapquestOAM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }); var mapquestHYB = L.layerGroup([L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }), L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/hyb/{z}/{x}/{y}.png", { maxZoom: 19, subdomains: ["oatile1", "oatile2", "oatile3", "oatile4"], })]); map = L.map("map", { zoom: 5, center: [39, -95], layers: [mapquestOSM] }); /* Larger screens get expanded layer control */ if (document.body.clientWidth <= 767) { var isCollapsed = true; } else { var isCollapsed = false; } var baseLayers = { "Street Map": mapquestOSM, "Aerial Imagery": mapquestOAM, "Imagery with Streets": mapquestHYB }; var overlays = {}; var layerControl = L.control.layers(baseLayers, {}, { collapsed: isCollapsed }).addTo(map); /* Add overlay layers to map after defining layer control to preserver order */ var sidebar = L.control.sidebar("sidebar", { closeButton: true, position: "left" }).addTo(map); sidebar.toggle(); /* Highlight search box text on click */ $("#searchbox").click(function () { $(this).select(); }); /* Placeholder hack for IE */ if (navigator.appName == "Microsoft Internet Explorer") { $("input").each(function () { if ($(this).val() === "" && $(this).attr("placeholder") !== "") { $(this).val($(this).attr("placeholder")); $(this).focus(function () { if ($(this).val() === $(this).attr("placeholder")) $(this).val(""); }); $(this).blur(function () { if ($(this).val() === "") $(this).val($(this).attr("placeholder")); }); } }); } $(function(){ var popup = { init : function() { // position popup windowW = $(window).width(); $("#map").on("mousemove", function(e) { var x = e.pageX + 20; var y = e.pageY; var windowH = $(window).height(); if (y > (windowH - 100)) { var y = e.pageY - 100; } else { var y = e.pageY - 20; } $("#info").css({ "left": x, "top": y }); }); } }; popup.init(); })
availabs/transit_analyst
assets/js/main.js
JavaScript
mit
2,596
# Jirabot A Slack bot that watches any channel it's invited to for mentions of JIRA issues. If it sees one, it responds with a message consisting of: ISSUE-1223: Issue summary https://yourlocation.jira.com/browse/ISSUE-1223 Issue Status (Issue Type) ## Setup You'll need to configure a bot on Slack (fixme: Add setup link) and get your API token. Once you have that, set a new environmental variable `SLACK_API_TOKEN`. Additionally, you'll need to supply JIRA credentials and your JIRA enpoint address. This is because JIRA cloud doesn't support app tokens. Yeah, in 2016 you have to use basic auth if your app doesn't run through a browser. For local development, you can do this with a `.env` file, which we've helpfully left out of this repo. # ENV Sample SLACK_API_TOKEN=yourtokengoeshere JIRA_USER=jirauser_notemail JIRA_PASS=jirapassword JIRA_PREFIX=https://yourcompany.jira.com/ ## Running Locally foreman start This will open your connection to the Slack API, and your bot will be online. You can connect to it and chat with it directly (it'll behave the same way).
calciphus/jirabot
README.md
Markdown
mit
1,107
# frozen_string_literal: true require 'spec_helper' describe ErrorTracking::ProjectErrorTrackingSetting do include ReactiveCachingHelpers set(:project) { create(:project) } subject { create(:project_error_tracking_setting, project: project) } describe 'Associations' do it { is_expected.to belong_to(:project) } end describe 'Validations' do context 'when api_url is over 255 chars' do before do subject.api_url = 'https://' + 'a' * 250 end it 'fails validation' do expect(subject).not_to be_valid expect(subject.errors.messages[:api_url]).to include('is too long (maximum is 255 characters)') end end context 'With unsafe url' do it 'fails validation' do subject.api_url = "https://replaceme.com/'><script>alert(document.cookie)</script>" expect(subject).not_to be_valid end end context 'presence validations' do using RSpec::Parameterized::TableSyntax valid_api_url = 'http://example.com/api/0/projects/org-slug/proj-slug/' valid_token = 'token' where(:enabled, :token, :api_url, :valid?) do true | nil | nil | false true | nil | valid_api_url | false true | valid_token | nil | false true | valid_token | valid_api_url | true false | nil | nil | true false | nil | valid_api_url | true false | valid_token | nil | true false | valid_token | valid_api_url | true end with_them do before do subject.enabled = enabled subject.token = token subject.api_url = api_url end it { expect(subject.valid?).to eq(valid?) } end end context 'URL path' do it 'fails validation with wrong path' do subject.api_url = 'http://gitlab.com/project1/something' expect(subject).not_to be_valid expect(subject.errors.messages[:api_url]).to include('path needs to start with /api/0/projects') end it 'passes validation with correct path' do subject.api_url = 'http://gitlab.com/api/0/projects/project1/something' expect(subject).to be_valid end end context 'non ascii chars in api_url' do before do subject.api_url = 'http://gitlab.com/api/0/projects/project1/something€' end it 'fails validation' do expect(subject).not_to be_valid end end end describe '#sentry_external_url' do let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' } before do subject.api_url = sentry_url end it 'returns the correct url' do expect(subject.class).to receive(:extract_sentry_external_url).with(sentry_url).and_call_original result = subject.sentry_external_url expect(result).to eq('https://sentrytest.gitlab.com/sentry-org/sentry-project') end end describe '#sentry_client' do it 'returns sentry client' do expect(subject.sentry_client).to be_a(Sentry::Client) end end describe '#list_sentry_issues' do let(:issues) { [:list, :of, :issues] } let(:opts) do { issue_status: 'unresolved', limit: 10 } end let(:result) do subject.list_sentry_issues(**opts) end context 'when cached' do let(:sentry_client) { spy(:sentry_client) } before do stub_reactive_cache(subject, issues, opts) synchronous_reactive_cache(subject) expect(subject).to receive(:sentry_client).and_return(sentry_client) end it 'returns cached issues' do expect(sentry_client).to receive(:list_issues).with(opts) .and_return(issues) expect(result).to eq(issues: issues) end end context 'when not cached' do it 'returns nil' do expect(subject).not_to receive(:sentry_client) expect(result).to be_nil end end end describe '#list_sentry_projects' do let(:projects) { [:list, :of, :projects] } let(:sentry_client) { spy(:sentry_client) } it 'calls sentry client' do expect(subject).to receive(:sentry_client).and_return(sentry_client) expect(sentry_client).to receive(:list_projects).and_return(projects) result = subject.list_sentry_projects expect(result).to eq(projects: projects) end end context 'slugs' do shared_examples_for 'slug from api_url' do |method, slug| context 'when api_url is correct' do before do subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug/' end it 'returns slug' do expect(subject.public_send(method)).to eq(slug) end end context 'when api_url is blank' do before do subject.api_url = nil end it 'returns nil' do expect(subject.public_send(method)).to be_nil end end end it_behaves_like 'slug from api_url', :project_slug, 'project-slug' it_behaves_like 'slug from api_url', :organization_slug, 'org-slug' end context 'names from api_url' do shared_examples_for 'name from api_url' do |name, titleized_slug| context 'name is present in DB' do it 'returns name from DB' do subject[name] = 'Sentry name' subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug' expect(subject.public_send(name)).to eq('Sentry name') end end context 'name is null in DB' do it 'titleizes and returns slug from api_url' do subject[name] = nil subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug' expect(subject.public_send(name)).to eq(titleized_slug) end it 'returns nil when api_url is incorrect' do subject[name] = nil subject.api_url = 'http://gitlab.com/api/0/projects/' expect(subject.public_send(name)).to be_nil end it 'returns nil when api_url is blank' do subject[name] = nil subject.api_url = nil expect(subject.public_send(name)).to be_nil end end end it_behaves_like 'name from api_url', :organization_name, 'Org Slug' it_behaves_like 'name from api_url', :project_name, 'Project Slug' end describe '.build_api_url_from' do it 'correctly builds api_url with slugs' do api_url = described_class.build_api_url_from( api_host: 'http://sentry.com/', organization_slug: 'org-slug', project_slug: 'proj-slug' ) expect(api_url).to eq('http://sentry.com/api/0/projects/org-slug/proj-slug/') end it 'correctly builds api_url without slugs' do api_url = described_class.build_api_url_from( api_host: 'http://sentry.com/', organization_slug: nil, project_slug: nil ) expect(api_url).to eq('http://sentry.com/api/0/projects/') end it 'does not raise exception with invalid url' do api_url = described_class.build_api_url_from( api_host: ':::', organization_slug: 'org-slug', project_slug: 'proj-slug' ) expect(api_url).to eq(':::') end end describe '#api_host' do context 'when api_url exists' do before do subject.api_url = 'https://example.com/api/0/projects/org-slug/proj-slug/' end it 'extracts the api_host from api_url' do expect(subject.api_host).to eq('https://example.com/') end end context 'when api_url is nil' do before do subject.api_url = nil end it 'returns nil' do expect(subject.api_url).to eq(nil) end end end end
axilleas/gitlabhq
spec/models/error_tracking/project_error_tracking_setting_spec.rb
Ruby
mit
7,804
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define({ "configText": "Ustaw tekst konfiguracyjny:", "generalSettings": { "tabTitle": "Ustawienia ogólne", "measurementUnitLabel": "Jednostka miary", "currencyLabel": "Symbol miary", "roundCostLabel": "Zaokrąglaj koszt", "projectOutputSettings": "Ustawienia wynikowe projektu", "typeOfProjectAreaLabel": "Typ obszaru projektu", "bufferDistanceLabel": "Odległość buforowania", "roundCostValues": { "twoDecimalPoint": "Dwa miejsca po przecinku", "nearestWholeNumber": "Najbliższa liczba całkowita", "nearestTen": "Najbliższa dziesiątka", "nearestHundred": "Najbliższa setka", "nearestThousand": "Najbliższe tysiące", "nearestTenThousands": "Najbliższe dziesiątki tysięcy" }, "projectAreaType": { "outline": "Obrys", "buffer": "Bufor" }, "errorMessages": { "currency": "Nieprawidłowa jednostka waluty", "bufferDistance": "Nieprawidłowa odległość buforowania", "outOfRangebufferDistance": "Wartość powinna być większa niż 0 i mniejsza niż lub równa 100" } }, "projectSettings": { "tabTitle": "Ustawienia projektu", "costingGeometrySectionTitle": "Zdefiniuj obszar geograficzny na potrzeby kalkulacji kosztów (opcjonalnie)", "costingGeometrySectionNote": "Uwaga: skonfigurowanie tej warstwy umożliwi użytkownikowi konfigurowanie równań kosztów szablonów obiektów na podstawie obszarów geograficznych.", "projectTableSectionTitle": "Możliwość zapisania/wczytania ustawień projektu (opcjonalnie)", "projectTableSectionNote": "Uwaga: skonfigurowanie wszystkich tabel i warstw umożliwi użytkownikowi zapisanie/wczytanie projektu w celu ponownego wykorzystania.", "costingGeometryLayerLabel": "Warstwa geometrii kalkulacji kosztów", "fieldLabelGeography": "Pole do oznaczenia etykietą obszaru geograficznego", "projectAssetsTableLabel": "Tabela zasobów projektu", "projectMultiplierTableLabel": "Tabela kosztów dodatkowych mnożnika projektu", "projectLayerLabel": "Warstwa projektu", "configureFieldsLabel": "Skonfiguruj pola", "fieldDescriptionHeaderTitle": "Opis pola", "layerFieldsHeaderTitle": "Pole warstwy", "selectLabel": "Zaznacz", "errorMessages": { "duplicateLayerSelection": "Warstwa ${layerName} jest już wybrana", "invalidConfiguration": "Należy wybrać wartość ${fieldsString}" }, "costingGeometryHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć możliwość wykonywania zapytania</li><li>\tWarstwa musi zawierać pole GlobalID</li></p>", "fieldToLabelGeographyHelp": "<p>Pola znakowe i liczbowe wybranej warstwy geometrii kalkulacji kosztów zostaną wyświetlone w menu rozwijanym Pole do oznaczenia etykietą obszaru geograficznego.</p>", "projectAssetsTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać sześć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tAssetGUID (pole typu GUID)</li><li>\tCostEquation (pole typu String)</li><li>\tScenario (pole typu String)</li><li>\tTemplateName (pole typu String)</li><li> GeographyGUID (pole typu GUID)</li><li>\tProjectGUID (pole typu GUID)</li></ul> </p>", "projectMultiplierTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tDescription (pole typu String)</li><li>\tType (pole typu String)</li><li>\tValue (pole typu Float/Double)</li><li>\tCostindex (pole typu Integer)</li><li> \tProjectGUID (pole typu GUID))</li></ul> </p>", "projectLayerHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>Warstwa musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Warstwa musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>ProjectName (pole typu String)</li><li>Description (pole typu String)</li><li>Totalassetcost (pole typu Float/Double)</li><li>Grossprojectcost (pole typu Float/Double)</li><li>GlobalID (pole typu GlobalID)</li></ul> </p>", "pointLayerCentroidLabel": "Centroid warstwy punktowej", "selectRelatedPointLayerDefaultOption": "Zaznacz", "pointLayerHintText": "<p>Zostaną wyświetlone warstwy punktowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć pole 'Projectid' (typ GUID)</li><li>\tWarstwa musi mieć możliwość edycji, a więc atrybut 'Tworzenie', 'Usuwanie' i 'Aktualizacja'</li></p>" }, "layerSettings": { "tabTitle": "Ustawienia warstwy", "layerNameHeaderTitle": "Nazwa warstwy", "layerNameHeaderTooltip": "Lista warstw na mapie", "EditableLayerHeaderTitle": "Edytowalne", "EditableLayerHeaderTooltip": "Dołącz warstwę i jej szablony w widżecie kalkulacji kosztów", "SelectableLayerHeaderTitle": "Podlegające selekcji", "SelectableLayerHeaderTooltip": "Geometria z obiektu może zostać użyta do wygenerowania nowego elementu kosztu", "fieldPickerHeaderTitle": "ID projektu (opcjonalnie)", "fieldPickerHeaderTooltip": "Pole opcjonalne (typu znakowego), w którym będzie przechowywany identyfikator projektu", "selectLabel": "Zaznacz", "noAssetLayersAvailable": "Nie znaleziono warstwy zasobów na wybranej mapie internetowej", "disableEditableCheckboxTooltip": "Ta warstwa nie ma możliwości edycji", "missingCapabilitiesMsg": "Dla tej warstwy brak następujących funkcji:", "missingGlobalIdMsg": "Ta warstwa nie ma pola GlobalId", "create": "Tworzenie", "update": "Aktualizuj", "delete": "Usuwanie", "attributeSettingHeaderTitle": "Ustawienia atrybutów", "addFieldLabelTitle": "Dodaj atrybuty", "layerAttributesHeaderTitle": "Atrybuty warstwy", "projectLayerAttributesHeaderTitle": "Atrybuty warstwy projektu", "attributeSettingsPopupTitle": "Ustawienia atrybutów warstwy" }, "costingInfo": { "tabTitle": "Informacje o kalkulacji kosztów", "proposedMainsLabel": "Proponowane elementy główne", "addCostingTemplateLabel": "Dodaj szablon kalkulacji kosztów", "manageScenariosTitle": "Zarządzaj scenariuszami", "featureTemplateTitle": "Szablon obiektu", "costEquationTitle": "Równanie kosztów", "geographyTitle": "Obszar geograficzny", "scenarioTitle": "Scenariusz", "actionTitle": "Działania", "scenarioNameLabel": "Nazwa scenariusza", "addBtnLabel": "Dodaj", "srNoLabel": "Nie.", "deleteLabel": "Usuwanie", "duplicateScenarioName": "Duplikuj nazwę scenariusza", "hintText": "<div>Wskazówka: użyj następujących słów kluczowych</div><ul><li><b>{TOTALCOUNT}</b>: używa łącznej liczby zasobów tego samego typu w obszarze geograficznym</li><li><b>{MEASURE}</b>: używa długości dla zasobu liniowego i pola powierzchni dla zasobu poligonowego</li><li><b>{TOTALMEASURE}</b>: używa łącznej długości dla zasobu liniowego i łącznego pola powierzchni dla zasobu poligonowego tego samego typu w obszarze geograficznym</li></ul> Możesz użyć funkcji, takich jak:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Należy zmodyfikować równanie kosztów zgodnie z wymaganiami projektu.", "noneValue": "Brak", "requiredCostEquation": "Niepoprawne równanie kosztów dla warstwy ${layerName} : ${templateName}", "duplicateTemplateMessage": "Istnieje podwójny wpis szablonu dla warstwy ${layerName} : ${templateName}", "defaultEquationRequired": "Wymagane jest domyślne równanie dla warstwy ${layerName} : ${templateName}", "validCostEquationMessage": "Wprowadź prawidłowe równanie kosztów", "costEquationHelpText": "Edytuj równanie kosztów zgodnie z wymaganiami projektu", "scenarioHelpText": "Wybierz scenariusz zgodnie z wymaganiami projektu", "copyRowTitle": "Kopiuj wiersz", "noTemplateAvailable": "Dodaj co najmniej jeden szablon dla warstwy ${layerName}", "manageScenarioLabel": "Zarządzaj scenariuszem", "noLayerMessage": "Wprowadź co najmniej jedną warstwę w ${tabName}", "noEditableLayersAvailable": "Warstwy, które należy oznaczyć jako możliwe do edycji na karcie ustawień warstwy", "updateProjectCostCheckboxLabel": "Aktualizuj równania projektu", "updateProjectCostEquationHint": "Wskazówka: Umożliwia użytkownikowi aktualizowanie równań kosztów zasobów, które zostały już dodane do istniejących projektów, za pomocą nowych równań zdefiniowanych niżej na podstawie szablonu obiektu, geografii i scenariusza. Jeśli brak określonej kombinacji, zostanie przyjęty koszt domyślny, tzn. geografia i scenariusz ma wartość 'None' (brak). W przypadku usunięcia szablonu obiektu ustawiony zostanie koszt równy 0." }, "statisticsSettings": { "tabTitle": "Dodatkowe ustawienia", "addStatisticsLabel": "Dodaj statystykę", "fieldNameTitle": "Pole", "statisticsTitle": "Etykieta", "addNewStatisticsText": "Dodaj nową statystykę", "deleteStatisticsText": "Usuń statystykę", "moveStatisticsUpText": "Przesuń statystykę w górę", "moveStatisticsDownText": "Przesuń statystykę w dół", "selectDeselectAllTitle": "Zaznacz wszystkie" }, "projectCostSettings": { "addProjectCostLabel": "Dodaj koszt dodatkowy projektu", "additionalCostValueColumnHeader": "Wartość", "invalidProjectCostMessage": "Nieprawidłowa wartość kosztu projektu", "additionalCostLabelColumnHeader": "Etykieta", "additionalCostTypeColumnHeader": "Typ" }, "statisticsType": { "countLabel": "Liczba", "averageLabel": "Średnia", "maxLabel": "Maksimum", "minLabel": "Minimum", "summationLabel": "Zsumowanie", "areaLabel": "Pole powierzchni", "lengthLabel": "Długość" } });
tmcgee/cmv-wab-widgets
wab/2.13/widgets/CostAnalysis/setting/nls/pl/strings.js
JavaScript
mit
10,828
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('commentator', 'Unit | Model | commentator', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function(assert) { let model = this.subject(); // let store = this.store(); assert.ok(!!model); });
morontt/zend-blog-3-backend
spa/tests/unit/models/commentator-test.js
JavaScript
mit
318
<?php /** * Created by PhpStorm. * User: Renfrid-Sacids * Date: 2/4/2016 * Time: 9:44 AM */ class Xform_model extends CI_Model { /** * Table name for xform definitions * * @var string */ private static $xform_table_name = "xforms"; //default value /** * Table name for archived/deleted xforms * * @var string */ private static $archive_xform_table_name = "archive_xformx"; //default value public function __construct() { $this->initialize_table(); } /** * Initializes table names from configuration files */ private function initialize_table() { if ($this->config->item("table_xform")) self::$xform_table_name = $this->config->item("table_xform"); if ($this->config->item("table_archive_xform")) self::$archive_xform_table_name = $this->config->item("table_archive_xform"); } /** * @param $statement * @return bool */ public function create_table($statement) { if ($this->db->simple_query($statement)) { log_message("debug", "Success!"); return TRUE; } else { $error = $this->db->error(); // Has keys 'code' and 'message' log_message("debug", $statement . ", error " . json_encode($error)); return FALSE; } } /** * @param $statement * @return bool */ public function insert_data($statement) { if ($this->db->simple_query($statement)) { log_message("debug", "Success!"); return TRUE; } else { $error = $this->db->error(); // Has keys 'code' and 'message' log_message("debug", $statement . ", error " . json_encode($error)); } } /** * @param $form_details an array of form details with keys match db field names * @return id for the created form */ public function create_xform($form_details) { $this->db->insert(self::$xform_table_name, $form_details); return $this->db->insert_id(); } /** * @param int xform_id the row that needs to be updated * @param string form_id * @return bool */ public function update_form_id($xform_id, $form_id) { $data = array('form_id' => $form_id); $this->db->where('id', $xform_id); return $this->db->update(self::$xform_table_name, $data); } /** * @param $form_id * @param $form_details * @return mixed */ public function update_form($form_id, $form_details) { $this->db->where('id', $form_id); return $this->db->update(self::$xform_table_name, $form_details); } /** * @param null $user_id * @param int $limit * @param int $offset * @return mixed returns list of forms available. */ public function get_form_list($user_id = NULL, $limit = 30, $offset = 0) { if ($user_id != NULL) $this->db->where("user_id", $user_id); $this->db->limit($limit, $offset); return $this->db->get(self::$xform_table_name)->result(); } /** * Finds a table field with point data type * * @param $table_name * @return field name or FALSE */ public function get_point_field($table_name) { $sql = " SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS "; $sql .= " WHERE table_name = '{$table_name}' "; $sql .= " AND DATA_TYPE = 'point'"; $query = $this->db->query($sql); return ($query->num_rows() == 1) ? $query->row(1)->COLUMN_NAME : FALSE; } /** * @param $form_id * @return mixed */ public function find_by_id($form_id) { $this->db->where("id", $form_id); return $this->db->get(self::$xform_table_name)->row(); } /** * @param $xform_id * @return mixed */ public function delete_form($xform_id) { $this->db->limit(1); $this->db->where("id", $xform_id); return $this->db->delete(self::$xform_table_name); } /** * @param $xform_archive_data * @return mixed */ public function create_archive($xform_archive_data) { return $this->db->insert(self::$archive_xform_table_name, $xform_archive_data); } /** * @param $table_name * @param int $limit * @param int $offset * @return mixed returns data from tables created by uploading xform definitions files. */ public function find_form_data($table_name, $limit = 30, $offset = 0) { $this->db->limit($limit, $offset); return $this->db->get($table_name)->result(); } /** * @param $table_name * @return mixed return an object of fields of the specified table */ public function find_table_columns($table_name) { return $this->db->list_fields($table_name); } /** * @param $table_name * @return mixed returns table fields/columns with metadata object */ public function find_table_columns_data($table_name) { return $this->db->field_data($table_name); } public function get_graph_data($table_name, $x_axis_column, $y_axis_column, $y_axis_action = "COUNT") { if ($y_axis_action == "COUNT") { $this->db->select("`" . $y_axis_column . "`, COUNT(" . $y_axis_column . ") AS `" . strtolower($y_axis_action) . "`"); $this->db->group_by($x_axis_column); } if ($y_axis_action == "SUM") { $this->db->select("`" . $y_axis_column . "`, SUM(" . $y_axis_column . ") AS `" . strtolower($y_axis_action) . "`"); $this->db->group_by($x_axis_column); } $this->db->from($table_name); return $this->db->get()->result(); } }
renfrid/dataManager
application/models/Xform_model.php
PHP
mit
5,088
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./c74afbe19e0f475e2fc44426785688aedfb48315daf39b05f2e65ff576c49dce.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/4a1e8638fe3dc0c69f0d71b8017fd613a193fee8e84ccd3df23b3056f9966334.html
HTML
mit
550
<!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <link rel="profile" href="http://gmpg.org/xfn/11"> <?php wp_head(); ?> </head> <body> <!-- Main navigation --> <?php do_action( 'omega_before_header' ); ?> <!-- Featured post --> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 col-sm-12 col-xs-12"> <div id="header-template"> </div> </div> </div> </div> <script type='template' id='headerTemplate'> <a href="<%- url %>"> <div class="header-feature"> <div class="header-mask"> <img class="header-mask-image" src="<%= thumbnail_images == 'undefined' ? 'http://placehold.it/350x150' : thumbnail_images.large.url %>" alt="<%- title %>"> </div> <div class="header-feature-text"> <h5> <%= custom_fields.participant %> </h5> <h1> <%= title %> </h1> </div> </div> </a> </script>
serpentinegalleries/radio-serpentine
header-home.php
PHP
mit
1,005
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use AppBundle\Entity\User; class registerType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('eMail', EmailType::class) ->add('password', RepeatedType::class, [ 'type' => PasswordType::class ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => User::class ]); } public function getBlockPrefix() { return 'app_bundleregister_type'; } }
Fabcra/bien_etre
src/AppBundle/Form/registerType.php
PHP
mit
962
/** ****************************************************************************** * @file CRYP/CRYP_TDESECBmode/stm32f4xx_it.c * @author MCD Application Team * @version V1.8.0 * @date 04-November-2016 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2016 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_it.h" /** @addtogroup STM32F4xx_StdPeriph_Examples * @{ */ /** @addtogroup CRYP_TDESECBmode * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f40xx.s/startup_stm32f427x.s/startup_stm32f429x.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
craftit/BMC2-Firmware
Firmware/ext/STM32F4xx_DSP_StdPeriph_Lib/Project/STM32F4xx_StdPeriph_Examples/CRYP/CRYP_TDESECBmode/stm32f4xx_it.c
C
mit
4,599
/* * This file is part of the Cliche project, licensed under MIT License. See LICENSE.txt file in root folder of Cliche * sources. */ package net.dudehook.cliche2.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * @author ASG */ public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> { private Map<K, List<V>> listMap; public ArrayHashMultiMap() { listMap = new HashMap<K, List<V>>(); } public ArrayHashMultiMap(MultiMap<K, V> map) { this(); putAll(map); } public void put(K key, V value) { List<V> values = listMap.get(key); if (values == null) { values = new ArrayList<V>(); listMap.put(key, values); } values.add(value); } public Collection<V> get(K key) { List<V> result = listMap.get(key); if (result == null) { result = new ArrayList<V>(); } return result; } public Set<K> keySet() { return listMap.keySet(); } public void remove(K key, V value) { List<V> values = listMap.get(key); if (values != null) { values.remove(value); if (values.isEmpty()) { listMap.remove(key); } } } public void removeAll(K key) { listMap.remove(key); } public int size() { int sum = 0; for (K key : listMap.keySet()) { sum += listMap.get(key).size(); } return sum; } public void putAll(MultiMap<K, V> map) { for (K key : map.keySet()) { for (V val : map.get(key)) { put(key, val); } } } @Override public String toString() { return listMap.toString(); } }
dudehook/Cliche2
src/main/java/net/dudehook/cliche2/util/ArrayHashMultiMap.java
Java
mit
2,003
const fs = require('fs') const { normalize, resolve, join, sep } = require('path') function getAppDir () { let dir = process.cwd() while (dir.length && dir[dir.length - 1] !== sep) { if (fs.existsSync(join(dir, 'quasar.conf.js'))) { return dir } dir = normalize(join(dir, '..')) } const { fatal } = require('./helpers/logger') fatal(`Error. This command must be executed inside a Quasar v1+ project folder.`) } const appDir = getAppDir() const cliDir = resolve(__dirname, '..') const srcDir = resolve(appDir, 'src') const pwaDir = resolve(appDir, 'src-pwa') const ssrDir = resolve(appDir, 'src-ssr') const cordovaDir = resolve(appDir, 'src-cordova') const capacitorDir = resolve(appDir, 'src-capacitor') const electronDir = resolve(appDir, 'src-electron') const bexDir = resolve(appDir, 'src-bex') module.exports = { cliDir, appDir, srcDir, pwaDir, ssrDir, cordovaDir, capacitorDir, electronDir, bexDir, resolve: { cli: dir => join(cliDir, dir), app: dir => join(appDir, dir), src: dir => join(srcDir, dir), pwa: dir => join(pwaDir, dir), ssr: dir => join(ssrDir, dir), cordova: dir => join(cordovaDir, dir), capacitor: dir => join(capacitorDir, dir), electron: dir => join(electronDir, dir), bex: dir => join(bexDir, dir) } }
rstoenescu/quasar-framework
app/lib/app-paths.js
JavaScript
mit
1,321
<?php require_once('config.php'); $session->requireLoggedIn(); require('design_head.php'); $text = ''; if (!empty($_POST['text'])) { $text = $_POST['text']; guessLanguage($text); } ?> <h2>Guess language</h2> Enter some text and see if the program can guess the language that the text were written in. <form method="post" action=""> <textarea name="text" cols="70" rows="20"></textarea><br/> <input type="submit" class="button" value="Submit"/> </form> <?php require('design_foot.php'); ?>
martinlindhe/core_dev
projects/lang/guess_language.php
PHP
mit
538
module.exports = { testClient: 'http://localhost:8089/dist/', mochaTimeout: 10000, testLayerIds: [0], seleniumTimeouts: { script: 5000, implicit: 1000, pageLoad: 5000 } }
KlausBenndorf/guide4you
tests/config.js
JavaScript
mit
193
'use strict'; import Maths from './maths.js' import FSM from './fsm.js' import { Animation, Interpolation } from './animation.js' export { Maths, FSM, Interpolation, Animation }
InconceivableVizzini/interjs
src/inter.js
JavaScript
mit
179
namespace Free.FileFormats.VRML.Interfaces { public interface IX3DTexturePropertiesNode { } }
shintadono/Free.FileFormats.VRML
18 Texturing/Interfaces/IX3DTexturePropertiesNode.cs
C#
mit
100
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #ifndef _GFXGLCUBEMAP_H_ #define _GFXGLCUBEMAP_H_ #ifndef _GFXCUBEMAP_H_ #include "gfx/gfxCubemap.h" #endif #ifndef __RESOURCE_H__ #include "core/resource.h" #endif class GFXGLCubemap : public GFXCubemap { public: GFXGLCubemap(); virtual ~GFXGLCubemap(); virtual void initStatic( GFXTexHandle *faces ); virtual void initStatic( DDSFile *dds ); virtual void initDynamic( U32 texSize, GFXFormat faceFormat = GFXFormatR8G8B8A8, U32 mipLevels = 0); virtual U32 getSize() const { return mWidth; } virtual GFXFormat getFormat() const { return mFaceFormat; } // Convenience methods for GFXGLTextureTarget U32 getWidth() { return mWidth; } U32 getHeight() { return mHeight; } U32 getHandle() { return mCubemap; } // GFXResource interface virtual void zombify(); virtual void resurrect(); /// Called by texCB; this is to ensure that all textures have been resurrected before we attempt to res the cubemap. void tmResurrect(); static GLenum getEnumForFaceNumber(U32 face) { return faceList[face]; } ///< Performs lookup to get a GLenum for the given face number protected: friend class GFXDevice; friend class GFXGLDevice; /// The callback used to get texture events. /// @see GFXTextureManager::addEventDelegate void _onTextureEvent( GFXTexCallbackCode code ); GLuint mCubemap; ///< Internal GL handle U32 mDynamicTexSize; ///< Size of faces for a dynamic texture (used in resurrect) // Self explanatory U32 mWidth; U32 mHeight; GFXFormat mFaceFormat; GFXTexHandle mTextures[6]; ///< Keep refs to our textures for resurrection of static cubemaps /// The backing DDSFile uses to restore the faces /// when the surface is lost. Resource<DDSFile> mDDSFile; // should only be called by GFXDevice virtual void setToTexUnit( U32 tuNum ); ///< Binds the cubemap to the given texture unit virtual void bind(U32 textureUnit) const; ///< Notifies our owning device that we want to be set to the given texture unit (used for GL internal state tracking) void fillCubeTextures(GFXTexHandle* faces); ///< Copies the textures in faces into the cubemap static GLenum faceList[6]; ///< Lookup table }; #endif
Azaezel/Torque3D
Engine/source/gfx/gl/gfxGLCubemap.h
C
mit
3,514
// Runs the wiki on port 80 var server = require('./server'); server.run(80);
rswingler/byuwiki
server/controller/js/wiki.js
JavaScript
mit
79
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "windows.h" #include "targetver.h" #include <string> // Headers for CppUnitTest //#include "CppUnitTest.h" // TODO: reference additional headers your program requires here
MagnusTiberius/terra.simulacra
mt/stdafx.h
C
mit
373
from datetime import datetime from zipfile import ZipFile from io import BytesIO from lxml import etree from docxgen import * from docxgen import nsmap from . import check_tag def test_init(): doc = Document() check_tag(doc.doc, ['document', 'body']) check_tag(doc.body, ['body']) def test_save(): doc = Document() tmp = BytesIO() doc.save(tmp) with ZipFile(tmp) as zippy: assert(zippy.testzip() is None) assert(set(zippy.namelist()) == set([ '[Content_Types].xml', '_rels/.rels', 'docProps/app.xml', 'word/fontTable.xml', 'word/numbering.xml', 'word/settings.xml', 'word/styles.xml', 'word/stylesWithEffects.xml', 'word/webSettings.xml', 'word/theme/theme1.xml', 'word/_rels/document.xml.rels', 'word/document.xml', 'docProps/core.xml' ])) zxf = zippy.open('word/document.xml') root = etree.parse(zxf) check_tag(root, 'document body'.split()) def test_load(): # assume save works d = Document() tmp = BytesIO() d.save(tmp) doc = Document.load(tmp) check_tag(doc.doc, 'document body'.split()) check_tag(doc.body, 'body'.split()) def test_dumps(): doc = Document() assert doc.dumps() def test_core_props(): doc = Document() attrs = dict(lastModifiedBy='Joe Smith', keywords=['egg', 'spam'], title='Testing Doc', subject='A boilerplate document', creator='Jill Smith', description='Core properties test.', created=datetime.now() ) doc.update(attrs) core = doc.get_core_props() for key in ('title', 'subject', 'creator', 'description'): attr = core.find('.//dc:%s' % key, namespaces=nsmap) assert attr is not None assert attr.text == attrs[key] attr = core.find('.//cp:keywords', namespaces=nsmap) assert attr is not None assert attr.text == ','.join(attrs['keywords']) attr = core.find('.//dcterms:created', namespaces=nsmap) assert attr is not None assert datetime.strptime(attr.text, '%Y-%m-%dT%H:%M:%SZ') == datetime(*attrs['created'].timetuple()[:6])
kunxi/docxgen
tests/test_docx.py
Python
mit
2,167
#!/bin/bash INSTALL_PATH=$PREFIX make shared_lib
Phelimb/cbg
.conda/rocksdb/build.sh
Shell
mit
50
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.commerce.customer.accounts; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.AsyncCallback; import java.util.concurrent.CountDownLatch; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Tenant administrators can add and view internal notes for a customer account. For example, a client can track a shopper's interests or complaints. Only clients can add and view notes. Shoppers cannot view these notes from the My Account page. * </summary> */ public class CustomerNoteClient { /** * Retrieves the contents of a particular note attached to a specified customer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=GetAccountNoteClient( accountId, noteId); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNote customerNote = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param noteId Unique identifier of a particular note to retrieve. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote> * @see com.mozu.api.contracts.customer.CustomerNote */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> getAccountNoteClient(Integer accountId, Integer noteId) throws Exception { return getAccountNoteClient( accountId, noteId, null); } /** * Retrieves the contents of a particular note attached to a specified customer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=GetAccountNoteClient( accountId, noteId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNote customerNote = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param noteId Unique identifier of a particular note to retrieve. * @param responseFields Use this field to include those fields which are not included by default. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote> * @see com.mozu.api.contracts.customer.CustomerNote */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> getAccountNoteClient(Integer accountId, Integer noteId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.getAccountNoteUrl(accountId, noteId, responseFields); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class; MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * Retrieves a list of notes added to a customer account according to any specified filter criteria and sort options. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> mozuClient=GetAccountNotesClient( accountId); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNoteCollection customerNoteCollection = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNoteCollection> * @see com.mozu.api.contracts.customer.CustomerNoteCollection */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> getAccountNotesClient(Integer accountId) throws Exception { return getAccountNotesClient( accountId, null, null, null, null, null); } /** * Retrieves a list of notes added to a customer account according to any specified filter criteria and sort options. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> mozuClient=GetAccountNotesClient( accountId, startIndex, pageSize, sortBy, filter, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNoteCollection customerNoteCollection = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true" * @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200. * @param responseFields Use this field to include those fields which are not included by default. * @param sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc" * @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNoteCollection> * @see com.mozu.api.contracts.customer.CustomerNoteCollection */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> getAccountNotesClient(Integer accountId, Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.getAccountNotesUrl(accountId, filter, pageSize, responseFields, sortBy, startIndex); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.customer.CustomerNoteCollection.class; MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * Adds a new note to the specified customer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=AddAccountNoteClient( note, accountId); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNote customerNote = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param note Properties of a note configured for a customer account. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote> * @see com.mozu.api.contracts.customer.CustomerNote * @see com.mozu.api.contracts.customer.CustomerNote */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> addAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId) throws Exception { return addAccountNoteClient( note, accountId, null); } /** * Adds a new note to the specified customer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=AddAccountNoteClient( note, accountId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNote customerNote = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param responseFields Use this field to include those fields which are not included by default. * @param note Properties of a note configured for a customer account. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote> * @see com.mozu.api.contracts.customer.CustomerNote * @see com.mozu.api.contracts.customer.CustomerNote */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> addAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.addAccountNoteUrl(accountId, responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class; MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(note); return mozuClient; } /** * Modifies an existing note for a customer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=UpdateAccountNoteClient( note, accountId, noteId); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNote customerNote = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param noteId Unique identifier of a particular note to retrieve. * @param note Properties of a note configured for a customer account. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote> * @see com.mozu.api.contracts.customer.CustomerNote * @see com.mozu.api.contracts.customer.CustomerNote */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> updateAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, Integer noteId) throws Exception { return updateAccountNoteClient( note, accountId, noteId, null); } /** * Modifies an existing note for a customer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=UpdateAccountNoteClient( note, accountId, noteId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * CustomerNote customerNote = client.Result(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param noteId Unique identifier of a particular note to retrieve. * @param responseFields Use this field to include those fields which are not included by default. * @param note Properties of a note configured for a customer account. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote> * @see com.mozu.api.contracts.customer.CustomerNote * @see com.mozu.api.contracts.customer.CustomerNote */ public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> updateAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, Integer noteId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.updateAccountNoteUrl(accountId, noteId, responseFields); String verb = "PUT"; Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class; MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(note); return mozuClient; } /** * Removes a note from the specified customer account. * <p><pre><code> * MozuClient mozuClient=DeleteAccountNoteClient( accountId, noteId); * client.setBaseAddress(url); * client.executeRequest(); * </code></pre></p> * @param accountId Unique identifier of the customer account. * @param noteId Unique identifier of a particular note to retrieve. * @return Mozu.Api.MozuClient */ public static MozuClient deleteAccountNoteClient(Integer accountId, Integer noteId) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.deleteAccountNoteUrl(accountId, noteId); String verb = "DELETE"; MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance(); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } }
lakshmi-nair/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/clients/commerce/customer/accounts/CustomerNoteClient.java
Java
mit
12,436
using System; using System.Linq; namespace CapnProto.Schema.Parser { class CapnpVisitor { protected Boolean mEnableNestedType = true; protected CapnpModule mActiveModule; protected void EnableNestedType() { mEnableNestedType = true; } protected void DisableNestedType() { mEnableNestedType = false; } public virtual CapnpType Visit(CapnpType target) { if (target == null) return null; return target.Accept(this); } protected internal virtual CapnpType VisitPrimitive(CapnpPrimitive primitive) { return primitive; } protected internal virtual CapnpType VisitList(CapnpList list) { list.Parameter = Visit(list.Parameter); return list; } protected internal virtual Value VisitValue(Value value) { return value; } protected internal virtual CapnpModule VisitModule(CapnpModule module) { // An imported module has already been processed. if (mActiveModule != null && mActiveModule != module) return module; mActiveModule = module; module.Structs = module.Structs.Select(s => VisitStruct(s)).ToArray(); module.Interfaces = module.Interfaces.Select(i => VisitInterface(i)).ToArray(); module.Constants = module.Constants.Select(c => VisitConst(c)).ToArray(); module.Enumerations = module.Enumerations.Select(e => VisitEnum(e)).ToArray(); module.AnnotationDefs = module.AnnotationDefs.Select(a => VisitAnnotationDecl(a)).ToArray(); module.Usings = module.Usings.Select(u => VisitUsing(u)).ToArray(); module.Annotations = module.Annotations.Select(a => VisitAnnotation(a)).ToArray(); return module; } protected internal virtual Annotation VisitAnnotation(Annotation annotation) { if (annotation == null) return null; annotation.Declaration = Visit(annotation.Declaration); annotation.Argument = VisitValue(annotation.Argument); return annotation; } protected internal virtual CapnpStruct VisitStruct(CapnpStruct @struct) { if (!mEnableNestedType) return @struct; @struct.Structs = @struct.Structs.Select(s => VisitStruct(s)).ToArray(); @struct.Interfaces = @struct.Interfaces.Select(i => VisitInterface(i)).ToArray(); DisableNestedType(); @struct.Enumerations = @struct.Enumerations.Select(e => VisitEnum(e)).ToArray(); @struct.Fields = @struct.Fields.Select(f => VisitField(f)).ToArray(); @struct.AnnotationDefs = @struct.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray(); @struct.Annotations = @struct.Annotations.Select(a => VisitAnnotation(a)).ToArray(); @struct.Usings = @struct.Usings.Select(u => VisitUsing(u)).ToArray(); @struct.Constants = @struct.Constants.Select(c => VisitConst(c)).ToArray(); EnableNestedType(); return @struct; } protected internal virtual CapnpInterface VisitInterface(CapnpInterface @interface) { if (!mEnableNestedType) return @interface; @interface.Structs = @interface.Structs.Select(s => VisitStruct(s)).ToArray(); @interface.Interfaces = @interface.Interfaces.Select(i => VisitInterface(i)).ToArray(); DisableNestedType(); @interface.Enumerations = @interface.Enumerations.Select(e => VisitEnum(e)).ToArray(); @interface.BaseInterfaces = @interface.BaseInterfaces.Select(i => Visit(i)).ToArray(); @interface.AnnotationDefs = @interface.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray(); @interface.Annotations = @interface.Annotations.Select(a => VisitAnnotation(a)).ToArray(); @interface.Methods = @interface.Methods.Select(m => VisitMethod(m)).ToArray(); @interface.Usings = @interface.Usings.Select(u => VisitUsing(u)).ToArray(); @interface.Constants = @interface.Constants.Select(c => VisitConst(c)).ToArray(); EnableNestedType(); return @interface; } protected internal virtual CapnpGenericParameter VisitGenericParameter(CapnpGenericParameter @param) { return @param; } protected internal virtual CapnpBoundGenericType VisitClosedType(CapnpBoundGenericType closed) { closed.OpenType = (CapnpNamedType)Visit(closed.OpenType); if (closed.ParentScope != null) closed.ParentScope = VisitClosedType(closed.ParentScope); return closed; } protected internal virtual CapnpEnum VisitEnum(CapnpEnum @enum) { @enum.Annotations = @enum.Annotations.Select(a => VisitAnnotation(a)).ToArray(); @enum.Enumerants = @enum.Enumerants.Select(e => VisitEnumerant(e)).ToArray(); return @enum; } protected internal virtual Enumerant VisitEnumerant(Enumerant e) { e.Annotation = VisitAnnotation(e.Annotation); return e; } protected internal virtual Field VisitField(Field fld) { fld.Type = Visit(fld.Type); fld.Value = VisitValue(fld.Value); fld.Annotation = VisitAnnotation(fld.Annotation); return fld; } protected internal virtual Method VisitMethod(Method method) { if (method.Arguments.Params != null) method.Arguments.Params = method.Arguments.Params.Select(p => VisitParameter(p)).ToArray(); else method.Arguments.Struct = Visit(method.Arguments.Struct); if (method.ReturnType.Params != null) method.ReturnType.Params = method.ReturnType.Params.Select(p => VisitParameter(p)).ToArray(); else method.ReturnType.Struct = Visit(method.ReturnType.Struct); method.Annotation = VisitAnnotation(method.Annotation); return method; } protected internal virtual Parameter VisitParameter(Parameter p) { p.Type = Visit(p.Type); p.Annotation = VisitAnnotation(p.Annotation); p.DefaultValue = VisitValue(p.DefaultValue); return p; } protected internal virtual CapnpGroup VisitGroup(CapnpGroup grp) { grp.Fields = grp.Fields.Select(f => VisitField(f)).ToArray(); return grp; } protected internal virtual CapnpUnion VisitUnion(CapnpUnion union) { union.Fields = union.Fields.Select(u => VisitField(u)).ToArray(); return union; } protected internal virtual CapnpType VisitReference(CapnpReference @ref) { return @ref; } protected internal virtual CapnpConst VisitConst(CapnpConst @const) { @const.Value = VisitValue(@const.Value); return @const; } protected internal virtual CapnpType VisitImport(CapnpImport import) { import.Type = Visit(import.Type); return import; } protected internal virtual CapnpUsing VisitUsing(CapnpUsing @using) { @using.Target = Visit(@using.Target); return @using; } protected internal virtual CapnpAnnotation VisitAnnotationDecl(CapnpAnnotation annotation) { annotation.ArgumentType = Visit(annotation.ArgumentType); return annotation; } } }
tempbottle/capnproto-net
CapnProto.net.Schema/Parser/CapnpVisitor.cs
C#
mit
7,402
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'rake' require 'rake/tasklib' require 'redmine_plugin_support/redmine_helper' require 'redmine_plugin_support/general_task' require 'redmine_plugin_support/environment_task' require 'redmine_plugin_support/database_task' require 'redmine_plugin_support/cucumber_task' require 'redmine_plugin_support/metrics_task' require 'redmine_plugin_support/rdoc_task' require 'redmine_plugin_support/release_task' require 'redmine_plugin_support/rspec_task' require 'redmine_plugin_support/stats_task' require 'redmine_plugin_support/test_unit_task' module RedminePluginSupport VERSION = '0.0.4' @@options = { } class Base include Singleton attr_accessor :project_name attr_accessor :tasks attr_accessor :plugin_root attr_accessor :redmine_root attr_accessor :default_task attr_accessor :plugin # :plugin_root => File.expand_path(File.dirname(__FILE__)) def self.setup(options = { }, &block) plugin = self.instance plugin.project_name = 'undefined' plugin.tasks = [:db, :doc, :spec, :cucumber, :release, :clean, :test, :stats] plugin.plugin_root = '.' plugin.redmine_root = ENV["REDMINE_ROOT"] || File.expand_path(File.dirname(__FILE__) + '/../../../') plugin.default_task = :doc plugin.instance_eval(&block) RedminePluginSupport::EnvironmentTask.new(:environment) plugin.tasks.each do |task| case task when :db RedminePluginSupport::DatabaseTask.new(:db) when :doc RedminePluginSupport::RDocTask.new(:doc) when :spec RedminePluginSupport::RspecTask.new(:spec) when :test RedminePluginSupport::TestUnitTask.new(:test) when :cucumber RedminePluginSupport::CucumberTask.new(:features) when :release RedminePluginSupport::ReleaseTask.new(:release) when :stats RedminePluginSupport::StatsTask.new(:stats) when :metrics RedminePluginSupport::MetricsTask.new(:metrics) when :clean require 'rake/clean' CLEAN.include('**/semantic.cache', "**/#{plugin.project_name}.zip", "**/#{plugin.project_name}.tar.gz") end end task :default => plugin.default_task end end end
edavis10/redmine_plugin_support
lib/redmine_plugin_support.rb
Ruby
mit
2,419
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>Nitrogen 2.x Documentation</title> <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/> <meta name="title" content="Nitrogen 2.x Documentation"/> <meta name="generator" content="Org-mode"/> <meta name="generated" content="2012-10-31 21:51:19 CDT"/> <meta name="author" content="Rusty Klophaus (@rustyio)"/> <meta name="description" content=""/> <meta name="keywords" content=""/> <style type="text/css"> <!--/*--><![CDATA[/*><!--*/ html { font-family: Times, serif; font-size: 12pt; } .title { text-align: center; } .todo { color: red; } .done { color: green; } .tag { background-color: #add8e6; font-weight:normal } .target { } .timestamp { color: #bebebe; } .timestamp-kwd { color: #5f9ea0; } .right {margin-left:auto; margin-right:0px; text-align:right;} .left {margin-left:0px; margin-right:auto; text-align:left;} .center {margin-left:auto; margin-right:auto; text-align:center;} p.verse { margin-left: 3% } pre { border: 1pt solid #AEBDCC; background-color: #F3F5F7; padding: 5pt; font-family: courier, monospace; font-size: 90%; overflow:auto; } table { border-collapse: collapse; } td, th { vertical-align: top; } th.right { text-align:center; } th.left { text-align:center; } th.center { text-align:center; } td.right { text-align:right; } td.left { text-align:left; } td.center { text-align:center; } dt { font-weight: bold; } div.figure { padding: 0.5em; } div.figure p { text-align: center; } div.inlinetask { padding:10px; border:2px solid gray; margin:10px; background: #ffffcc; } textarea { overflow-x: auto; } .linenr { font-size:smaller } .code-highlighted {background-color:#ffff00;} .org-info-js_info-navigation { border-style:none; } #org-info-js_console-label { font-size:10px; font-weight:bold; white-space:nowrap; } .org-info-js_search-highlight {background-color:#ffff00; color:#000000; font-weight:bold; } /*]]>*/--> </style> <LINK href="stylesheet.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> <!--/*--><![CDATA[/*><!--*/ function CodeHighlightOn(elem, id) { var target = document.getElementById(id); if(null != target) { elem.cacheClassElem = elem.className; elem.cacheClassTarget = target.className; target.className = "code-highlighted"; elem.className = "code-highlighted"; } } function CodeHighlightOff(elem, id) { var target = document.getElementById(id); if(elem.cacheClassElem) elem.className = elem.cacheClassElem; if(elem.cacheClassTarget) target.className = elem.cacheClassTarget; } /*]]>*///--> </script> </head> <body> <div id="preamble"> </div> <div id="content"> <h1 class="title">Nitrogen 2.x Documentation</h1> <p><a href="./index.html">Getting Started</a> | <a href="./api.html">API</a> | <a href="./elements.html">Elements</a> | <b>Actions</b> | <a href="./validators.html">Validators</a> | <a href="./handlers.html">Handlers</a> | <a href="./config.html">Configuration Options</a> | <a href="./about.html">About</a> </p> <div class=headline>Nitrogen Actions</div> <div id="table-of-contents"> <h2>Table of Contents</h2> <div id="text-table-of-contents"> <ul> <li><a href="#sec-1">1 Base Action</a></li> <li><a href="#sec-2">2 Page Manipulation</a></li> <li><a href="#sec-3">3 Effects</a></li> <li><a href="#sec-4">4 Feedback</a></li> <li><a href="#sec-5">5 See Also</a></li> </ul> </div> </div> <div id="outline-container-1" class="outline-2"> <h2 id="sec-1"><span class="section-number-2">1</span> Base Action</h2> <div class="outline-text-2" id="text-1"> <ul> <li><a href="./actions/base.html">Base Action</a> - All actions contain these attributes. </li> </ul> </div> </div> <div id="outline-container-2" class="outline-2"> <h2 id="sec-2"><span class="section-number-2">2</span> Page Manipulation</h2> <div class="outline-text-2" id="text-2"> <ul> <li><a href="./actions/event.html">Event</a> </li> <li><a href="./actions/script.html">Script</a> </li> <li><a href="./actions/validate.html">Validate</a> </li> <li><a href="./actions/clear_validation.html">Clear Validation</a> </li> <li><a href="./actions/api.html">Ajax API</a> </li> </ul> </div> </div> <div id="outline-container-3" class="outline-2"> <h2 id="sec-3"><span class="section-number-2">3</span> Effects</h2> <div class="outline-text-2" id="text-3"> <ul> <li><a href="./actions/show.html">Show</a> </li> <li><a href="./actions/hide.html">Hide</a> </li> <li><a href="./actions/appear.html">Appear</a> </li> <li><a href="./actions/fade.html">Fade</a> </li> <li><a href="./actions/slide_down.html">Slide Down</a> </li> <li><a href="./actions/slide_up.html">Slide Up</a> </li> <li><a href="./actions/animate.html">Animate</a> </li> <li><a href="./actions/toggle.html">Toggle</a> </li> <li><a href="./actions/effect.html">Effect</a> </li> <li><a href="./actions/add_class.html">Add Class</a> </li> <li><a href="./actions/remove_class.html">Remove Class</a> </li> <li><a href="./actions/disable.html">Disable</a> </li> </ul> </div> </div> <div id="outline-container-4" class="outline-2"> <h2 id="sec-4"><span class="section-number-2">4</span> Feedback</h2> <div class="outline-text-2" id="text-4"> <ul> <li><a href="./actions/alert.html">Alert</a> </li> <li><a href="./actions/confirm.html">Confirm</a> </li> <li><a href="./actions/other.html">Other</a> </li> </ul> </div> </div> <div id="outline-container-5" class="outline-2"> <h2 id="sec-5"><span class="section-number-2">5</span> See Also</h2> <div class="outline-text-2" id="text-5"> <ul> <li><a href="./paths.html">Nitrogen Element Paths</a> </li> </ul> </div> </div> </div> <div id="postamble"> <p class="date">Date: 2012-10-31 21:51:19 CDT</p> <p class="author">Author: Rusty Klophaus (@rustyio)</p> <p class="creator">Org version 7.8.02 with Emacs version 23</p> <a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a> </div><h2>Comments</h2> <b>Note:</b><!-- Disqus does not currently support Erlang for its syntax highlighting, so t-->To specify <!--Erlang--> code blocks, just use the generic code block syntax: <pre><b>&lt;pre&gt;&lt;code&gt;your code here&lt;/code&gt;&lt;/pre&gt;</b></pre> <br /> <br /> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'nitrogenproject'; // required: replace example with your forum shortname var disqus_identifier = 'html/actions.html'; //This will be replaced with the path part of the url /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> </body> </html>
jpyle/nitrogen_core
doc/html/actions.html
HTML
mit
7,516
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MultiMiner.Update")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MultiMiner.Update")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d18592f7-b2be-41cb-9f51-a5d6bd6563c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("4.2.3.379")] [assembly: AssemblyVersion("4.2.3.379")] [assembly: AssemblyFileVersion("4.2.3.379")]
nwoolls/MultiMiner
MultiMiner.Update/Properties/AssemblyInfo.cs
C#
mit
1,454
.dividend-wrap { display: none; } .dividend-wrap.active { display: flex; width: 100%; } .overflow.dividendModal > form input::-webkit-input-placeholder { /* Chrome/Opera/Safari */ opacity: .8; color: #fff; font-size: 14px; } .overflow.dividendModal > form input::-moz-placeholder { /* Firefox 19+ */ opacity: .8; color: #fff; font-size: 14px; } .overflow.dividendModal > form input:-moz-placeholder { /* Firefox 18- */ opacity: .8; color: #fff; font-size: 14px; } .overflow.dividendModal > form input:-ms-input-placeholder { /* IE 10+ */ opacity: .8; color: #fff; font-size: 14px; }
safex/safex_wallet
public/css/dividend-modal.css
CSS
mit
612
package pipe.actions.gui; import pipe.controllers.PetriNetController; import pipe.controllers.PlaceController; import uk.ac.imperial.pipe.models.petrinet.Connectable; import uk.ac.imperial.pipe.models.petrinet.Place; import java.awt.event.MouseEvent; import java.util.Map; /** * Abstract action responsible for adding and deleting tokens to places */ public abstract class TokenAction extends CreateAction { /** * * @param name image name * @param tooltip tooltip message * @param key keyboard shortcut * @param modifiers keyboard accelerator * @param applicationModel current PIPE application model */ public TokenAction(String name, String tooltip, int key, int modifiers, PipeApplicationModel applicationModel) { super(name, tooltip, key, modifiers, applicationModel); } /** * Noop action when a component has not been clicked on * @param event mouse event * @param petriNetController controller for the petri net */ @Override public void doAction(MouseEvent event, PetriNetController petriNetController) { // Do nothing unless clicked a connectable } /** * Performs the subclass token action on the place * @param connectable item clicked * @param petriNetController controller for the petri net */ @Override public void doConnectableAction(Connectable connectable, PetriNetController petriNetController) { //TODO: Maybe a method, connectable.containsTokens() or visitor pattern if (connectable instanceof Place) { Place place = (Place) connectable; String token = petriNetController.getSelectedToken(); performTokenAction(petriNetController.getPlaceController(place), token); } } /** * Subclasses should perform their relevant action on the token e.g. add/delete * * @param placeController * @param token */ protected abstract void performTokenAction(PlaceController placeController, String token); /** * Sets the place to contain counts. * <p/> * Creates a new history edit * * @param placeController * @param counts */ protected void setTokenCounts(PlaceController placeController, Map<String, Integer> counts) { placeController.setTokenCounts(counts); } }
frig-neutron/PIPE
pipe-gui/src/main/java/pipe/actions/gui/TokenAction.java
Java
mit
2,378
--- layout: page title: Adding Atom to Your Dotfiles --- Keeping all your dotfiles and system configurations together, under version control, and stored somewhere accessible (say on GitHub) is a good practice. It allows you to easily access and install everything from bash/zsh settings to environment variables to git aliases (and more) across all your machines. Plus others can use clever bits and pieces from your dotfiles in their own. Why not include your Atom files (those in `~/.atom`) in all of this? If you don't know what dotfiles are or you don't already have your own dotfiles setup, [GitHub can help get you up to speed](http://dotfiles.github.io/). ## What to include We recommend that you store `config.cson`, `init.coffee`, `keymap.cson`, `snippets.cson`, and `styles.less` in your dotfiles. The `packages/` and `storage/` directories should not be included. In fact you will even want to add them to your `.gitignore` file. ## How to include them There are as many ways to include these in your dotfiles as there are ways to setup your dotfiles. We are not going to go through all of them here. A common approach to having a dotfile configuration installed is with symlinks. This is the approach we will discuss. First, figure out the naming scheme for directories that is used by your installation script. It is likely either `directory.symlink` or `.directory`. Move the `~/.atom` directory to your dotfiles directory renaming it according to the appropriate naming scheme. For example, mv ~/.atom ~/.dotfiles/atom.symlink Following the naming scheme is important because that is the basis on which your installation script will decide what to symlink. Now test out that things are working properly. Run your installation script and then check if there again exists `~/.atom`. If you run `ls -la ~` you should be able to see if it is there. You will also notice that it tells you the directory that it is symlinked to. Success. You can now commit the files we discussed above to your dotfiles repository. At this point you should be all set and ready to go. ## Concerns You may be wondering if there is any risk in committing certain data from `config.cson` to a public repository. Values like the `userId` values under `exception-reporting` and `metric` might look like they contain sensitive information. Fortunately, these are hashed values that won't reveal anything sensitive ([exception-reporting source](https://github.com/atom/exception-reporting/issues/7), [metrics source](https://github.com/atom/metrics/issues/18)). In other words, you should be able to commit that file as is.
jbranchaud/splitting-atoms
adding-atom-to-dotfiles.md
Markdown
mit
2,626
var Type = require("@kaoscript/runtime").Type; module.exports = function(expect) { class Shape { constructor() { this.__ks_init(); this.__ks_cons(arguments); } __ks_init_0() { this._color = ""; } __ks_init() { Shape.prototype.__ks_init_0.call(this); } __ks_cons_0(color) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(color === void 0 || color === null) { throw new TypeError("'color' is not nullable"); } else if(!Type.isString(color)) { throw new TypeError("'color' is not of type 'String'"); } this._color = color; } __ks_cons(args) { if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } __ks_func_color_0() { return this._color; } color() { if(arguments.length === 0) { return Shape.prototype.__ks_func_color_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } __ks_func_draw_0() { return "I'm drawing a " + this._color + " rectangle."; } draw() { if(arguments.length === 0) { return Shape.prototype.__ks_func_draw_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } } Shape.prototype.__ks_cons_1 = function() { this._color = "red"; }; Shape.prototype.__ks_cons = function(args) { if(args.length === 0) { Shape.prototype.__ks_cons_1.apply(this); } else if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } let shape = new Shape(); expect(shape.draw()).to.equals("I'm drawing a red rectangle."); };
kaoscript/kaoscript
test/fixtures/compile/implement/implement.ctor.nseal.alias.js
JavaScript
mit
1,741
module TasksFileMutations AddFilesToTask = GraphQL::Relay::Mutation.define do name 'AddFilesToTask' input_field :id, !types.ID return_field :task, TaskType resolve -> (_root, inputs, ctx) { task = GraphqlCrudOperations.object_from_id_if_can(inputs['id'], ctx['ability']) files = [ctx[:file]].flatten.reject{ |f| f.blank? } if task.is_a?(Task) && !files.empty? task.add_files(files) end { task: task } } end RemoveFilesFromTask = GraphQL::Relay::Mutation.define do name 'RemoveFilesFromTask' input_field :id, !types.ID input_field :filenames, types[types.String] return_field :task, TaskType resolve -> (_root, inputs, ctx) { task = GraphqlCrudOperations.object_from_id_if_can(inputs['id'], ctx['ability']) filenames = inputs['filenames'] if task.is_a?(Task) && !filenames.empty? task.remove_files(filenames) end { task: task } } end end
meedan/check-api
app/graph/mutations/tasks_file_mutations.rb
Ruby
mit
972
package uk.co.nevarneyok.entities.product; import com.google.gson.annotations.SerializedName; public class ProductSize { private long id; @SerializedName("remote_id") private long remoteId; private String value; public ProductSize() { } public ProductSize(long id, long remoteId, String value) { this.id = id; this.remoteId = remoteId; this.value = value; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getRemoteId() { return remoteId; } public void setRemoteId(long remoteId) { this.remoteId = remoteId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProductSize that = (ProductSize) o; if (id != that.id) return false; if (remoteId != that.remoteId) return false; return !(value != null ? !value.equals(that.value) : that.value != null); } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (int) (remoteId ^ (remoteId >>> 32)); result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public String toString() { return "ProductSize{" + "id=" + id + ", remoteId=" + remoteId + ", value='" + value + '\'' + '}'; } }
tugrulkarakaya/NeVarNeYok
app/src/main/java/uk/co/nevarneyok/entities/product/ProductSize.java
Java
mit
1,689
# -*- coding: utf-8 -*- """ 将json文件中的数据存到数据库中 """ import requests import json import os from word.models import (Word, EnDefinition, CnDefinition, Audio, Pronunciation, Example, Note) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(BASE_DIR) def process_data(data): data = data['data']['reviews'] print('len', len(data)) for item in data: content = item['content'] print('uk_audio', item['uk_audio']) print('us_audio', item['us_audio']) obj = Word.objects.create(content=content) if item['uk_audio']: uk_audio_filepath = save_files('uk', item['content'], item['uk_audio']) if item['us_audio']: us_audio_filepath = save_files('us', item['content'], item['us_audio']) if filepath is not None: pass Audio.objects.create(word=obj, us_audio=us_audio_filepath, uk_audio=uk_audio_filepath) def save_files(tp, word, url): filepath = '%s/media/audio/%stp/%s.mp3' % (BASE_DIR, tp, word) with open(BASE_DIR + '/media/audio/'+ tp +'/'+word+'.mp3', 'wb') as handle: response = requests.get(url, stream=True) if response.ok: # Something went wrong for block in response.iter_content(1024): handle.write(block) return filepath return None def serialize_data(file_name): """ """ with open(file_name, 'r') as f: data = json.loads(f.read()) process_data(data) # data = requests.get('', stream=True) if __name__ == "__main__": serialize_data("data1.json")
HideMode/ShanBay
data/script.py
Python
mit
1,642
--- layout: post title: All Roads Lead to Shenzhen (for Electronics) excerpt: "An account of my first visit to Shenzhen, China - the modern day Mecca of electronics manufacturing." tags: [electronics, Shenzhen, China] categories: [Electronics] comments: true modified: 2015-01-17 thumbnail: images/2016/01/shenzhen-bldg.jpg images: images/2016/01/shenzhen-bldg.jpg image: feature: header.jpg --- *This is a brief account of my four day visit in January 2016 to Shenzhen, China. Due to my unfamiliarity with the language and brevity of the trip, this is only a superficial perspective.* ![Shenzhen](/images/2016/01/shenzhen-bldg.jpg) ## Why Shenzhen? If you are doing anything related to electronics today, you will come to know about Shenzhen soon enough. In my case, [snapVCC][1], a product that I succesfully crowd-funded recently, brought me here. Although it was not a requirement for me to be present here for production, I decided to make the trip to get a feel for the place - especially considering future projects. ## Getting There Here's a brief overview of the formalities involved in getting to Shenzhen - from an Indian point of view. ### Chinese Visa I applied for a visa through a travel agent in Bangalore, since the Chinese consulate is in Mumbai. The visa fee was INR 8000 (plus the travel agent charged a small fee). I applied for a *business* visa, and the only supporting docunent I needed was an invitation letter from Seeed Studio, the company that's manufacturing my product in Shenzhen. I got the visa in hand in about a week - a single entry visa valid for three months. ### Tickets When I asked around, I was advised to fly to Hong Kong and take ground transportation rather than fly directly to Shenzhen. Ticket prices from Bangalore to Shenzhen ranged from around INR 25000 to 35000, depending on airlines, dates and stop-overs. I opted for a direct flight - a five hour journey. I think you can do it on the cheap if you don't mind breaking your journey and are flexible with dates. ### Currency The currency in China is Chinese Yuan (CNY), but it's more commonly referred to with its older name RMB. A quick approximate conversion to INR is to just multiply CNY by 10. I took USD from India and converted it in Hong Kong. The conversion rate of Hong Kong Dollar to INR is about 7.5 at the moment. ### Crossing from Hong Kong Immigration at Hong Kong was straightforward. I just needed to fill a form, and there was no visa as such for short visits from India. I then collected my luggage and followed the "transport to mainland" signs. I opted for a "limo service" which is actually a shared taxi. I had my Shenzhen hotel address printed in Chinese characters (using google Translate), so all I had to is point to it, and pay 200 HKD at the counter. They slapped a sticker on to my jacket (which probably said "illiterate man") and I was handed over to an attendant who shooed me towards the taxi gates. From then on, I was in "point and sign" mode. ![Shenzhen](/images/2016/01/shenzhen-hk-crossing.jpg) The "limo" was actually a van which takes a driver plus seven passengers. I was wedged between two passengers in the middle row. After my initial bewildrement, I had a nice conversation (in English) with the fellow to my left - an Engineer from Taiwan who worked for Foxconn. The driver provided us with yellow immigration forms to fill, and in less than hour, we were at the border. We first passed through the Hong Kong gates, and then the Chinese gates. In both cases, we did not need to get out of the car. The officers just inspected out passports and peered into the car which had the interiors lighst on and the doors open. The taxis all had their trunks open, but in our case atleast, there was no inspection. Once we crossed the Chinese border, the taxi went into a mall where passengers were switched to other cars based on their Shenzhen destinations. In another 20 minutes, I was dropped off at my hotel. ### Hotel I wanted to stay close to the electronics markets, and I (mostly by accident) ended up choosing the Shenzhen Shanghai Hotel, which was at a walking distance to the Huaqiangbei markets. The cost of the room was about 500 RMB per night, which did not include a meal plan. My room was nice and cozy and the service in general was good. The buffet breakfast was atrociously bad, though. Definitely not worth the 75 RMB charge. ## Shenzhen Shenzhen is one of China's first Special Economic Zones set up in the 1980s and has grown to become the world's destination for electronics manufacturing. Shenzhen is a huge city, and I visited only parts of Futian, Nanshan, and Luohu districts during my stay. ### Getting Around ![Shenzhen](/images/2016/01/shenzhen-metro.jpg) You can get around Shenzhen in a taxi, but using the metro or bus is much cheaper. I used the metro, and found it to be very convenient. You can buy subway tokens at all stations, and the main menu has an English option which you can use. The machines I saw accepted only 5 Yuan notes or coins. A better option (which I plan to try next time) is to buy a *Shenzhen Tong Card* - a prepaid card that be used for both the bus and the metro. If you do take a taxi, ask for a *fa-piao* - a "tax receipt" - this apparently reduces the chance that you will be overcharged for the trip. ### Food Being a vegetarian (not vegan) my expectation was that I was screwed in China as far food goes. But this was actually not the case. ![Shenzhen](/images/2016/01/shenzhen-food.jpg) As long as I was with someone who could speak Mandarin, I got excellent vegetarian food. Left to myself, I exercised my pathetic point and mime skills, and usually ended up with weird stuff like tentacles on noodles. But even then I was always able to drown my (temporary) sorrow in a bottle of Tsingtao and some fried Tofu. I had learned the phrases *wo chi su* (I eat vegetables.) and *wo bu chi roe* (I don't eat meat.) - but Chinese language is *tonal* which meant that most of the time people just stared at my (apparent) gibberish, and I beat a hasty retreat to sign language. ### Language As I was preparing for the trip, one of my friends who had travelled in China remarked - "you will get to experience what illiteracy means". It's not just that I was in a place where I didn't know the local language - I had travelled in Thailand, Cambodia and Indonesia. But those were tourist friendly destinations where it was easy to find someone who spoke English. But in Shezhen, the isolation was complete. I had no idea what I was looking at - almost all shop signs were in Chinese, and hardly anyone spoke English. Technology can help, *Pleco* is an app I found to be useful - it provides an off-line translation from English to Chinese, including pronunciation. But this app can be confusing as well. A given English word can have multiple translations and most may make no sense for your particular situation.You can also use google to translate the Chinese characters. I am sure there's plenty of other software you could use to do similar things. One useful thing to learn (thanks Charles, for teaching me) is Chinese hand gestures for numbers: ![Shenzhen](/images/2016/01/shenzhen-hand.jpg) *(Image credit: https://pdsworldservice.files.wordpress.com/2013/06/e69caae6a087e9a298-1.jpg)* By the way, Shenzhen is pronounced more like *shen-jen* rather than *shen-zen*. ### Safety During my trip, I found the Chinese people to be friendly and Shenzhen streets to be safe. I routinely walked a couple of kilometers back to the hotel late at night, and I faced no problems whatsoever. Every few blocks, I saw Police kiosks and a uniformed officer. The streets were so brightly lit at some places that it felt like daylight at 11:30 PM. ### Internet As you might have heard, a lot of the internet that you take for granted (Facebook, Twitter, Google services, etc.) are blocked in China. But almost everyone I met used VPN software, so it's important to set one up before making the trip. Another idea is to get a SIM from Hong Kong for your phone, have in on roaming, and you have unfiltered internet on your phone in Shenzhen for the duration of your trip. ### Visit to Seeed Studio The primary purpose of my trip was to be at Seeed Studio in time for the production of snapVCC. ![Shenzhen](/images/2016/01/shenzhen-seeed.jpg) Seeed is in Xili, which was a 40 minute ride by taxi from my hotel, and cost about 80 RMB. I won't go into details of my Seeed visit here, except to say that they are a great bunch of people, and that I was very happy to be present to see the first pieces of snapVCC come out of production. ### Haquiangbei Electronics Market One of the big attractions of Shenzhen is the Haquiangbei (HQB) electronics market. For folks from Bangalore, think of it as $$(S.P.Road)^N$$ where $$N$$ is a very large number. A good guide to this area is the *Shenzhen Map for Makers* created by Seeed Studio, the PDF for which is available free online. When I was in town they also gave me a printed copy, which was very handy. ![Shenzhen](/images/2016/01/shenzhen-hqb-map.jpg) You can think of HQB as a big spread of multi-storied malls densely packed with shops selling all kinds of electronics - right from discrete components to fully assembled computers. There are zones for specific components - power supplies or motors, for instance. The most impressive sight in that area is the 70+ storied SEG building, the first 8 floors of which consist of electronics markets, and the rest filled with restaurants, offices and such. It was so tall that I could used the building as a marker to orient myself as I walked around it that area. ![Shenzhen](/images/2016/01/shenzhen-hqb.jpg) One interesting sight outside HQB malls is stalls selling remote controlled drones. These can be as cheap as 100 RMB. It's great fun to watch the sellers fly these things - they can make them shoot up to the sky and do all kinds of crazy maneuvers. Added to this is their sales pitch. My seller stood on top of a drone to demonstrate its crash recoverability. So of course I bought one. Looking at HQB, you understand why so many companies from the west have operations here. Need a reel of MOSFETs for your assembly line? No problem - just walk to HQB and get one. It's like buying vegetables in a supermarket. ### Ian & HQB Hackers I was in touch with Ian (of *Dangerous Prototypes* fame) who has his base in Shenzhen now. He was kind enough to connect me with his HQB hacker group on *WeChat*. Every evening we hung out in the HQB area and I great fun speaking to folks from US, Germany, Australia and other places who were using the Shenzhen infrastructure to work on their projects. ![Shenzhen](/images/2016/01/shenzhen-hackers.jpg) If you are in the HQB area, I'd be happy to put you in touch with Ian's group. ### Sightseeing Although most folks come to Shenzhen for electronics, the place offers plenty of sightseeing opportunites as well. One place I visited is the Dafen oil painting village, where I purchased a couple of paintings by local artists. ![Shenzhen](/images/2016/01/shenzhen-dafen.jpg) I wanted to visit the Fairly Lake botanical gardens, but didn't have time. It's supposed to be one of the most beautful parks in China. Do check the wikitravel guide to Shenzhen for other suggestions. ## Conclusion Although my trip was short, a visit to Shenzhen gave me a much clearer picture of its electronics manufacturing infrastructure. I hope to leverage my knowledge and contacts for future projects. Looking forward to my next visit! ## References 1. [Wikitravel guide to Shenzhen][2] [1]: https://www.crowdsupply.com/electronut-labs/snapvcc [2]: http://wikitravel.org/en/Shenzhen
electronut/electronut.github.io
_posts/2016-01-17-all-roads-shenzhen.md
Markdown
mit
11,762
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>wCMF 4.1: Member List</title> <meta name="generator" content="Doxygen 1.8.17"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="A MDSD framework for building reliable, maintainable and extendable web applications with PHP"> <meta name="keywords" content="PHP, web application framework, model driven development"> <meta name="author" content="wemove digital solutions"> <link rel="shortcut icon" href="theme/images/favicon.ico"> <script src="jquery.js"></script> <script src="theme/vendor/popper/popper.min.js"></script> <script src="theme/vendor/bootstrap/js/bootstrap.min.js"></script> <link href="theme/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="theme/vendor/fontawesome/css/all.min.css" rel="stylesheet"> <script src="theme/vendor/bootstrap-toc/bootstrap-toc.min.js"></script> <link href="theme/vendor/bootstrap-toc/bootstrap-toc.min.css" rel="stylesheet"> <script src="theme/vendor/bootstrap3-typeahead/bootstrap3-typeahead.min.js"></script> <script src="theme/vendor/highlight/highlight.pack.js"></script> <link href="theme/vendor/highlight/styles/solarized-dark.css" rel="stylesheet"> <script src="theme/js/application.js"></script> <script src="dynsections.js"></script> <link href="theme/css/style.css" rel="stylesheet"> </head> <body data-spy="scroll" data-target="#toc"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top"> <a class="navbar-brand" href="index.html">wCMF 4.1</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggler" aria-controls="navbarToggler" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggler"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="guidesDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="far fa-hand-point-right"></i> Guides <b class="caret"></b> </a> <div class="dropdown-menu" aria-labelledby="guidesDropdownMenuLink"> <a class="dropdown-item" href="gettingstarted.html">Getting started</a> <a class="dropdown-item" href="architecture.html">Architecture</a> <a class="dropdown-item" href="model.html">Model</a> <a class="dropdown-item" href="persistence.html">Persistence</a> <a class="dropdown-item" href="presentation.html">Presentation</a> <a class="dropdown-item" href="configuration.html">Configuration</a> <a class="dropdown-item" href="security.html">Security</a> <a class="dropdown-item" href="i18n_l10n.html">I18n & l10n</a> <a class="dropdown-item" href="tests.html">Tests</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="versionsDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-tags"></i> Versions <b class="caret"></b> </a> <div class="dropdown-menu" aria-labelledby="versionsDropdownMenuLink"> <a class="dropdown-item" href="4.1/index.html">4.1.x</a> <a class="dropdown-item" href="4.0/index.html">4.0.x</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="apiDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-file-alt"></i> API <b class="caret"></b> </a> <div class="dropdown-menu" aria-labelledby="apiDropdownMenuLink"> <a class="dropdown-item" href="annotated.html">Classes</a> <a class="dropdown-item" href="hierarchy.html">Hierarchy</a> </div> </li> <li class="nav-item"><a class="nav-link" href="https://github.com/iherwig/wcmf"><i class="fab fa-github"></i> Code</a></li> <li class="nav-item"><a class="nav-link" href="support.html"><i class="fas fa-life-ring"></i> Support</a></li> </ul> <form class="form-inline my-2 my-lg-0"> <input id="search-field" class="form-control mr-sm-2" type="search" placeholder="Search API" disabled> </form> </div> </nav> <a class="anchor" id="top"></a> <div class="content" id="content"> <div class="container"> <div class="row mt-4"> <div id="toc-container" class="col-lg-3 d-none d-lg-block d-none"> <nav id="toc" class="sticky-top"></nav> </div> <div id="content-container" class="col-md-12 col-lg-12"> <div> <!-- end header part --><!-- Generated by Doxygen 1.8.17 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ //var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacewcmf.html">wcmf</a></li><li class="navelem"><a class="el" href="namespacewcmf_1_1lib.html">lib</a></li><li class="navelem"><a class="el" href="namespacewcmf_1_1lib_1_1config.html">config</a></li><li class="navelem"><a class="el" href="namespacewcmf_1_1lib_1_1config_1_1impl.html">impl</a></li><li class="navelem"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html">ConfigActionKeyProvider</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">ConfigActionKeyProvider Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html">ConfigActionKeyProvider</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html#a4dfad0a6d659cfa93b4c4041902c80a4">__construct</a>(Configuration $configuration, $configSection)</td><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html">ConfigActionKeyProvider</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html#a303a70abaf5614e1f9025044c1f78e17">containsKey</a>($actionKey)</td><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html">ConfigActionKeyProvider</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html#a12251d0c022e9e21c137a105ff683f13">getId</a>()</td><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html">ConfigActionKeyProvider</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html#a7deb1d109f361a251f9dbf9e8507037e">getKeyValue</a>($actionKey)</td><td class="entry"><a class="el" href="classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider.html">ConfigActionKeyProvider</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> </div> </div> </div> </div> <hr> <footer> <div class="container"> <div class="row"> <div class="col-md-9"> <small>&copy; 2020 <a href="http://www.wemove.com" target="_blank">wemove digital solutions</a><br> Generated on Mon Dec 21 2020 22:40:28 for wCMF by &#160;<a href="http://www.doxygen.org/index.html" target="_blank">doxygen</a> 1.8.17</small> </div> </div> </div> </footer> <!-- Matomo --> <script type="text/javascript"> var _paq = _paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://piwik.wemove.com/"; _paq.push(['setTrackerUrl', u+'piwik.php']); _paq.push(['setSiteId', '7']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); </script> <noscript><img src="https://piwik.wemove.com/piwik.php?idsite=7&rec=1" style="border:0" alt="" /></noscript> <!-- End Matomo --> </body> </html>
iherwig/wcmf
docs/api-gen/html/latest/classwcmf_1_1lib_1_1config_1_1impl_1_1_config_action_key_provider-members.html
HTML
mit
8,747
namespace Watcher.Messages.Person { public class PersonRequest { } }
ronaldme/Watcher
Watcher.Messages/Person/PersonRequest.cs
C#
mit
84
.icons > [class^="icon-"] { position: relative; text-align: left; font-size: 32px; } .icons > [class^="icon-"] > span { display: none; padding: 20px 23px 18px 23px; background: #00101c; width: auto; color: #fff; font-family: 'Roboto', Arial, sans-serif; font-size: 16px; } .icons > [class^="icon-"]:hover > span { display: block; position: absolute; top: -64px; right: 35px; white-space: nowrap; z-index: 5; } .arrow-down { width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; display: none; border-top: 10px solid #00101c; } .icons > [class^="icon-"]:hover > .arrow-down { display: block; position: absolute; top: -10px; right: 50px; }
vrch/efigence-camp
stylesheets/icons-temporary.css
CSS
mit
740
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GenericApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Medline Industries, Inc.")] [assembly: AssemblyProduct("GenericApp")] [assembly: AssemblyCopyright("Copyright © Medline Industries, Inc. 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("10196d63-1170-4124-9a14-48ebdefab06f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
jeffld/CSharp-Regex
GenericApp/GenericApp.Program/Properties/AssemblyInfo.cs
C#
mit
1,480
<?php namespace System\Classes; use App; use Url; use File; use Lang; use Event; use Cache; use Route; use Config; use Request; use Response; use Assetic\Asset\FileAsset; use Assetic\Asset\GlobAsset; use Assetic\Asset\AssetCache; use Assetic\Asset\AssetCollection; use Assetic\Factory\AssetFactory; use October\Rain\Parse\Assetic\FilesystemCache; use System\Helpers\Cache as CacheHelper; use ApplicationException; use DateTime; /** * Combiner class used for combining JavaScript and StyleSheet files. * * This works by taking a collection of asset locations, serializing them, * then storing them in the session with a unique ID. The ID is then used * to generate a URL to the `/combine` route via the system controller. * * When the combine route is hit, the unique ID is used to serve up the * assets -- minified, compiled or both. Special E-Tags are used to prevent * compilation and delivery of cached assets that are unchanged. * * Use the `CombineAssets::combine` method to combine your own assets. * * The functionality of this class is controlled by these config items: * * - cms.enableAssetCache - Cache untouched assets * - cms.enableAssetMinify - Compress assets using minification * - cms.enableAssetDeepHashing - Advanced caching of imports * * @see System\Classes\SystemController System controller * @see https://octobercms.com/docs/services/session Session service * @package october\system * @author Alexey Bobkov, Samuel Georges */ class CombineAssets { use \October\Rain\Support\Traits\Singleton; /** * @var array A list of known JavaScript extensions. */ protected static $jsExtensions = ['js']; /** * @var array A list of known StyleSheet extensions. */ protected static $cssExtensions = ['css', 'less', 'scss', 'sass']; /** * @var array Aliases for asset file paths. */ protected $aliases = []; /** * @var array Bundles that are compiled to the filesystem. */ protected $bundles = []; /** * @var array Filters to apply to each file. */ protected $filters = []; /** * @var string The local path context to find assets. */ protected $localPath; /** * @var string The output folder for storing combined files. */ protected $storagePath; /** * @var bool Cache untouched files. */ public $useCache = false; /** * @var bool Compress (minify) asset files. */ public $useMinify = false; /** * @var bool When true, cache will be busted when an import is modified. * Enabling this feature will make page loading slower. */ public $useDeepHashing = false; /** * @var array Cache of registration callbacks. */ private static $callbacks = []; /** * Constructor */ public function init() { /* * Register preferences */ $this->useCache = Config::get('cms.enableAssetCache', false); $this->useMinify = Config::get('cms.enableAssetMinify', null); $this->useDeepHashing = Config::get('cms.enableAssetDeepHashing', null); if ($this->useMinify === null) { $this->useMinify = !Config::get('app.debug', false); } if ($this->useDeepHashing === null) { $this->useDeepHashing = Config::get('app.debug', false); } /* * Register JavaScript filters */ $this->registerFilter('js', new \October\Rain\Parse\Assetic\JavascriptImporter); /* * Register CSS filters */ $this->registerFilter('css', new \Assetic\Filter\CssImportFilter); $this->registerFilter(['css', 'less', 'scss'], new \Assetic\Filter\CssRewriteFilter); $this->registerFilter('less', new \October\Rain\Parse\Assetic\LessCompiler); $this->registerFilter('scss', new \October\Rain\Parse\Assetic\ScssCompiler); /* * Minification filters */ if ($this->useMinify) { $this->registerFilter('js', new \Assetic\Filter\JSMinFilter); $this->registerFilter(['css', 'less', 'scss'], new \October\Rain\Parse\Assetic\StylesheetMinify); } /* * Common Aliases */ $this->registerAlias('jquery', '~/modules/backend/assets/js/vendor/jquery.min.js'); $this->registerAlias('framework', '~/modules/system/assets/js/framework.js'); $this->registerAlias('framework.extras', '~/modules/system/assets/js/framework.extras.js'); $this->registerAlias('framework.extras', '~/modules/system/assets/css/framework.extras.css'); /* * Deferred registration */ foreach (static::$callbacks as $callback) { $callback($this); } } /** * Combines JavaScript or StyleSheet file references * to produce a page relative URL to the combined contents. * * $assets = [ * 'assets/vendor/mustache/mustache.js', * 'assets/js/vendor/jquery.ui.widget.js', * 'assets/js/vendor/canvas-to-blob.js', * ]; * * CombineAssets::combine($assets, base_path('plugins/acme/blog')); * * @param array $assets Collection of assets * @param string $localPath Prefix all assets with this path (optional) * @return string URL to contents. */ public static function combine($assets = [], $localPath = null) { return self::instance()->prepareRequest($assets, $localPath); } /** * Combines a collection of assets files to a destination file * * $assets = [ * 'assets/less/header.less', * 'assets/less/footer.less', * ]; * * CombineAssets::combineToFile( * $assets, * base_path('themes/website/assets/theme.less'), * base_path('themes/website') * ); * * @param array $assets Collection of assets * @param string $destination Write the combined file to this location * @param string $localPath Prefix all assets with this path (optional) * @return void */ public function combineToFile($assets = [], $destination, $localPath = null) { // Disable cache always $this->storagePath = null; list($assets, $extension) = $this->prepareAssets($assets); $rewritePath = File::localToPublic(dirname($destination)); $combiner = $this->prepareCombiner($assets, $rewritePath); $contents = $combiner->dump(); File::put($destination, $contents); } /** * Returns the combined contents from a prepared cache identifier. * @param string $cacheKey Cache identifier. * @return string Combined file contents. */ public function getContents($cacheKey) { $cacheInfo = $this->getCache($cacheKey); if (!$cacheInfo) { throw new ApplicationException(Lang::get('system::lang.combiner.not_found', ['name'=>$cacheKey])); } $this->localPath = $cacheInfo['path']; $this->storagePath = storage_path('cms/combiner/assets'); /* * Analyse cache information */ $lastModifiedTime = gmdate("D, d M Y H:i:s \G\M\T", array_get($cacheInfo, 'lastMod')); $etag = array_get($cacheInfo, 'etag'); $mime = (array_get($cacheInfo, 'extension') == 'css') ? 'text/css' : 'application/javascript'; /* * Set 304 Not Modified header, if necessary */ header_remove(); $response = Response::make(); $response->header('Content-Type', $mime); $response->header('Cache-Control', 'private, max-age=604800'); $response->setLastModified(new DateTime($lastModifiedTime)); $response->setEtag($etag); $response->setPublic(); $modified = !$response->isNotModified(App::make('request')); /* * Request says response is cached, no code evaluation needed */ if ($modified) { $this->setHashOnCombinerFilters($cacheKey); $combiner = $this->prepareCombiner($cacheInfo['files']); $contents = $combiner->dump(); $response->setContent($contents); } return $response; } /** * Prepares an array of assets by normalizing the collection * and processing aliases. * @param array $assets * @return array */ protected function prepareAssets(array $assets) { if (!is_array($assets)) { $assets = [$assets]; } /* * Split assets in to groups. */ $combineJs = []; $combineCss = []; foreach ($assets as $asset) { /* * Allow aliases to go through without an extension */ if (substr($asset, 0, 1) == '@') { $combineJs[] = $asset; $combineCss[] = $asset; continue; } $extension = File::extension($asset); if (in_array($extension, self::$jsExtensions)) { $combineJs[] = $asset; continue; } if (in_array($extension, self::$cssExtensions)) { $combineCss[] = $asset; continue; } } /* * Determine which group of assets to combine. */ if (count($combineCss) > count($combineJs)) { $extension = 'css'; $assets = $combineCss; } else { $extension = 'js'; $assets = $combineJs; } /* * Apply registered aliases */ if ($aliasMap = $this->getAliases($extension)) { foreach ($assets as $key => $asset) { if (substr($asset, 0, 1) !== '@') { continue; } $_asset = substr($asset, 1); if (isset($aliasMap[$_asset])) { $assets[$key] = $aliasMap[$_asset]; } } } return [$assets, $extension]; } /** * Combines asset file references of a single type to produce * a URL reference to the combined contents. * @param array $assets List of asset files. * @param string $localPath File extension, used for aesthetic purposes only. * @return string URL to contents. */ protected function prepareRequest(array $assets, $localPath = null) { if (substr($localPath, -1) != '/') { $localPath = $localPath.'/'; } $this->localPath = $localPath; $this->storagePath = storage_path('cms/combiner/assets'); list($assets, $extension) = $this->prepareAssets($assets); /* * Cache and process */ $cacheKey = $this->getCacheKey($assets); $cacheInfo = $this->useCache ? $this->getCache($cacheKey) : false; if (!$cacheInfo) { $this->setHashOnCombinerFilters($cacheKey); $combiner = $this->prepareCombiner($assets); if ($this->useDeepHashing) { $factory = new AssetFactory($this->localPath); $lastMod = $factory->getLastModified($combiner); } else { $lastMod = $combiner->getLastModified(); } $cacheInfo = [ 'version' => $cacheKey.'-'.$lastMod, 'etag' => $cacheKey, 'lastMod' => $lastMod, 'files' => $assets, 'path' => $this->localPath, 'extension' => $extension ]; $this->putCache($cacheKey, $cacheInfo); } return $this->getCombinedUrl($cacheInfo['version']); } /** * Returns the combined contents from a prepared cache identifier. * @param array $assets List of asset files. * @param string $rewritePath * @return string Combined file contents. */ protected function prepareCombiner(array $assets, $rewritePath = null) { /* * Extensibility */ Event::fire('cms.combiner.beforePrepare', [$this, $assets]); $files = []; $filesSalt = null; foreach ($assets as $asset) { $filters = $this->getFilters(File::extension($asset)) ?: []; $path = file_exists($asset) ? $asset : File::symbolizePath($asset, null) ?: $this->localPath . $asset; $files[] = new FileAsset($path, $filters, public_path()); $filesSalt .= $this->localPath . $asset; } $filesSalt = md5($filesSalt); $collection = new AssetCollection($files, [], $filesSalt); $collection->setTargetPath($this->getTargetPath($rewritePath)); if ($this->storagePath === null) { return $collection; } if (!File::isDirectory($this->storagePath)) { @File::makeDirectory($this->storagePath); } $cache = new FilesystemCache($this->storagePath); $cachedFiles = []; foreach ($files as $file) { $cachedFiles[] = new AssetCache($file, $cache); } $cachedCollection = new AssetCollection($cachedFiles, [], $filesSalt); $cachedCollection->setTargetPath($this->getTargetPath($rewritePath)); return $cachedCollection; } /** * Busts the cache based on a different cache key. * @return void */ protected function setHashOnCombinerFilters($hash) { $allFilters = call_user_func_array('array_merge', $this->getFilters()); foreach ($allFilters as $filter) { if (method_exists($filter, 'setHash')) { $filter->setHash($hash); } } } /** * Returns a deep hash on filters that support it. * @param array $assets List of asset files. * @return void */ protected function getDeepHashFromAssets($assets) { $key = ''; $assetFiles = array_map(function ($file) { return file_exists($file) ? $file : File::symbolizePath($file, null) ?: $this->localPath . $file; }, $assets); foreach ($assetFiles as $file) { $filters = $this->getFilters(File::extension($file)); foreach ($filters as $filter) { if (method_exists($filter, 'hashAsset')) { $key .= $filter->hashAsset($file, $this->localPath); } } } return $key; } /** * Returns the URL used for accessing the combined files. * @param string $outputFilename A custom file name to use. * @return string */ protected function getCombinedUrl($outputFilename = 'undefined.css') { $combineAction = 'System\Classes\Controller@combine'; $actionExists = Route::getRoutes()->getByAction($combineAction) !== null; if ($actionExists) { return Url::action($combineAction, [$outputFilename], false); } else { return '/combine/'.$outputFilename; } } /** * Returns the target path for use with the combiner. The target * path helps generate relative links within CSS. * * /combine returns combine/ * /index.php/combine returns index-php/combine/ * * @param string|null $path * @return string The new target path */ protected function getTargetPath($path = null) { if ($path === null) { $baseUri = substr(Request::getBaseUrl(), strlen(Request::getBasePath())); $path = $baseUri.'/combine'; } if (strpos($path, '/') === 0) { $path = substr($path, 1); } $path = str_replace('.', '-', $path).'/'; return $path; } // // Registration // /** * Registers a callback function that defines bundles. * The callback function should register bundles by calling the manager's * `registerBundle` method. This instance is passed to the callback * function as an argument. Usage: * * CombineAssets::registerCallback(function($combiner){ * $combiner->registerBundle('~/modules/backend/assets/less/october.less'); * }); * * @param callable $callback A callable function. */ public static function registerCallback(callable $callback) { self::$callbacks[] = $callback; } // // Filters // /** * Register a filter to apply to the combining process. * @param string|array $extension Extension name. Eg: css * @param object $filter Collection of files to combine. * @return self */ public function registerFilter($extension, $filter) { if (is_array($extension)) { foreach ($extension as $_extension) { $this->registerFilter($_extension, $filter); } return; } $extension = strtolower($extension); if (!isset($this->filters[$extension])) { $this->filters[$extension] = []; } if ($filter !== null) { $this->filters[$extension][] = $filter; } return $this; } /** * Clears any registered filters. * @param string $extension Extension name. Eg: css * @return self */ public function resetFilters($extension = null) { if ($extension === null) { $this->filters = []; } else { $this->filters[$extension] = []; } return $this; } /** * Returns filters. * @param string $extension Extension name. Eg: css * @return self */ public function getFilters($extension = null) { if ($extension === null) { return $this->filters; } elseif (isset($this->filters[$extension])) { return $this->filters[$extension]; } else { return null; } } // // Bundles // /** * Registers bundle. * @param string|array $files Files to be registered to bundle * @param string $destination Destination file will be compiled to. * @param string $extension Extension name. Eg: css * @return self */ public function registerBundle($files, $destination = null, $extension = null) { if (!is_array($files)) { $files = [$files]; } $firstFile = array_values($files)[0]; if ($extension === null) { $extension = File::extension($firstFile); } $extension = strtolower(trim($extension)); if ($destination === null) { $file = File::name($firstFile); $path = dirname($firstFile); $preprocessors = array_except(self::$cssExtensions, 'css'); if (in_array($extension, $preprocessors)) { $cssPath = $path.'/../css'; if ( in_array(strtolower(basename($path)), $preprocessors) && File::isDirectory(File::symbolizePath($cssPath)) ) { $path = $cssPath; } $destination = $path.'/'.$file.'.css'; } else { $destination = $path.'/'.$file.'-min.'.$extension; } } $this->bundles[$extension][$destination] = $files; return $this; } /** * Returns bundles. * @param string $extension Extension name. Eg: css * @return self */ public function getBundles($extension = null) { if ($extension === null) { return $this->bundles; } elseif (isset($this->bundles[$extension])) { return $this->bundles[$extension]; } else { return null; } } // // Aliases // /** * Register an alias to use for a longer file reference. * @param string $alias Alias name. Eg: framework * @param string $file Path to file to use for alias * @param string $extension Extension name. Eg: css * @return self */ public function registerAlias($alias, $file, $extension = null) { if ($extension === null) { $extension = File::extension($file); } $extension = strtolower($extension); if (!isset($this->aliases[$extension])) { $this->aliases[$extension] = []; } $this->aliases[$extension][$alias] = $file; return $this; } /** * Clears any registered aliases. * @param string $extension Extension name. Eg: css * @return self */ public function resetAliases($extension = null) { if ($extension === null) { $this->aliases = []; } else { $this->aliases[$extension] = []; } return $this; } /** * Returns aliases. * @param string $extension Extension name. Eg: css * @return self */ public function getAliases($extension = null) { if ($extension === null) { return $this->aliases; } elseif (isset($this->aliases[$extension])) { return $this->aliases[$extension]; } else { return null; } } // // Cache // /** * Stores information about a asset collection against * a cache identifier. * @param string $cacheKey Cache identifier. * @param array $cacheInfo List of asset files. * @return bool Successful */ protected function putCache($cacheKey, array $cacheInfo) { $cacheKey = 'combiner.'.$cacheKey; if (Cache::has($cacheKey)) { return false; } $this->putCacheIndex($cacheKey); Cache::forever($cacheKey, base64_encode(serialize($cacheInfo))); return true; } /** * Look up information about a cache identifier. * @param string $cacheKey Cache identifier * @return array Cache information */ protected function getCache($cacheKey) { $cacheKey = 'combiner.'.$cacheKey; if (!Cache::has($cacheKey)) { return false; } return @unserialize(@base64_decode(Cache::get($cacheKey))); } /** * Builds a unique string based on assets * @param array $assets Asset files * @return string Unique identifier */ protected function getCacheKey(array $assets) { $cacheKey = $this->localPath . implode('|', $assets); /* * Deep hashing */ if ($this->useDeepHashing) { $cacheKey .= $this->getDeepHashFromAssets($assets); } /* * Extensibility */ $dataHolder = (object) ['key' => $cacheKey]; Event::fire('cms.combiner.getCacheKey', [$this, $dataHolder]); $cacheKey = $dataHolder->key; return md5($cacheKey); } /** * Resets the combiner cache * @return void */ public static function resetCache() { if (Cache::has('combiner.index')) { $index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: []; foreach ($index as $cacheKey) { Cache::forget($cacheKey); } Cache::forget('combiner.index'); } CacheHelper::instance()->clearCombiner(); } /** * Adds a cache identifier to the index store used for * performing a reset of the cache. * @param string $cacheKey Cache identifier * @return bool Returns false if identifier is already in store */ protected function putCacheIndex($cacheKey) { $index = []; if (Cache::has('combiner.index')) { $index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: []; } if (in_array($cacheKey, $index)) { return false; } $index[] = $cacheKey; Cache::forever('combiner.index', base64_encode(serialize($index))); return true; } }
lupin72/piergorelli.com
modules/system/classes/CombineAssets.php
PHP
mit
24,315
raspi led === > basic LED interactions on a raspberry pi ![screenshot](./screenshot.png) # Setup Follow the base setup of the johnny-five LED example ![breadboard setup](http://johnny-five.io/img/breadboard/led-13-raspberry-pi.png) # Usage `Make sure you do these steps on a raspberry pi` * install prerequisites `sudo apt-get install wiringpi` (might crash if you don't have git) * install dependencies (`yarn` seems to cause errors, use `npm install` instead) * run the code with root priviledges ``sudo `which node` index`` * see your LED blinking > You can also use [remote-code](https://github.com/anoff/remote-code) if you don't want to work manually on your pi.
anoff/robby5
examples/raspi-led/readme.md
Markdown
mit
678
<?php ################################################## ## ## ## CREATE APPLICATION DEFINITIONS ## ## ## ################################################## # define('APPLICATION', 'application'); define('CONFIG', 'config'); define('CONTROLLER', 'controllers'); define('CORE', 'core'); define('DS', DIRECTORY_SEPARATOR); define('ERRORS', 'errors'); define('LIBRARY', 'libraries'); define('MODEL', 'models'); define('RUN', true); define('PHP', '.php'); define('VIEW', 'views'); ################################################## ## ## ## GET UTILITIES ## ## ## ################################################## # require_once(APPLICATION.DS.CORE.DS.'Utilities'.PHP); ################################################## ## ## ## BOOTSTRAP ## ## ## ################################################## # load_class('Logging', CORE); load_class('Controller', CORE); load_class('Security', CORE); load_class('Router', CORE);
jjNford/phpblueprint-framework
index.php
PHP
mit
1,270
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.2-dev * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * SimplePie Name */ define('SIMPLEPIE_NAME', 'SimplePie'); /** * SimplePie Version */ define('SIMPLEPIE_VERSION', '1.3.2-dev'); /** * SimplePie Build * @todo Hardcode for release (there's no need to have to call SimplePie_Misc::get_build() only every load of simplepie.inc) */ define('SIMPLEPIE_BUILD', gmdate('YmdHis', SimplePie_Misc::get_build())); /** * SimplePie Website URL */ define('SIMPLEPIE_URL', 'http://simplepie.org'); /** * SimplePie Useragent * @see SimplePie::set_useragent() */ define('SIMPLEPIE_USERAGENT', SIMPLEPIE_NAME . '/' . SIMPLEPIE_VERSION . ' (Feed Parser; ' . SIMPLEPIE_URL . '; Allow like Gecko) Build/' . SIMPLEPIE_BUILD); /** * SimplePie Linkback */ define('SIMPLEPIE_LINKBACK', '<a href="' . SIMPLEPIE_URL . '" title="' . SIMPLEPIE_NAME . ' ' . SIMPLEPIE_VERSION . '">' . SIMPLEPIE_NAME . '</a>'); /** * No Autodiscovery * @see SimplePie::set_autodiscovery_level() */ define('SIMPLEPIE_LOCATOR_NONE', 0); /** * Feed Link Element Autodiscovery * @see SimplePie::set_autodiscovery_level() */ define('SIMPLEPIE_LOCATOR_AUTODISCOVERY', 1); /** * Local Feed Extension Autodiscovery * @see SimplePie::set_autodiscovery_level() */ define('SIMPLEPIE_LOCATOR_LOCAL_EXTENSION', 2); /** * Local Feed Body Autodiscovery * @see SimplePie::set_autodiscovery_level() */ define('SIMPLEPIE_LOCATOR_LOCAL_BODY', 4); /** * Remote Feed Extension Autodiscovery * @see SimplePie::set_autodiscovery_level() */ define('SIMPLEPIE_LOCATOR_REMOTE_EXTENSION', 8); /** * Remote Feed Body Autodiscovery * @see SimplePie::set_autodiscovery_level() */ define('SIMPLEPIE_LOCATOR_REMOTE_BODY', 16); /** * All Feed Autodiscovery * @see SimplePie::set_autodiscovery_level() */ define('SIMPLEPIE_LOCATOR_ALL', 31); /** * No known feed type */ define('SIMPLEPIE_TYPE_NONE', 0); /** * RSS 0.90 */ define('SIMPLEPIE_TYPE_RSS_090', 1); /** * RSS 0.91 (Netscape) */ define('SIMPLEPIE_TYPE_RSS_091_NETSCAPE', 2); /** * RSS 0.91 (Userland) */ define('SIMPLEPIE_TYPE_RSS_091_USERLAND', 4); /** * RSS 0.91 (both Netscape and Userland) */ define('SIMPLEPIE_TYPE_RSS_091', 6); /** * RSS 0.92 */ define('SIMPLEPIE_TYPE_RSS_092', 8); /** * RSS 0.93 */ define('SIMPLEPIE_TYPE_RSS_093', 16); /** * RSS 0.94 */ define('SIMPLEPIE_TYPE_RSS_094', 32); /** * RSS 1.0 */ define('SIMPLEPIE_TYPE_RSS_10', 64); /** * RSS 2.0 */ define('SIMPLEPIE_TYPE_RSS_20', 128); /** * RDF-based RSS */ define('SIMPLEPIE_TYPE_RSS_RDF', 65); /** * Non-RDF-based RSS (truly intended as syndication format) */ define('SIMPLEPIE_TYPE_RSS_SYNDICATION', 190); /** * All RSS */ define('SIMPLEPIE_TYPE_RSS_ALL', 255); /** * Atom 0.3 */ define('SIMPLEPIE_TYPE_ATOM_03', 256); /** * Atom 1.0 */ define('SIMPLEPIE_TYPE_ATOM_10', 512); /** * All Atom */ define('SIMPLEPIE_TYPE_ATOM_ALL', 768); /** * All feed types */ define('SIMPLEPIE_TYPE_ALL', 1023); /** * No construct */ define('SIMPLEPIE_CONSTRUCT_NONE', 0); /** * Text construct */ define('SIMPLEPIE_CONSTRUCT_TEXT', 1); /** * HTML construct */ define('SIMPLEPIE_CONSTRUCT_HTML', 2); /** * XHTML construct */ define('SIMPLEPIE_CONSTRUCT_XHTML', 4); /** * base64-encoded construct */ define('SIMPLEPIE_CONSTRUCT_BASE64', 8); /** * IRI construct */ define('SIMPLEPIE_CONSTRUCT_IRI', 16); /** * A construct that might be HTML */ define('SIMPLEPIE_CONSTRUCT_MAYBE_HTML', 32); /** * All constructs */ define('SIMPLEPIE_CONSTRUCT_ALL', 63); /** * Don't change case */ define('SIMPLEPIE_SAME_CASE', 1); /** * Change to lowercase */ define('SIMPLEPIE_LOWERCASE', 2); /** * Change to uppercase */ define('SIMPLEPIE_UPPERCASE', 4); /** * PCRE for HTML attributes */ define('SIMPLEPIE_PCRE_HTML_ATTRIBUTE', '((?:[\x09\x0A\x0B\x0C\x0D\x20]+[^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3D\x3E]*(?:[\x09\x0A\x0B\x0C\x0D\x20]*=[\x09\x0A\x0B\x0C\x0D\x20]*(?:"(?:[^"]*)"|\'(?:[^\']*)\'|(?:[^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?)*)[\x09\x0A\x0B\x0C\x0D\x20]*'); /** * PCRE for XML attributes */ define('SIMPLEPIE_PCRE_XML_ATTRIBUTE', '((?:\s+(?:(?:[^\s:]+:)?[^\s:]+)\s*=\s*(?:"(?:[^"]*)"|\'(?:[^\']*)\'))*)\s*'); /** * XML Namespace */ define('SIMPLEPIE_NAMESPACE_XML', 'http://www.w3.org/XML/1998/namespace'); /** * Atom 1.0 Namespace */ define('SIMPLEPIE_NAMESPACE_ATOM_10', 'http://www.w3.org/2005/Atom'); /** * Atom 0.3 Namespace */ define('SIMPLEPIE_NAMESPACE_ATOM_03', 'http://purl.org/atom/ns#'); /** * RDF Namespace */ define('SIMPLEPIE_NAMESPACE_RDF', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); /** * RSS 0.90 Namespace */ define('SIMPLEPIE_NAMESPACE_RSS_090', 'http://my.netscape.com/rdf/simple/0.9/'); /** * RSS 1.0 Namespace */ define('SIMPLEPIE_NAMESPACE_RSS_10', 'http://purl.org/rss/1.0/'); /** * RSS 1.0 Content Module Namespace */ define('SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT', 'http://purl.org/rss/1.0/modules/content/'); /** * RSS 2.0 Namespace * (Stupid, I know, but I'm certain it will confuse people less with support.) */ define('SIMPLEPIE_NAMESPACE_RSS_20', ''); /** * DC 1.0 Namespace */ define('SIMPLEPIE_NAMESPACE_DC_10', 'http://purl.org/dc/elements/1.0/'); /** * DC 1.1 Namespace */ define('SIMPLEPIE_NAMESPACE_DC_11', 'http://purl.org/dc/elements/1.1/'); /** * W3C Basic Geo (WGS84 lat/long) Vocabulary Namespace */ define('SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO', 'http://www.w3.org/2003/01/geo/wgs84_pos#'); /** * GeoRSS Namespace */ define('SIMPLEPIE_NAMESPACE_GEORSS', 'http://www.georss.org/georss'); /** * Media RSS Namespace */ define('SIMPLEPIE_NAMESPACE_MEDIARSS', 'http://search.yahoo.com/mrss/'); /** * Wrong Media RSS Namespace. Caused by a long-standing typo in the spec. */ define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG', 'http://search.yahoo.com/mrss'); /** * Wrong Media RSS Namespace #2. New namespace introduced in Media RSS 1.5. */ define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG2', 'http://video.search.yahoo.com/mrss'); /** * Wrong Media RSS Namespace #3. A possible typo of the Media RSS 1.5 namespace. */ define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG3', 'http://video.search.yahoo.com/mrss/'); /** * Wrong Media RSS Namespace #4. New spec location after the RSS Advisory Board takes it over, but not a valid namespace. */ define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG4', 'http://www.rssboard.org/media-rss'); /** * Wrong Media RSS Namespace #5. A possible typo of the RSS Advisory Board URL. */ define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG5', 'http://www.rssboard.org/media-rss/'); /** * iTunes RSS Namespace */ define('SIMPLEPIE_NAMESPACE_ITUNES', 'http://www.itunes.com/dtds/podcast-1.0.dtd'); /** * XHTML Namespace */ define('SIMPLEPIE_NAMESPACE_XHTML', 'http://www.w3.org/1999/xhtml'); /** * IANA Link Relations Registry */ define('SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY', 'http://www.iana.org/assignments/relation/'); /** * No file source */ define('SIMPLEPIE_FILE_SOURCE_NONE', 0); /** * Remote file source */ define('SIMPLEPIE_FILE_SOURCE_REMOTE', 1); /** * Local file source */ define('SIMPLEPIE_FILE_SOURCE_LOCAL', 2); /** * fsockopen() file source */ define('SIMPLEPIE_FILE_SOURCE_FSOCKOPEN', 4); /** * cURL file source */ define('SIMPLEPIE_FILE_SOURCE_CURL', 8); /** * file_get_contents() file source */ define('SIMPLEPIE_FILE_SOURCE_FILE_GET_CONTENTS', 16); /** * SimplePie * * @package SimplePie * @subpackage API */ class SimplePie { /** * @var array Raw data * @access private */ public $data = array(); /** * @var mixed Error string * @access private */ public $error; /** * @var object Instance of SimplePie_Sanitize (or other class) * @see SimplePie::set_sanitize_class() * @access private */ public $sanitize; /** * @var string SimplePie Useragent * @see SimplePie::set_useragent() * @access private */ public $useragent = SIMPLEPIE_USERAGENT; /** * @var string Feed URL * @see SimplePie::set_feed_url() * @access private */ public $feed_url; /** * @var object Instance of SimplePie_File to use as a feed * @see SimplePie::set_file() * @access private */ public $file; /** * @var string Raw feed data * @see SimplePie::set_raw_data() * @access private */ public $raw_data; /** * @var int Timeout for fetching remote files * @see SimplePie::set_timeout() * @access private */ public $timeout = 10; /** * @var bool Forces fsockopen() to be used for remote files instead * of cURL, even if a new enough version is installed * @see SimplePie::force_fsockopen() * @access private */ public $force_fsockopen = false; /** * @var bool Force the given data/URL to be treated as a feed no matter what * it appears like * @see SimplePie::force_feed() * @access private */ public $force_feed = false; /** * @var bool Enable/Disable Caching * @see SimplePie::enable_cache() * @access private */ public $cache = true; /** * @var int Cache duration (in seconds) * @see SimplePie::set_cache_duration() * @access private */ public $cache_duration = 3600; /** * @var int Auto-discovery cache duration (in seconds) * @see SimplePie::set_autodiscovery_cache_duration() * @access private */ public $autodiscovery_cache_duration = 604800; // 7 Days. /** * @var string Cache location (relative to executing script) * @see SimplePie::set_cache_location() * @access private */ public $cache_location = './cache'; /** * @var string Function that creates the cache filename * @see SimplePie::set_cache_name_function() * @access private */ public $cache_name_function = 'md5'; /** * @var bool Reorder feed by date descending * @see SimplePie::enable_order_by_date() * @access private */ public $order_by_date = true; /** * @var mixed Force input encoding to be set to the follow value * (false, or anything type-cast to false, disables this feature) * @see SimplePie::set_input_encoding() * @access private */ public $input_encoding = false; /** * @var int Feed Autodiscovery Level * @see SimplePie::set_autodiscovery_level() * @access private */ public $autodiscovery = SIMPLEPIE_LOCATOR_ALL; /** * Class registry object * * @var SimplePie_Registry */ public $registry; /** * @var int Maximum number of feeds to check with autodiscovery * @see SimplePie::set_max_checked_feeds() * @access private */ public $max_checked_feeds = 10; /** * @var array All the feeds found during the autodiscovery process * @see SimplePie::get_all_discovered_feeds() * @access private */ public $all_discovered_feeds = array(); /** * @var string Web-accessible path to the handler_image.php file. * @see SimplePie::set_image_handler() * @access private */ public $image_handler = ''; /** * @var array Stores the URLs when multiple feeds are being initialized. * @see SimplePie::set_feed_url() * @access private */ public $multifeed_url = array(); /** * @var array Stores SimplePie objects when multiple feeds initialized. * @access private */ public $multifeed_objects = array(); /** * @var array Stores the get_object_vars() array for use with multifeeds. * @see SimplePie::set_feed_url() * @access private */ public $config_settings = null; /** * @var integer Stores the number of items to return per-feed with multifeeds. * @see SimplePie::set_item_limit() * @access private */ public $item_limit = 0; /** * @var array Stores the default attributes to be stripped by strip_attributes(). * @see SimplePie::strip_attributes() * @access private */ public $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'); /** * @var array Stores the default tags to be stripped by strip_htmltags(). * @see SimplePie::strip_htmltags() * @access private */ public $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'); /** * The SimplePie class contains feed level data and options * * To use SimplePie, create the SimplePie object with no parameters. You can * then set configuration options using the provided methods. After setting * them, you must initialise the feed using $feed->init(). At that point the * object's methods and properties will be available to you. * * Previously, it was possible to pass in the feed URL along with cache * options directly into the constructor. This has been removed as of 1.3 as * it caused a lot of confusion. * * @since 1.0 Preview Release */ public function __construct() { if (version_compare(PHP_VERSION, '5.2', '<')) { trigger_error('PHP 4.x, 5.0 and 5.1 are no longer supported. Please upgrade to PHP 5.2 or newer.'); die(); } // Other objects, instances created here so we can set options on them $this->sanitize = new SimplePie_Sanitize(); $this->registry = new SimplePie_Registry(); if (func_num_args() > 0) { $level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING; trigger_error('Passing parameters to the constructor is no longer supported. Please use set_feed_url(), set_cache_location(), and set_cache_location() directly.', $level); $args = func_get_args(); switch (count($args)) { case 3: $this->set_cache_duration($args[2]); case 2: $this->set_cache_location($args[1]); case 1: $this->set_feed_url($args[0]); $this->init(); } } } /** * Used for converting object to a string */ public function __toString() { return md5(serialize($this->data)); } /** * Remove items that link back to this before destroying this object */ public function __destruct() { if ((version_compare(PHP_VERSION, '5.3', '<') || !gc_enabled()) && !ini_get('zend.ze1_compatibility_mode')) { if (!empty($this->data['items'])) { foreach ($this->data['items'] as $item) { $item->__destruct(); } unset($item, $this->data['items']); } if (!empty($this->data['ordered_items'])) { foreach ($this->data['ordered_items'] as $item) { $item->__destruct(); } unset($item, $this->data['ordered_items']); } } } /** * Force the given data/URL to be treated as a feed * * This tells SimplePie to ignore the content-type provided by the server. * Be careful when using this option, as it will also disable autodiscovery. * * @since 1.1 * @param bool $enable Force the given data/URL to be treated as a feed */ public function force_feed($enable = false) { $this->force_feed = (bool) $enable; } /** * Set the URL of the feed you want to parse * * This allows you to enter the URL of the feed you want to parse, or the * website you want to try to use auto-discovery on. This takes priority * over any set raw data. * * You can set multiple feeds to mash together by passing an array instead * of a string for the $url. Remember that with each additional feed comes * additional processing and resources. * * @since 1.0 Preview Release * @see set_raw_data() * @param string|array $url This is the URL (or array of URLs) that you want to parse. */ public function set_feed_url($url) { $this->multifeed_url = array(); if (is_array($url)) { foreach ($url as $value) { $this->multifeed_url[] = $this->registry->call('Misc', 'fix_protocol', array($value, 1)); } } else { $this->feed_url = $this->registry->call('Misc', 'fix_protocol', array($url, 1)); } } /** * Set an instance of {@see SimplePie_File} to use as a feed * * @param SimplePie_File &$file * @return bool True on success, false on failure */ public function set_file(&$file) { if ($file instanceof SimplePie_File) { $this->feed_url = $file->url; $this->file =& $file; return true; } return false; } /** * Set the raw XML data to parse * * Allows you to use a string of RSS/Atom data instead of a remote feed. * * If you have a feed available as a string in PHP, you can tell SimplePie * to parse that data string instead of a remote feed. Any set feed URL * takes precedence. * * @since 1.0 Beta 3 * @param string $data RSS or Atom data as a string. * @see set_feed_url() */ public function set_raw_data($data) { $this->raw_data = $data; } /** * Set the the default timeout for fetching remote feeds * * This allows you to change the maximum time the feed's server to respond * and send the feed back. * * @since 1.0 Beta 3 * @param int $timeout The maximum number of seconds to spend waiting to retrieve a feed. */ public function set_timeout($timeout = 10) { $this->timeout = (int) $timeout; } /** * Force SimplePie to use fsockopen() instead of cURL * * @since 1.0 Beta 3 * @param bool $enable Force fsockopen() to be used */ public function force_fsockopen($enable = false) { $this->force_fsockopen = (bool) $enable; } /** * Enable/disable caching in SimplePie. * * This option allows you to disable caching all-together in SimplePie. * However, disabling the cache can lead to longer load times. * * @since 1.0 Preview Release * @param bool $enable Enable caching */ public function enable_cache($enable = true) { $this->cache = (bool) $enable; } /** * Set the length of time (in seconds) that the contents of a feed will be * cached * * @param int $seconds The feed content cache duration */ public function set_cache_duration($seconds = 3600) { $this->cache_duration = (int) $seconds; } /** * Set the length of time (in seconds) that the autodiscovered feed URL will * be cached * * @param int $seconds The autodiscovered feed URL cache duration. */ public function set_autodiscovery_cache_duration($seconds = 604800) { $this->autodiscovery_cache_duration = (int) $seconds; } /** * Set the file system location where the cached files should be stored * * @param string $location The file system location. */ public function set_cache_location($location = './cache') { $this->cache_location = (string) $location; } /** * Set whether feed items should be sorted into reverse chronological order * * @param bool $enable Sort as reverse chronological order. */ public function enable_order_by_date($enable = true) { $this->order_by_date = (bool) $enable; } /** * Set the character encoding used to parse the feed * * This overrides the encoding reported by the feed, however it will fall * back to the normal encoding detection if the override fails * * @param string $encoding Character encoding */ public function set_input_encoding($encoding = false) { if ($encoding) { $this->input_encoding = (string) $encoding; } else { $this->input_encoding = false; } } /** * Set how much feed autodiscovery to do * * @see SIMPLEPIE_LOCATOR_NONE * @see SIMPLEPIE_LOCATOR_AUTODISCOVERY * @see SIMPLEPIE_LOCATOR_LOCAL_EXTENSION * @see SIMPLEPIE_LOCATOR_LOCAL_BODY * @see SIMPLEPIE_LOCATOR_REMOTE_EXTENSION * @see SIMPLEPIE_LOCATOR_REMOTE_BODY * @see SIMPLEPIE_LOCATOR_ALL * @param int $level Feed Autodiscovery Level (level can be a combination of the above constants, see bitwise OR operator) */ public function set_autodiscovery_level($level = SIMPLEPIE_LOCATOR_ALL) { $this->autodiscovery = (int) $level; } /** * Get the class registry * * Use this to override SimplePie's default classes * @see SimplePie_Registry * @return SimplePie_Registry */ public function &get_registry() { return $this->registry; } /**#@+ * Useful when you are overloading or extending SimplePie's default classes. * * @deprecated Use {@see get_registry()} instead * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation * @param string $class Name of custom class * @return boolean True on success, false otherwise */ /** * Set which class SimplePie uses for caching */ public function set_cache_class($class = 'SimplePie_Cache') { return $this->registry->register('Cache', $class, true); } /** * Set which class SimplePie uses for auto-discovery */ public function set_locator_class($class = 'SimplePie_Locator') { return $this->registry->register('Locator', $class, true); } /** * Set which class SimplePie uses for XML parsing */ public function set_parser_class($class = 'SimplePie_Parser') { return $this->registry->register('Parser', $class, true); } /** * Set which class SimplePie uses for remote file fetching */ public function set_file_class($class = 'SimplePie_File') { return $this->registry->register('File', $class, true); } /** * Set which class SimplePie uses for data sanitization */ public function set_sanitize_class($class = 'SimplePie_Sanitize') { return $this->registry->register('Sanitize', $class, true); } /** * Set which class SimplePie uses for handling feed items */ public function set_item_class($class = 'SimplePie_Item') { return $this->registry->register('Item', $class, true); } /** * Set which class SimplePie uses for handling author data */ public function set_author_class($class = 'SimplePie_Author') { return $this->registry->register('Author', $class, true); } /** * Set which class SimplePie uses for handling category data */ public function set_category_class($class = 'SimplePie_Category') { return $this->registry->register('Category', $class, true); } /** * Set which class SimplePie uses for feed enclosures */ public function set_enclosure_class($class = 'SimplePie_Enclosure') { return $this->registry->register('Enclosure', $class, true); } /** * Set which class SimplePie uses for `<media:text>` captions */ public function set_caption_class($class = 'SimplePie_Caption') { return $this->registry->register('Caption', $class, true); } /** * Set which class SimplePie uses for `<media:copyright>` */ public function set_copyright_class($class = 'SimplePie_Copyright') { return $this->registry->register('Copyright', $class, true); } /** * Set which class SimplePie uses for `<media:credit>` */ public function set_credit_class($class = 'SimplePie_Credit') { return $this->registry->register('Credit', $class, true); } /** * Set which class SimplePie uses for `<media:rating>` */ public function set_rating_class($class = 'SimplePie_Rating') { return $this->registry->register('Rating', $class, true); } /** * Set which class SimplePie uses for `<media:restriction>` */ public function set_restriction_class($class = 'SimplePie_Restriction') { return $this->registry->register('Restriction', $class, true); } /** * Set which class SimplePie uses for content-type sniffing */ public function set_content_type_sniffer_class($class = 'SimplePie_Content_Type_Sniffer') { return $this->registry->register('Content_Type_Sniffer', $class, true); } /** * Set which class SimplePie uses item sources */ public function set_source_class($class = 'SimplePie_Source') { return $this->registry->register('Source', $class, true); } /**#@-*/ /** * Set the user agent string * * @param string $ua New user agent string. */ public function set_useragent($ua = SIMPLEPIE_USERAGENT) { $this->useragent = (string) $ua; } /** * Set callback function to create cache filename with * * @param mixed $function Callback function */ public function set_cache_name_function($function = 'md5') { if (is_callable($function)) { $this->cache_name_function = $function; } } /** * Set options to make SP as fast as possible * * Forgoes a substantial amount of data sanitization in favor of speed. This * turns SimplePie into a dumb parser of feeds. * * @param bool $set Whether to set them or not */ public function set_stupidly_fast($set = false) { if ($set) { $this->enable_order_by_date(false); $this->remove_div(false); $this->strip_comments(false); $this->strip_htmltags(false); $this->strip_attributes(false); $this->set_image_handler(false); } } /** * Set maximum number of feeds to check with autodiscovery * * @param int $max Maximum number of feeds to check */ public function set_max_checked_feeds($max = 10) { $this->max_checked_feeds = (int) $max; } public function remove_div($enable = true) { $this->sanitize->remove_div($enable); } public function strip_htmltags($tags = '', $encode = null) { if ($tags === '') { $tags = $this->strip_htmltags; } $this->sanitize->strip_htmltags($tags); if ($encode !== null) { $this->sanitize->encode_instead_of_strip($tags); } } public function encode_instead_of_strip($enable = true) { $this->sanitize->encode_instead_of_strip($enable); } public function strip_attributes($attribs = '') { if ($attribs === '') { $attribs = $this->strip_attributes; } $this->sanitize->strip_attributes($attribs); } /** * Set the output encoding * * Allows you to override SimplePie's output to match that of your webpage. * This is useful for times when your webpages are not being served as * UTF-8. This setting will be obeyed by {@see handle_content_type()}, and * is similar to {@see set_input_encoding()}. * * It should be noted, however, that not all character encodings can support * all characters. If your page is being served as ISO-8859-1 and you try * to display a Japanese feed, you'll likely see garbled characters. * Because of this, it is highly recommended to ensure that your webpages * are served as UTF-8. * * The number of supported character encodings depends on whether your web * host supports {@link http://php.net/mbstring mbstring}, * {@link http://php.net/iconv iconv}, or both. See * {@link http://simplepie.org/wiki/faq/Supported_Character_Encodings} for * more information. * * @param string $encoding */ public function set_output_encoding($encoding = 'UTF-8') { $this->sanitize->set_output_encoding($encoding); } public function strip_comments($strip = false) { $this->sanitize->strip_comments($strip); } /** * Set element/attribute key/value pairs of HTML attributes * containing URLs that need to be resolved relative to the feed * * Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite, * |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite, * |q|@cite * * @since 1.0 * @param array|null $element_attribute Element/attribute key/value pairs, null for default */ public function set_url_replacements($element_attribute = null) { $this->sanitize->set_url_replacements($element_attribute); } /** * Set the handler to enable the display of cached images. * * @param str $page Web-accessible path to the handler_image.php file. * @param str $qs The query string that the value should be passed to. */ public function set_image_handler($page = false, $qs = 'i') { if ($page !== false) { $this->sanitize->set_image_handler($page . '?' . $qs . '='); } else { $this->image_handler = ''; } } /** * Set the limit for items returned per-feed with multifeeds * * @param integer $limit The maximum number of items to return. */ public function set_item_limit($limit = 0) { $this->item_limit = (int) $limit; } /** * Initialize the feed object * * This is what makes everything happen. Period. This is where all of the * configuration options get processed, feeds are fetched, cached, and * parsed, and all of that other good stuff. * * @return boolean True if successful, false otherwise */ public function init() { // Check absolute bare minimum requirements. if (!extension_loaded('xml') || !extension_loaded('pcre')) { return false; } // Then check the xml extension is sane (i.e., libxml 2.7.x issue on PHP < 5.2.9 and libxml 2.7.0 to 2.7.2 on any version) if we don't have xmlreader. elseif (!extension_loaded('xmlreader')) { static $xml_is_sane = null; if ($xml_is_sane === null) { $parser_check = xml_parser_create(); xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values); xml_parser_free($parser_check); $xml_is_sane = isset($values[0]['value']); } if (!$xml_is_sane) { return false; } } if (method_exists($this->sanitize, 'set_registry')) { $this->sanitize->set_registry($this->registry); } // Pass whatever was set with config options over to the sanitizer. // Pass the classes in for legacy support; new classes should use the registry instead $this->sanitize->pass_cache_data($this->cache, $this->cache_location, $this->cache_name_function, $this->registry->get_class('Cache')); $this->sanitize->pass_file_data($this->registry->get_class('File'), $this->timeout, $this->useragent, $this->force_fsockopen); if (!empty($this->multifeed_url)) { $i = 0; $success = 0; $this->multifeed_objects = array(); $this->error = array(); foreach ($this->multifeed_url as $url) { $this->multifeed_objects[$i] = clone $this; $this->multifeed_objects[$i]->set_feed_url($url); $single_success = $this->multifeed_objects[$i]->init(); $success |= $single_success; if (!$single_success) { $this->error[$i] = $this->multifeed_objects[$i]->error(); } $i++; } return (bool) $success; } elseif ($this->feed_url === null && $this->raw_data === null) { return false; } $this->error = null; $this->data = array(); $this->multifeed_objects = array(); $cache = false; if ($this->feed_url !== null) { $parsed_feed_url = $this->registry->call('Misc', 'parse_url', array($this->feed_url)); // Decide whether to enable caching if ($this->cache && $parsed_feed_url['scheme'] !== '') { $cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, call_user_func($this->cache_name_function, $this->feed_url), 'spc')); } // Fetch the data via SimplePie_File into $this->raw_data if (($fetched = $this->fetch_data($cache)) === true) { return true; } elseif ($fetched === false) { return false; } list($headers, $sniffed) = $fetched; } // Set up array of possible encodings $encodings = array(); // First check to see if input has been overridden. if ($this->input_encoding !== false) { $encodings[] = $this->input_encoding; } $application_types = array('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity'); $text_types = array('text/xml', 'text/xml-external-parsed-entity'); // RFC 3023 (only applies to sniffed content) if (isset($sniffed)) { if (in_array($sniffed, $application_types) || substr($sniffed, 0, 12) === 'application/' && substr($sniffed, -4) === '+xml') { if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset)) { $encodings[] = strtoupper($charset[1]); } $encodings = array_merge($encodings, $this->registry->call('Misc', 'xml_encoding', array($this->raw_data, &$this->registry))); $encodings[] = 'UTF-8'; } elseif (in_array($sniffed, $text_types) || substr($sniffed, 0, 5) === 'text/' && substr($sniffed, -4) === '+xml') { if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset)) { $encodings[] = $charset[1]; } $encodings[] = 'US-ASCII'; } // Text MIME-type default elseif (substr($sniffed, 0, 5) === 'text/') { $encodings[] = 'US-ASCII'; } } // Fallback to XML 1.0 Appendix F.1/UTF-8/ISO-8859-1 $encodings = array_merge($encodings, $this->registry->call('Misc', 'xml_encoding', array($this->raw_data, &$this->registry))); $encodings[] = 'UTF-8'; $encodings[] = 'ISO-8859-1'; // There's no point in trying an encoding twice $encodings = array_unique($encodings); // Loop through each possible encoding, till we return something, or run out of possibilities foreach ($encodings as $encoding) { // Change the encoding to UTF-8 (as we always use UTF-8 internally) if ($utf8_data = $this->registry->call('Misc', 'change_encoding', array($this->raw_data, $encoding, 'UTF-8'))) { // Create new parser $parser = $this->registry->create('Parser'); // If it's parsed fine if ($parser->parse($utf8_data, 'UTF-8')) { $this->data = $parser->get_data(); if (!($this->get_type() & ~SIMPLEPIE_TYPE_NONE)) { $this->error = "A feed could not be found at $this->feed_url. This does not appear to be a valid RSS or Atom feed."; $this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, __FILE__, __LINE__)); return false; } if (isset($headers)) { $this->data['headers'] = $headers; } $this->data['build'] = SIMPLEPIE_BUILD; // Cache the file if caching is enabled if ($cache && !$cache->save($this)) { trigger_error("$this->cache_location is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING); } return true; } } } if (isset($parser)) { // We have an error, just set SimplePie_Misc::error to it and quit $this->error = sprintf('This XML document is invalid, likely due to invalid characters. XML error: %s at line %d, column %d', $parser->get_error_string(), $parser->get_current_line(), $parser->get_current_column()); } else { $this->error = 'The data could not be converted to UTF-8. You MUST have either the iconv or mbstring extension installed. Upgrading to PHP 5.x (which includes iconv) is highly recommended.'; } $this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, __FILE__, __LINE__)); return false; } /** * Fetch the data via SimplePie_File * * If the data is already cached, attempt to fetch it from there instead * @param SimplePie_Cache|false $cache Cache handler, or false to not load from the cache * @return array|true Returns true if the data was loaded from the cache, or an array of HTTP headers and sniffed type */ protected function fetch_data(&$cache) { // If it's enabled, use the cache if ($cache) { // Load the Cache $this->data = $cache->load(); if (!empty($this->data)) { // If the cache is for an outdated build of SimplePie if (!isset($this->data['build']) || $this->data['build'] !== SIMPLEPIE_BUILD) { $cache->unlink(); $this->data = array(); } // If we've hit a collision just rerun it with caching disabled elseif (isset($this->data['url']) && $this->data['url'] !== $this->feed_url) { $cache = false; $this->data = array(); } // If we've got a non feed_url stored (if the page isn't actually a feed, or is a redirect) use that URL. elseif (isset($this->data['feed_url'])) { // If the autodiscovery cache is still valid use it. if ($cache->mtime() + $this->autodiscovery_cache_duration > time()) { // Do not need to do feed autodiscovery yet. if ($this->data['feed_url'] !== $this->data['url']) { $this->set_feed_url($this->data['feed_url']); return $this->init(); } $cache->unlink(); $this->data = array(); } } // Check if the cache has been updated elseif ($cache->mtime() + $this->cache_duration < time()) { // If we have last-modified and/or etag set if (isset($this->data['headers']['last-modified']) || isset($this->data['headers']['etag'])) { $headers = array( 'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1', ); if (isset($this->data['headers']['last-modified'])) { $headers['if-modified-since'] = $this->data['headers']['last-modified']; } if (isset($this->data['headers']['etag'])) { $headers['if-none-match'] = $this->data['headers']['etag']; } $file = $this->registry->create('File', array($this->feed_url, $this->timeout/10, 5, $headers, $this->useragent, $this->force_fsockopen)); if ($file->success) { if ($file->status_code === 304) { $cache->touch(); return true; } } else { unset($file); } } } // If the cache is still valid, just return true else { $this->raw_data = false; return true; } } // If the cache is empty, delete it else { $cache->unlink(); $this->data = array(); } } // If we don't already have the file (it'll only exist if we've opened it to check if the cache has been modified), open it. if (!isset($file)) { if ($this->file instanceof SimplePie_File && $this->file->url === $this->feed_url) { $file =& $this->file; } else { $headers = array( 'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1', ); $file = $this->registry->create('File', array($this->feed_url, $this->timeout, 5, $headers, $this->useragent, $this->force_fsockopen)); } } // If the file connection has an error, set SimplePie::error to that and quit if (!$file->success && !($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300))) { $this->error = $file->error; return !empty($this->data); } if (!$this->force_feed) { // Check if the supplied URL is a feed, if it isn't, look for it. $locate = $this->registry->create('Locator', array(&$file, $this->timeout, $this->useragent, $this->max_checked_feeds)); if (!$locate->is_feed($file)) { // We need to unset this so that if SimplePie::set_file() has been called that object is untouched unset($file); try { if (!($file = $locate->find($this->autodiscovery, $this->all_discovered_feeds))) { $this->error = "A feed could not be found at $this->feed_url. A feed with an invalid mime type may fall victim to this error, or " . SIMPLEPIE_NAME . " was unable to auto-discover it.. Use force_feed() if you are certain this URL is a real feed."; $this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, __FILE__, __LINE__)); return false; } } catch (SimplePie_Exception $e) { // This is usually because DOMDocument doesn't exist $this->error = $e->getMessage(); $this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, $e->getFile(), $e->getLine())); return false; } if ($cache) { $this->data = array('url' => $this->feed_url, 'feed_url' => $file->url, 'build' => SIMPLEPIE_BUILD); if (!$cache->save($this)) { trigger_error("$this->cache_location is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING); } $cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, call_user_func($this->cache_name_function, $file->url), 'spc')); } $this->feed_url = $file->url; } $locate = null; } $this->raw_data = $file->body; $headers = $file->headers; $sniffer = $this->registry->create('Content_Type_Sniffer', array(&$file)); $sniffed = $sniffer->get_type(); return array($headers, $sniffed); } /** * Get the error message for the occured error * * @return string|array Error message, or array of messages for multifeeds */ public function error() { return $this->error; } /** * Get the raw XML * * This is the same as the old `$feed->enable_xml_dump(true)`, but returns * the data instead of printing it. * * @return string|boolean Raw XML data, false if the cache is used */ public function get_raw_data() { return $this->raw_data; } /** * Get the character encoding used for output * * @since Preview Release * @return string */ public function get_encoding() { return $this->sanitize->output_encoding; } /** * Send the content-type header with correct encoding * * This method ensures that the SimplePie-enabled page is being served with * the correct {@link http://www.iana.org/assignments/media-types/ mime-type} * and character encoding HTTP headers (character encoding determined by the * {@see set_output_encoding} config option). * * This won't work properly if any content or whitespace has already been * sent to the browser, because it relies on PHP's * {@link http://php.net/header header()} function, and these are the * circumstances under which the function works. * * Because it's setting these settings for the entire page (as is the nature * of HTTP headers), this should only be used once per page (again, at the * top). * * @param string $mime MIME type to serve the page as */ public function handle_content_type($mime = 'text/html') { if (!headers_sent()) { $header = "Content-type: $mime;"; if ($this->get_encoding()) { $header .= ' charset=' . $this->get_encoding(); } else { $header .= ' charset=UTF-8'; } header($header); } } /** * Get the type of the feed * * This returns a SIMPLEPIE_TYPE_* constant, which can be tested against * using {@link http://php.net/language.operators.bitwise bitwise operators} * * @since 0.8 (usage changed to using constants in 1.0) * @see SIMPLEPIE_TYPE_NONE Unknown. * @see SIMPLEPIE_TYPE_RSS_090 RSS 0.90. * @see SIMPLEPIE_TYPE_RSS_091_NETSCAPE RSS 0.91 (Netscape). * @see SIMPLEPIE_TYPE_RSS_091_USERLAND RSS 0.91 (Userland). * @see SIMPLEPIE_TYPE_RSS_091 RSS 0.91. * @see SIMPLEPIE_TYPE_RSS_092 RSS 0.92. * @see SIMPLEPIE_TYPE_RSS_093 RSS 0.93. * @see SIMPLEPIE_TYPE_RSS_094 RSS 0.94. * @see SIMPLEPIE_TYPE_RSS_10 RSS 1.0. * @see SIMPLEPIE_TYPE_RSS_20 RSS 2.0.x. * @see SIMPLEPIE_TYPE_RSS_RDF RDF-based RSS. * @see SIMPLEPIE_TYPE_RSS_SYNDICATION Non-RDF-based RSS (truly intended as syndication format). * @see SIMPLEPIE_TYPE_RSS_ALL Any version of RSS. * @see SIMPLEPIE_TYPE_ATOM_03 Atom 0.3. * @see SIMPLEPIE_TYPE_ATOM_10 Atom 1.0. * @see SIMPLEPIE_TYPE_ATOM_ALL Any version of Atom. * @see SIMPLEPIE_TYPE_ALL Any known/supported feed type. * @return int SIMPLEPIE_TYPE_* constant */ public function get_type() { if (!isset($this->data['type'])) { $this->data['type'] = SIMPLEPIE_TYPE_ALL; if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'])) { $this->data['type'] &= SIMPLEPIE_TYPE_ATOM_10; } elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'])) { $this->data['type'] &= SIMPLEPIE_TYPE_ATOM_03; } elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'])) { if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['channel']) || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['image']) || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['item']) || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['textinput'])) { $this->data['type'] &= SIMPLEPIE_TYPE_RSS_10; } if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['channel']) || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['image']) || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['item']) || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['textinput'])) { $this->data['type'] &= SIMPLEPIE_TYPE_RSS_090; } } elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'])) { $this->data['type'] &= SIMPLEPIE_TYPE_RSS_ALL; if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['attribs']['']['version'])) { switch (trim($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['attribs']['']['version'])) { case '0.91': $this->data['type'] &= SIMPLEPIE_TYPE_RSS_091; if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_20]['skiphours']['hour'][0]['data'])) { switch (trim($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_20]['skiphours']['hour'][0]['data'])) { case '0': $this->data['type'] &= SIMPLEPIE_TYPE_RSS_091_NETSCAPE; break; case '24': $this->data['type'] &= SIMPLEPIE_TYPE_RSS_091_USERLAND; break; } } break; case '0.92': $this->data['type'] &= SIMPLEPIE_TYPE_RSS_092; break; case '0.93': $this->data['type'] &= SIMPLEPIE_TYPE_RSS_093; break; case '0.94': $this->data['type'] &= SIMPLEPIE_TYPE_RSS_094; break; case '2.0': $this->data['type'] &= SIMPLEPIE_TYPE_RSS_20; break; } } } else { $this->data['type'] = SIMPLEPIE_TYPE_NONE; } } return $this->data['type']; } /** * Get the URL for the feed * * May or may not be different from the URL passed to {@see set_feed_url()}, * depending on whether auto-discovery was used. * * @since Preview Release (previously called `get_feed_url()` since SimplePie 0.8.) * @todo If we have a perm redirect we should return the new URL * @todo When we make the above change, let's support <itunes:new-feed-url> as well * @todo Also, |atom:link|@rel=self * @return string|null */ public function subscribe_url() { if ($this->feed_url !== null) { return $this->sanitize($this->feed_url, SIMPLEPIE_CONSTRUCT_IRI); } else { return null; } } /** * Get data for an feed-level element * * This method allows you to get access to ANY element/attribute that is a * sub-element of the opening feed tag. * * The return value is an indexed array of elements matching the given * namespace and tag name. Each element has `attribs`, `data` and `child` * subkeys. For `attribs` and `child`, these contain namespace subkeys. * `attribs` then has one level of associative name => value data (where * `value` is a string) after the namespace. `child` has tag-indexed keys * after the namespace, each member of which is an indexed array matching * this same format. * * For example: * <pre> * // This is probably a bad example because we already support * // <media:content> natively, but it shows you how to parse through * // the nodes. * $group = $item->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'group'); * $content = $group[0]['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content']; * $file = $content[0]['attribs']['']['url']; * echo $file; * </pre> * * @since 1.0 * @see http://simplepie.org/wiki/faq/supported_xml_namespaces * @param string $namespace The URL of the XML namespace of the elements you're trying to access * @param string $tag Tag name * @return array */ public function get_feed_tags($namespace, $tag) { $type = $this->get_type(); if ($type & SIMPLEPIE_TYPE_ATOM_10) { if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag])) { return $this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag]; } } if ($type & SIMPLEPIE_TYPE_ATOM_03) { if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag])) { return $this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag]; } } if ($type & SIMPLEPIE_TYPE_RSS_RDF) { if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag])) { return $this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag]; } } if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION) { if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][$namespace][$tag])) { return $this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][$namespace][$tag]; } } return null; } /** * Get data for an channel-level element * * This method allows you to get access to ANY element/attribute in the * channel/header section of the feed. * * See {@see SimplePie::get_feed_tags()} for a description of the return value * * @since 1.0 * @see http://simplepie.org/wiki/faq/supported_xml_namespaces * @param string $namespace The URL of the XML namespace of the elements you're trying to access * @param string $tag Tag name * @return array */ public function get_channel_tags($namespace, $tag) { $type = $this->get_type(); if ($type & SIMPLEPIE_TYPE_ATOM_ALL) { if ($return = $this->get_feed_tags($namespace, $tag)) { return $return; } } if ($type & SIMPLEPIE_TYPE_RSS_10) { if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'channel')) { if (isset($channel[0]['child'][$namespace][$tag])) { return $channel[0]['child'][$namespace][$tag]; } } } if ($type & SIMPLEPIE_TYPE_RSS_090) { if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'channel')) { if (isset($channel[0]['child'][$namespace][$tag])) { return $channel[0]['child'][$namespace][$tag]; } } } if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION) { if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'channel')) { if (isset($channel[0]['child'][$namespace][$tag])) { return $channel[0]['child'][$namespace][$tag]; } } } return null; } /** * Get data for an channel-level element * * This method allows you to get access to ANY element/attribute in the * image/logo section of the feed. * * See {@see SimplePie::get_feed_tags()} for a description of the return value * * @since 1.0 * @see http://simplepie.org/wiki/faq/supported_xml_namespaces * @param string $namespace The URL of the XML namespace of the elements you're trying to access * @param string $tag Tag name * @return array */ public function get_image_tags($namespace, $tag) { $type = $this->get_type(); if ($type & SIMPLEPIE_TYPE_RSS_10) { if ($image = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'image')) { if (isset($image[0]['child'][$namespace][$tag])) { return $image[0]['child'][$namespace][$tag]; } } } if ($type & SIMPLEPIE_TYPE_RSS_090) { if ($image = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'image')) { if (isset($image[0]['child'][$namespace][$tag])) { return $image[0]['child'][$namespace][$tag]; } } } if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION) { if ($image = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'image')) { if (isset($image[0]['child'][$namespace][$tag])) { return $image[0]['child'][$namespace][$tag]; } } } return null; } /** * Get the base URL value from the feed * * Uses `<xml:base>` if available, otherwise uses the first link in the * feed, or failing that, the URL of the feed itself. * * @see get_link * @see subscribe_url * * @param array $element * @return string */ public function get_base($element = array()) { if (!($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION) && !empty($element['xml_base_explicit']) && isset($element['xml_base'])) { return $element['xml_base']; } elseif ($this->get_link() !== null) { return $this->get_link(); } else { return $this->subscribe_url(); } } /** * Sanitize feed data * * @access private * @see SimplePie_Sanitize::sanitize() * @param string $data Data to sanitize * @param int $type One of the SIMPLEPIE_CONSTRUCT_* constants * @param string $base Base URL to resolve URLs against * @return string Sanitized data */ public function sanitize($data, $type, $base = '') { return $this->sanitize->sanitize($data, $type, $base); } /** * Get the title of the feed * * Uses `<atom:title>`, `<title>` or `<dc:title>` * * @since 1.0 (previously called `get_feed_title` since 0.8) * @return string|null */ public function get_title() { if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } /** * Get a category for the feed * * @since Unknown * @param int $key The category that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Category|null */ public function get_category($key = 0) { $categories = $this->get_categories(); if (isset($categories[$key])) { return $categories[$key]; } else { return null; } } /** * Get all categories for the feed * * Uses `<atom:category>`, `<category>` or `<dc:subject>` * * @since Unknown * @return array|null List of {@see SimplePie_Category} objects */ public function get_categories() { $categories = array(); foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category) { $term = null; $scheme = null; $label = null; if (isset($category['attribs']['']['term'])) { $term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories[] = $this->registry->create('Category', array($term, $scheme, $label)); } foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'category') as $category) { // This is really the label, but keep this as the term also for BC. // Label will also work on retrieving because that falls back to term. $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); if (isset($category['attribs']['']['domain'])) { $scheme = $this->sanitize($category['attribs']['']['domain'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = null; } $categories[] = $this->registry->create('Category', array($term, $scheme, null)); } foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category) { $categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category) { $categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } if (!empty($categories)) { return array_unique($categories); } else { return null; } } /** * Get an author for the feed * * @since 1.1 * @param int $key The author that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Author|null */ public function get_author($key = 0) { $authors = $this->get_authors(); if (isset($authors[$key])) { return $authors[$key]; } else { return null; } } /** * Get all authors for the feed * * Uses `<atom:author>`, `<author>`, `<dc:creator>` or `<itunes:author>` * * @since 1.1 * @return array|null List of {@see SimplePie_Author} objects */ public function get_authors() { $authors = array(); foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author) { $name = null; $uri = null; $email = null; if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) { $name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) { $uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); } if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) { $email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $uri !== null) { $authors[] = $this->registry->create('Author', array($name, $uri, $email)); } } if ($author = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author')) { $name = null; $url = null; $email = null; if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) { $name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) { $url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); } if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) { $email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $url !== null) { $authors[] = $this->registry->create('Author', array($name, $url, $email)); } } foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } if (!empty($authors)) { return array_unique($authors); } else { return null; } } /** * Get a contributor for the feed * * @since 1.1 * @param int $key The contrbutor that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Author|null */ public function get_contributor($key = 0) { $contributors = $this->get_contributors(); if (isset($contributors[$key])) { return $contributors[$key]; } else { return null; } } /** * Get all contributors for the feed * * Uses `<atom:contributor>` * * @since 1.1 * @return array|null List of {@see SimplePie_Author} objects */ public function get_contributors() { $contributors = array(); foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor) { $name = null; $uri = null; $email = null; if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) { $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) { $uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) { $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $uri !== null) { $contributors[] = $this->registry->create('Author', array($name, $uri, $email)); } } foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor) { $name = null; $url = null; $email = null; if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) { $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) { $url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) { $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $url !== null) { $contributors[] = $this->registry->create('Author', array($name, $url, $email)); } } if (!empty($contributors)) { return array_unique($contributors); } else { return null; } } /** * Get a single link for the feed * * @since 1.0 (previously called `get_feed_link` since Preview Release, `get_feed_permalink()` since 0.8) * @param int $key The link that you want to return. Remember that arrays begin with 0, not 1 * @param string $rel The relationship of the link to return * @return string|null Link URL */ public function get_link($key = 0, $rel = 'alternate') { $links = $this->get_links($rel); if (isset($links[$key])) { return $links[$key]; } else { return null; } } /** * Get the permalink for the item * * Returns the first link available with a relationship of "alternate". * Identical to {@see get_link()} with key 0 * * @see get_link * @since 1.0 (previously called `get_feed_link` since Preview Release, `get_feed_permalink()` since 0.8) * @internal Added for parity between the parent-level and the item/entry-level. * @return string|null Link URL */ public function get_permalink() { return $this->get_link(0); } /** * Get all links for the feed * * Uses `<atom:link>` or `<link>` * * @since Beta 2 * @param string $rel The relationship of links to return * @return array|null Links found for the feed (strings) */ public function get_links($rel = 'alternate') { if (!isset($this->data['links'])) { $this->data['links'] = array(); if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link')) { foreach ($links as $link) { if (isset($link['attribs']['']['href'])) { $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); } } } if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link')) { foreach ($links as $link) { if (isset($link['attribs']['']['href'])) { $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); } } } if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } $keys = array_keys($this->data['links']); foreach ($keys as $key) { if ($this->registry->call('Misc', 'is_isegment_nz_nc', array($key))) { if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key])) { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]); $this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]; } else { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key]; } } elseif (substr($key, 0, 41) === SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY) { $this->data['links'][substr($key, 41)] =& $this->data['links'][$key]; } $this->data['links'][$key] = array_unique($this->data['links'][$key]); } } if (isset($this->data['links'][$rel])) { return $this->data['links'][$rel]; } else { return null; } } public function get_all_discovered_feeds() { return $this->all_discovered_feeds; } /** * Get the content for the item * * Uses `<atom:subtitle>`, `<atom:tagline>`, `<description>`, * `<dc:description>`, `<itunes:summary>` or `<itunes:subtitle>` * * @since 1.0 (previously called `get_feed_description()` since 0.8) * @return string|null */ public function get_description() { if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'subtitle')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'tagline')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } else { return null; } } /** * Get the copyright info for the feed * * Uses `<atom:rights>`, `<atom:copyright>` or `<dc:rights>` * * @since 1.0 (previously called `get_feed_copyright()` since 0.8) * @return string|null */ public function get_copyright() { if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'copyright')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'copyright')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } /** * Get the language for the feed * * Uses `<language>`, `<dc:language>`, or @xml_lang * * @since 1.0 (previously called `get_feed_language()` since 0.8) * @return string|null */ public function get_language() { if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'language')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'language')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'language')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['xml_lang'])) { return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['xml_lang'])) { return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['xml_lang'])) { return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($this->data['headers']['content-language'])) { return $this->sanitize($this->data['headers']['content-language'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } /** * Get the latitude coordinates for the item * * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications * * Uses `<geo:lat>` or `<georss:point>` * * @since 1.0 * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo * @link http://www.georss.org/ GeoRSS * @return string|null */ public function get_latitude() { if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat')) { return (float) $return[0]['data']; } elseif (($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) { return (float) $match[1]; } else { return null; } } /** * Get the longitude coordinates for the feed * * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications * * Uses `<geo:long>`, `<geo:lon>` or `<georss:point>` * * @since 1.0 * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo * @link http://www.georss.org/ GeoRSS * @return string|null */ public function get_longitude() { if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long')) { return (float) $return[0]['data']; } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon')) { return (float) $return[0]['data']; } elseif (($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) { return (float) $match[2]; } else { return null; } } /** * Get the feed logo's title * * RSS 0.9.0, 1.0 and 2.0 feeds are allowed to have a "feed logo" title. * * Uses `<image><title>` or `<image><dc:title>` * * @return string|null */ public function get_image_title() { if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } /** * Get the feed logo's URL * * RSS 0.9.0, 2.0, Atom 1.0, and feeds with iTunes RSS tags are allowed to * have a "feed logo" URL. This points directly to the image itself. * * Uses `<itunes:image>`, `<atom:logo>`, `<atom:icon>`, * `<image><title>` or `<image><dc:title>` * * @return string|null */ public function get_image_url() { if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'image')) { return $this->sanitize($return[0]['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'logo')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'icon')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'url')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'url')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'url')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } else { return null; } } /** * Get the feed logo's link * * RSS 0.9.0, 1.0 and 2.0 feeds are allowed to have a "feed logo" link. This * points to a human-readable page that the image should link to. * * Uses `<itunes:image>`, `<atom:logo>`, `<atom:icon>`, * `<image><title>` or `<image><dc:title>` * * @return string|null */ public function get_image_link() { if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'link')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } else { return null; } } /** * Get the feed logo's link * * RSS 2.0 feeds are allowed to have a "feed logo" width. * * Uses `<image><width>` or defaults to 88.0 if no width is specified and * the feed is an RSS 2.0 feed. * * @return int|float|null */ public function get_image_width() { if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'width')) { return round($return[0]['data']); } elseif ($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION && $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'url')) { return 88.0; } else { return null; } } /** * Get the feed logo's height * * RSS 2.0 feeds are allowed to have a "feed logo" height. * * Uses `<image><height>` or defaults to 31.0 if no height is specified and * the feed is an RSS 2.0 feed. * * @return int|float|null */ public function get_image_height() { if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'height')) { return round($return[0]['data']); } elseif ($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION && $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'url')) { return 31.0; } else { return null; } } /** * Get the number of items in the feed * * This is well-suited for {@link http://php.net/for for()} loops with * {@see get_item()} * * @param int $max Maximum value to return. 0 for no limit * @return int Number of items in the feed */ public function get_item_quantity($max = 0) { $max = (int) $max; $qty = count($this->get_items()); if ($max === 0) { return $qty; } else { return ($qty > $max) ? $max : $qty; } } /** * Get a single item from the feed * * This is better suited for {@link http://php.net/for for()} loops, whereas * {@see get_items()} is better suited for * {@link http://php.net/foreach foreach()} loops. * * @see get_item_quantity() * @since Beta 2 * @param int $key The item that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Item|null */ public function get_item($key = 0) { $items = $this->get_items(); if (isset($items[$key])) { return $items[$key]; } else { return null; } } /** * Get all items from the feed * * This is better suited for {@link http://php.net/for for()} loops, whereas * {@see get_items()} is better suited for * {@link http://php.net/foreach foreach()} loops. * * @see get_item_quantity * @since Beta 2 * @param int $start Index to start at * @param int $end Number of items to return. 0 for all items after `$start` * @return array|null List of {@see SimplePie_Item} objects */ public function get_items($start = 0, $end = 0) { if (!isset($this->data['items'])) { if (!empty($this->multifeed_objects)) { $this->data['items'] = SimplePie::merge_items($this->multifeed_objects, $start, $end, $this->item_limit); } else { $this->data['items'] = array(); if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'entry')) { $keys = array_keys($items); foreach ($keys as $key) { $this->data['items'][] = $this->registry->create('Item', array($this, $items[$key])); } } if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'entry')) { $keys = array_keys($items); foreach ($keys as $key) { $this->data['items'][] = $this->registry->create('Item', array($this, $items[$key])); } } if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'item')) { $keys = array_keys($items); foreach ($keys as $key) { $this->data['items'][] = $this->registry->create('Item', array($this, $items[$key])); } } if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'item')) { $keys = array_keys($items); foreach ($keys as $key) { $this->data['items'][] = $this->registry->create('Item', array($this, $items[$key])); } } if ($items = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'item')) { $keys = array_keys($items); foreach ($keys as $key) { $this->data['items'][] = $this->registry->create('Item', array($this, $items[$key])); } } } } if (!empty($this->data['items'])) { // If we want to order it by date, check if all items have a date, and then sort it if ($this->order_by_date && empty($this->multifeed_objects)) { if (!isset($this->data['ordered_items'])) { $do_sort = true; foreach ($this->data['items'] as $item) { if (!$item->get_date('U')) { $do_sort = false; break; } } $item = null; $this->data['ordered_items'] = $this->data['items']; if ($do_sort) { usort($this->data['ordered_items'], array(get_class($this), 'sort_items')); } } $items = $this->data['ordered_items']; } else { $items = $this->data['items']; } // Slice the data as desired if ($end === 0) { return array_slice($items, $start); } else { return array_slice($items, $start, $end); } } else { return array(); } } /** * Set the favicon handler * * @deprecated Use your own favicon handling instead */ public function set_favicon_handler($page = false, $qs = 'i') { $level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING; trigger_error('Favicon handling has been removed, please use your own handling', $level); return false; } /** * Get the favicon for the current feed * * @deprecated Use your own favicon handling instead */ public function get_favicon() { $level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING; trigger_error('Favicon handling has been removed, please use your own handling', $level); if (($url = $this->get_link()) !== null) { return 'http://g.etfv.co/' . urlencode($url); } return false; } /** * Magic method handler * * @param string $method Method name * @param array $args Arguments to the method * @return mixed */ public function __call($method, $args) { if (strpos($method, 'subscribe_') === 0) { $level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING; trigger_error('subscribe_*() has been deprecated, implement the callback yourself', $level); return ''; } if ($method === 'enable_xml_dump') { $level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING; trigger_error('enable_xml_dump() has been deprecated, use get_raw_data() instead', $level); return false; } $class = get_class($this); $trace = debug_backtrace(); $file = $trace[0]['file']; $line = $trace[0]['line']; trigger_error("Call to undefined method $class::$method() in $file on line $line", E_USER_ERROR); } /** * Sorting callback for items * * @access private * @param SimplePie $a * @param SimplePie $b * @return boolean */ public static function sort_items($a, $b) { return $a->get_date('U') <= $b->get_date('U'); } /** * Merge items from several feeds into one * * If you're merging multiple feeds together, they need to all have dates * for the items or else SimplePie will refuse to sort them. * * @link http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date#if_feeds_require_separate_per-feed_settings * @param array $urls List of SimplePie feed objects to merge * @param int $start Starting item * @param int $end Number of items to return * @param int $limit Maximum number of items per feed * @return array */ public static function merge_items($urls, $start = 0, $end = 0, $limit = 0) { if (is_array($urls) && sizeof($urls) > 0) { $items = array(); foreach ($urls as $arg) { if ($arg instanceof SimplePie) { $items = array_merge($items, $arg->get_items(0, $limit)); } else { trigger_error('Arguments must be SimplePie objects', E_USER_WARNING); } } $do_sort = true; foreach ($items as $item) { if (!$item->get_date('U')) { $do_sort = false; break; } } $item = null; if ($do_sort) { usort($items, array(get_class($urls[0]), 'sort_items')); } if ($end === 0) { return array_slice($items, $start); } else { return array_slice($items, $start, $end); } } else { trigger_error('Cannot merge zero SimplePie objects', E_USER_WARNING); return array(); } } }
b13/t3ext-newsfeedimport
Classes/SimplePie/library/SimplePie.php
PHP
mit
88,133
#include "ObservationSequences.h" #include <iostream> #include <fstream> #include <algorithm> #include "boost\filesystem.hpp" using namespace std; namespace bst = boost::filesystem; ObservationSequences::~ObservationSequences() { } ObservationSequences::ObservationSequences(std::string folderName) { noOfFiles = 0; noOfTrainingFiles = 0; noOfScoringFiles = 0; this->malwareFamilyName = folderName; } void ObservationSequences::getFileList() { string folderName = "D:/Aditya/CS_266/Project/Dataset/" + this->malwareFamilyName + "/"; cout << folderName << endl; bst::path p(folderName); for (auto i = bst::directory_iterator(p); i != bst::directory_iterator(); i++) { if (!bst::is_directory(i->path())) { string fullFileName = folderName + i->path().filename().string(); this->fileNameList.push_back(fullFileName); } } } void ObservationSequences::getFileStream() { this->noOfFiles = this->fileNameList.size(); for (int index = 0; index < this->noOfFiles; index++) { vector<int> tempFileStream; vector<string> opCodeStream; string tempFileName = this->fileNameList.at(index); ifstream tempReadFile; tempReadFile.open(tempFileName); string line; while (getline(tempReadFile, line)) { int opCodeIndex = find(this->distinctOpCodesList.begin(), this->distinctOpCodesList.end(), line) - this->distinctOpCodesList.begin(); int endIndex = this->distinctOpCodesList.size(); if (opCodeIndex != endIndex) { tempFileStream.push_back(opCodeIndex); } else { this->distinctOpCodesList.push_back(line); int newOpCodeIndex = this->distinctOpCodesList.size()-1; tempFileStream.push_back(newOpCodeIndex); } opCodeStream.push_back(line); } this->obsSequenceList.push_back(tempFileStream); } cout << this->distinctOpCodesList.size(); }
anish-shekhawat/hmm-adaboost
src/ObservationSequences.cpp
C++
mit
1,824
#!/bin/bash docker build -t chamerling/openstack-client .
chamerling/openstack-client-docker
build.sh
Shell
mit
58
'use strict' angular .module('softvApp') .controller('ModalAddhubCtrl', function (clusterFactory, tapFactory, $rootScope, areaTecnicaFactory, $uibModalInstance, opcion, ngNotify, $state) { function init() { if (opcion.opcion === 1) { vm.blockForm2 = true; muestraColonias(); muestrarelaciones(); vm.Titulo = 'Nuevo HUB'; } else if (opcion.opcion === 2) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { console.log(); vm.blockForm2 = false; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Editar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } else if (opcion.opcion === 3) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { vm.blockForm2 = true; vm.blocksave = true; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Consultar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } } function muestraColonias() { areaTecnicaFactory.GetMuestraColoniaHub(0, 0, 0) .then(function (data) { vm.colonias = data.GetMuestraColoniaHubResult; }); } function AddSector() { if (opcion.opcion === 1) { areaTecnicaFactory.GetNueHub(0, vm.Clv_Txt, vm.Descripcion).then(function (data) { if (data.GetNueHubResult > 0) { vm.clv_hub = data.GetNueHubResult; ngNotify.set('El HUB se ha registrado correctamente ,ahora puedes agregar la relación con las colonias', 'success'); $rootScope.$broadcast('reloadlista'); vm.blockForm2 = false; vm.blocksave = true; } else { ngNotify.set('La clave del HUB ya existe', 'error'); } }); } else if (opcion.opcion === 2) { areaTecnicaFactory.GetModHub(vm.clv_hub, vm.Clv_Txt, vm.Descripcion).then(function (data) { console.log(data); ngNotify.set('El HUB se ha editado correctamente', 'success'); $rootScope.$broadcast('reloadlista'); $uibModalInstance.dismiss('cancel'); }); } } function cancel() { $uibModalInstance.dismiss('cancel'); } function validaRelacion(clv) { var count = 0; vm.RelColonias.forEach(function (item) { count += (item.IdColonia === clv) ? 1 : 0; }); return (count > 0) ? true : false; } function NuevaRelacionSecColonia() { if (validaRelacion(vm.Colonia.IdColonia) === true) { ngNotify.set('La relación HUB-COLONIA ya esta establecida', 'warn'); return; } areaTecnicaFactory.GetNueRelHubColonia(vm.clv_hub, vm.Colonia.IdColonia) .then(function (data) { muestrarelaciones(); ngNotify.set('se agrego la relación correctamente', 'success'); }); } function muestrarelaciones() { areaTecnicaFactory.GetConRelHubColonia(vm.clv_hub) .then(function (rel) { console.log(rel); vm.RelColonias = rel.GetConRelHubColoniaResult; }); } function deleterelacion(clv) { clusterFactory.GetQuitarEliminarRelClusterSector(2, vm.clv_cluster, clv).then(function (data) { ngNotify.set('Se eliminó la relación correctamente', 'success'); muestrarelaciones(); }); } var vm = this; init(); vm.cancel = cancel; vm.clv_hub = 0; vm.RelColonias = []; vm.AddSector = AddSector; vm.NuevaRelacionSecColonia = NuevaRelacionSecColonia; });
alesabas/Softv
app/scripts/controllers/areatecnica/ModalAddhubCtrl.js
JavaScript
mit
3,930
require 'spec_helper' require 'rails_helper' require 'email_helper' describe CommitteeController do fixtures :users fixtures :meetings fixtures :committees fixtures :announcements fixtures :participations before(:each) do sign_in users(:tester) # allow to do production mode allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new('production')) @committee = Committee.create!({name: "Nice", hidden: true, inactive: true}) @test_admin = User.find_by(name: "Rspec_admin") @test_committee = Committee.find_by(name: "Nice") end describe 'new committee' do it 'renders the new committee template' do get :new_committee expect(response).to render_template("new_committee") end # it 'redirects non-admin users' do # sign_in users(:user) # get :new_committee # expect(response).to redirect_to root_path # sign_out users(:user) # end end describe 'create committee' do it 'redirects to the committee index page' do post :create_committee, params: {committee: {name: "Good Committee"}} expect(response).to redirect_to(committee_index_path) end it 'should not allow a blank name field' do post :create_committee, params: {committee: {name: ""}} expect(flash[:notice]).to eq("Committee name field cannot be blank.") expect(response).to redirect_to(new_committee_path) end it 'should not allow an already used committee name field' do expect(Committee).to receive(:has_name?).with("Good Committee").and_return(true) post :create_committee, params: {committee: {name: "Good Committee"}} expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.") expect(response).to redirect_to(new_committee_path) end it 'creates a committee' do expect(Committee).to receive(:create!).with(name: "Good Committee", :description => nil, :hidden => true, :inactive => true) post :create_committee, params: {committee: {name: "Good Committee"}} expect(flash[:notice]).to eq("Committee Good Committee was successfully created!") end it 'redirects non-admin users' do sign_in users(:user) post :create_committee, params: {committee: {name: "Good Committee"}} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'CRUD create committee' do it 'redirects to the committee index page' do post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"} expect(response).to redirect_to(committee_index_path) end it 'should not allow a blank name field' do post :crud_committee, params: {committee: {name: ""}, do_action: "create"} expect(flash[:notice]).to eq("Committee name field cannot be blank.") expect(response).to redirect_to(new_committee_path) end it 'should not allow an already used committee name field' do expect(Committee).to receive(:has_name?).with("Good Committee").and_return(true) post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"} expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.") expect(response).to redirect_to(new_committee_path) end it 'creates a committee' do expect(Committee).to receive(:create!).with(name: "Good Committee", :description => nil, :hidden => true, :inactive => true) post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"} expect(flash[:notice]).to eq("Committee Good Committee was successfully created!") end it 'redirects non-admin users' do sign_in users(:user) post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'edit committee' do it 'renders the edit committee template' do get :edit_committee, params: {id: @test_committee.id} expect(response).to render_template("edit_committee") end it 'redirects non-admin users' do sign_in users(:user) get :edit_committee, params: {id: @test_committee.id} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'update committee' do it 'redirects to the committee index page' do put :update_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}} expect(response).to redirect_to(committee_index_path) end it 'should not allow a blank name field' do put :update_committee, params: {id: @test_committee.id, committee: {name: ""}} expect(flash[:notice]).to eq("Please fill in the committee name field.") expect(response).to redirect_to(edit_committee_path) end it 'should not allow an already used committee name field' do expect(Committee).to receive(:has_name?).with("Nice").and_return true put :update_committee, params: {id: @test_committee.id, committee: {name: "Nice"}} expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.") expect(response).to redirect_to(edit_committee_path) end it 'updates the committee' do put :update_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}} expect(response).to redirect_to(committee_index_path) end it 'redirects non-admin users' do sign_in users(:user) put :update_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'CRUD update committee' do it 'redirects to the committee index page' do put :crud_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}, do_action: "update"} expect(response).to redirect_to(committee_index_path) end it 'should not allow a blank name field' do put :crud_committee, params: {id: @test_committee.id, committee: {name: ""}, do_action: "update"} expect(flash[:notice]).to eq("Please fill in the committee name field.") expect(response).to redirect_to(edit_committee_path) end it 'should not allow an already used committee name field' do expect(Committee).to receive(:has_name?).with("Nice").and_return true put :crud_committee, params: {id: @test_committee.id, committee: {name: "Nice"}, do_action: "update"} expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.") expect(response).to redirect_to(edit_committee_path) end it 'updates the committee' do put :crud_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}, do_action: "update"} expect(response).to redirect_to(committee_index_path) end it 'updates the committee description' do put :crud_committee, params: {id: @test_committee.id, committee: {name: "Nice", description: "I am making new description"}, do_action: "update"} expect(response).to redirect_to(committee_index_path) end it 'redirects non-admin users' do sign_in users(:user) put :crud_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}, do_action: "update"} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'delete committee' do it 'redirects to the committee index page' do delete :delete_committee, params: {id: @test_committee.id} expect(response).to redirect_to(committee_index_path) end it "shows a flash delete message when committee successfully deleted" do delete :delete_committee, params: {id: @test_committee.id} expect(flash[:notice]).to eq("Committee with name Nice deleted successfully.") end it 'redirects non-admin users' do sign_in users(:user) delete :delete_committee, params: {id: @test_committee.id} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'CRUD delete committee' do it 'redirects to the committee index page' do delete :crud_committee, params: {id: @test_committee.id, do_action: "delete"} expect(response).to redirect_to(committee_index_path) end it "shows a flash delete message when committee successfully deleted" do delete :crud_committee, params: {id: @test_committee.id, do_action: "delete"} expect(flash[:notice]).to eq("Committee with name Nice deleted successfully.") end it 'redirects non-admin users' do sign_in users(:user) delete :crud_committee, params: {id: @test_committee.id, do_action: "delete"} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'hide committee' do it 'redirects to the committee index page' do get :action_committee, params: {id: @test_committee.id, do_action: 'hide'} expect(response).to redirect_to(committee_index_path) end it 'shows a flash message when committee successfully hidden' do get :action_committee, params: {id: @test_committee.id, do_action: 'hide'} expect(flash[:notice]).to eq("Nice successfully hidden.") end it 'sets the committee\'s hidden attribute to true' do expect_any_instance_of(Committee).to receive(:hide) get :action_committee, params: {id: @test_committee.id, do_action: 'hide'} end it 'redirects non-admin users' do sign_in users(:user) get :action_committee, params: {id: @test_committee.id, do_action: 'hide'} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'show committee' do it 'redirects to the committee index page' do get :action_committee, params: {id: @test_committee.id, do_action: 'show'} expect(response).to redirect_to(committee_index_path) end it 'shows a flash message when committee successfully shown' do get :action_committee, params: {id: @test_committee.id, do_action: 'show'} expect(flash[:notice]).to eq("Nice successfully shown.") end it 'sets the committee\'s hidden attribute to false' do expect_any_instance_of(Committee).to receive(:show) get :action_committee, params: {id: @test_committee.id, do_action: 'show'} end it 'redirects non-admin users' do sign_in users(:user) get :action_committee, params: {id: @test_committee.id, do_action: 'show'} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'activate committee' do it 'redirects to the committee index page' do get :action_committee, params: {id: @test_committee.id, do_action: 'active'} expect(response).to redirect_to(committee_index_path) end it 'shows a flash message when committee successfully active' do get :action_committee, params: {id: @test_committee.id, do_action: 'active'} expect(flash[:notice]).to eq("Nice successfully made active.") end it 'sets the committee\'s hidden attribute to true' do expect_any_instance_of(Committee).to receive(:activate) get :action_committee, params: {id: @test_committee.id, do_action: 'active'} end it 'redirects non-admin users' do sign_in users(:user) get :action_committee, params: {id: @test_committee.id, do_action: 'active'} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'Inactivate committee' do it 'redirects to the committee index page' do get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'} expect(response).to redirect_to(committee_index_path) end it 'shows a flash message when committee successfully inactive' do get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'} expect(flash[:notice]).to eq("Nice successfully made inactive.") end it 'sets the committee\'s hidden attribute to false' do expect_any_instance_of(Committee).to receive(:inactivate) get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'} end it 'redirects non-admin users' do sign_in users(:user) get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'} expect(response).to redirect_to dashboard_index_path sign_out users(:user) end end describe 'Add committee member' do it 'shows a flash message when all members are successfully added to committee' do test_user = User.find_by(name: "Rspec_user") test_admin = User.find_by(name: "Rspec_admin") allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new('production')) # puts test_user.id: 227792459 # puts test_admin.id: 1011897928 put :update_members, params: {id: @test_committee.id, check: {"227792459": 1, "1011897928": 1}} expect(flash[:notice]).to eq("Successfully updated members in #{@test_committee.name}.") end it 'remove all the members in committee' do test_user = User.find_by(name: "Rspec_user") test_admin = User.find_by(name: "Rspec_admin") put :update_members, params: {id: @test_committee.id, check: {"227792459": 0, "1011897928": 0}} expect(flash[:notice]).to eq("Successfully updated members in #{@test_committee.name}.") end end end
hsp1324/communitygrows
spec/controllers/committee_controller_spec.rb
Ruby
mit
13,782
/* * The MIT License (MIT) * * Copyright (c) 2015 Lachlan Dowding * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package permafrost.tundra.math; import java.text.MessageFormat; /** * A collection of convenience methods for working with integers. */ public final class IntegerHelper { /** * The default value used when parsing a null string. */ private static int DEFAULT_INT_VALUE = 0; /** * Disallow instantiation of this class. */ private IntegerHelper() {} /** * Converts the given object to a Integer. * * @param object The object to be converted. * @return The converted object. */ public static Integer normalize(Object object) { Integer value = null; if (object instanceof Number) { value = ((Number)object).intValue(); } else if (object instanceof String) { value = parse((String)object); } return value; } /** * Parses the given string as an integer. * * @param input A string to be parsed as integer. * @return Integer representing the given string, or 0 if the given string was null. */ public static int parse(String input) { return parse(input, DEFAULT_INT_VALUE); } /** * Parses the given string as an integer. * * @param input A string to be parsed as integer. * @param defaultValue The value returned if the given string is null. * @return Integer representing the given string, or defaultValue if the given string is null. */ public static int parse(String input, int defaultValue) { if (input == null) return defaultValue; return Integer.parseInt(input); } /** * Parses the given strings as integers. * * @param input A list of strings to be parsed as integers. * @return A list of integers representing the given strings. */ public static int[] parse(String[] input) { return parse(input, DEFAULT_INT_VALUE); } /** * Parses the given strings as integers. * * @param input A list of strings to be parsed as integers. * @param defaultValue The value returned if a string in the list is null. * @return A list of integers representing the given strings. */ public static int[] parse(String[] input, int defaultValue) { if (input == null) return null; int[] output = new int[input.length]; for (int i = 0; i < input.length; i++) { output[i] = parse(input[i], defaultValue); } return output; } /** * Serializes the given integer as a string. * * @param input The integer to be serialized. * @return A string representation of the given integer. */ public static String emit(int input) { return Integer.toString(input); } /** * Serializes the given integers as strings. * * @param input A list of integers to be serialized. * @return A list of string representations of the given integers. */ public static String[] emit(int[] input) { if (input == null) return null; String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) { output[i] = emit(input[i]); } return output; } }
Permafrost/Tundra.java
src/main/java/permafrost/tundra/math/IntegerHelper.java
Java
mit
4,471
'use strict'; var path = require('path'); var fs = require('fs'); module.exports = function(gen,cb) { var sections; if (gen.config.get('framework')==='bigwheel') { var model = require(path.join(process.cwd(),'src/model/index.js')); sections = ['Preloader']; Object.keys(model).forEach(function(key) { if (key.charAt(0)==="/") sections.push(key.substr(1) || 'Landing'); }); } else { sections = ['Landing']; } nextSection(sections,gen,cb); }; function nextSection(arr,gen,cb) { if (arr.length>0) { createSection(arr.shift(),gen,function() { nextSection(arr,gen,cb); }); } else { if (cb) cb(); } } function createSection(cur,gen,cb) { var name = gen.config.get('sectionNames') ? '{{section}}.js' : 'index.js'; var style = gen.config.get('sectionNames') ? '{{section}}.{{css}}' : 'style.{{css}}'; var count = 0; var total = 0; var done = function() { count++; if (count>=total) cb(); }; fs.stat('src/sections/'+cur+'/',function(err,stat) { if (err) { gen.config.set('section',cur); if (gen.config.get('framework')==='bigwheel') { var type = cur==='Preloader' ? 'preloader' : 'normal'; gen.copy('templates/sections/{{framework}}/'+type+'/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/'+type+'/style.css','src/sections/{{section}}/'+style,done); gen.copy('templates/sections/{{framework}}/'+type+'/template.hbs','src/sections/{{section}}/template.hbs',done); gen.copy('templates/.gitkeep','src/ui/{{section}}/.gitkeep',done); total += 4; } else if (gen.config.get('framework')==='react') { gen.copy('templates/sections/{{framework}}/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/style.css','src/sections/{{section}}/'+style,done); total += 2; } } else { done(); } }); };
Jam3/generator-jam3
lib/createSections.js
JavaScript
mit
1,958
<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Aarthi Gurusami</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="../stylesheets/stylesheet.css"> <link rel = "stylesheet" type = "text/css" href = "../stylesheets/stylesheet-mobile.css"> <link rel="stylesheet" type="text/css" href="../stylesheets/blog-template-stylesheet.css"> <link rel="stylesheet" type="text/css" href="../stylesheets/blog-template-mobile.css"> <script type = "text/javascript" src = "../stylesheets/default-with-subfolders.js"></script> <script type = "text/javascript" src = "../stylesheets/blog-post.js"></script> </head> <body> <nav class = "main_nav"> <ul class="transition"> <li id= "first"><a href="../index.html">home</a> <li id="second"><a href="../about.html">about</a></li> <li id="third"><a href="index.html">blog</a></li> <li id="fourth"><a href="../projects/index.html">projects</a></li> <li id = "resume"><a href="https://resume.creddle.io/resume/fgzuvelzjsf">resume</a></li> <li id = "contact"><a href="../contact.html">contact</a></li> </ul> </nav> <header> <h1> What's it like to blog? </h1> <h2> 04/08/2016. </h2> </header> <main> <figure> <img src="imgs/sample-image.png" alt= ""> <br> <figcaption> blog. </figcaption> </figure> <p> I enjoy how much more I learn when I'm blogging for an audience. It helps me understand concepts I was having a lot of trouble with, and I typically find myself wanting to go above and beyond to help them understand new concepts. </p> <p> That being said, it's incredibly cumbersome to go through multiple drafts of the same post, and make sure each line of code is as succinct and "pretty" as it should be for an audience. </p> <p> I learned a lot through this process, both technically and personally. I felt like I developed a fun and interesting blogging style, and had really dig into some creative juices to make these topics interesting. It was a really nice way to combine my new found technical knowledge with my artistic and communication skills! </p> <div id = "tabs"> <ul id = "tab"> <li id = "previous"><a href = "">Previous</a></li> <li id = "next"><a href = "">Next</a></li> </ul> </div> </main> <footer> <p> Aarthi Gurusami <br> (607) 738-9214 </p> </footer> <nav> <aside> <h2>other posts.</h2> <ul> <li><a href="git.html">Gits Using Git</a></li> <li><a href="css-concepts.html">Elements With Benefits</a></li> <li><a href="arrays-hashes.html">#hashlikeyoumeanit</a></li> <li><a href="enumerable-methods.html">Paul: Give me my money.</a></li> <li><a href="ruby-classes.html">I'm drunk.</a></li> <li><a href="javascript.html">I'm not drunk, but I could be.</a></li> <li><a href="tech.html">toma[yh]to.</a></li> </ul> </aside> </nav> </body> </html>
agurusa/agurusa.github.io
blog/blogging.html
HTML
mit
3,010
{% extends "../base.html" %} {% block content %} <div class="row"> <div class="col-sm-6"> <legend translate>Platform Information</legend> <!--ajax_result--> <div class="ajax_result"> {% if msg %} <div class="alert alert-info" role="alert">{{msg}}</div> {% endif %} <table width="100%" class="table table-striped table-hover"> <thead> <tr> <th translate>Height</th> <th translate>Millimeter</th> <th translate>Pulse</th> </tr> </thead> <tbody> <tr> <td translate>Zero Level</td> <td>0</td> <td>0</td> </tr> <tr class="success"> <td translate>Current</td> <td><b>{{CurrentHeightMm}}</b></td> <td><b>{{Status.CurrentHeight}}</b></td> </tr> <tr> <td translate>End Level</td> <td><b>{{ZAxisHeightMm}}</b></td> <td><b>{{Config.ZAxisHeight}}</b></td> </tr> </tbody> </table> {% if ZAxisPin %} <br> <a href="/z-axis/touch-limit" type="button" class="btn btn-primary" translate>Calibrate Zero Position ⇧</a> <br> <br> <legend translate>Save Z Axis Calibration</legend> <a href="/z-axis/calibrate" class="btn btn-danger btn-lg ask" data-ask="measure-confirm" role="button" translate>Measure Z-Axis Length ⇧ </a> <translate class="hide" id="measure-confirm">Are you sure you want to set this height as the bottom?</translate> <br> <br> {% if ZAxisEnable>0 %} <a href="/z-axis/enable/1" type="button" class="btn btn-success" translate>Enable Motor</a> &nbsp; <a href="/z-axis/enable/0" type="button" class="btn btn-warning" translate>Disable Motor</a> {% endif %} {% endif %} </div> <!--ajax_result--> <br><br> {{ buttonsView(buttons,"/z-calibration") }} </div> <div class="col-sm-6"> <legend translate>Move</legend> <div class="row calibration"> <div class="col-xs-6 right_link"> <a href="/z-axis/bottom" type="button" class="btn btn-danger btn-sm" translate>Floor ⇩</a> <a href="/z-axis/move/down/micron/200000" type="button" class="btn btn-warning btn-sm">200mm ⇩</a> <a href="/z-axis/move/down/micron/100000" type="button" class="btn btn-warning btn-sm">100mm ⇩</a> <a href="/z-axis/move/down/micron/50000" type="button" class="btn btn-warning btn-sm">50mm ⇩</a> <a href="/z-axis/move/down/micron/10000" type="button" class="btn btn-warning btn-sm">10mm ⇩</a> <a href="/z-axis/move/down/micron/1000" type="button" class="btn btn-warning btn-sm">1mm ⇩</a> <a href="/z-axis/move/down/micron/500" type="button" class="btn btn-warning btn-sm">0.5mm ⇩</a> <a href="/z-axis/move/down/micron/100" type="button" class="btn btn-warning btn-sm">0.1mm ⇩</a> <a href="/z-axis/move/down/pulse/100" type="button" class="btn btn-warning btn-sm side_left" translate>100 Pulse ⇩</a> <a href="/z-axis/move/down/pulse/10" type="button" class="btn btn-warning btn-sm side_left" translate>10 Pulse ⇩</a> <a href="/z-axis/move/down/pulse/1" type="button" class="btn btn-warning btn-sm side_left" translate>1 Pulse ⇩</a> </div> <div class="col-xs-6 left_link"> <a href="/z-axis/top" type="button" class="btn btn-primary btn-sm" translate>Top ⇧</a> <a href="/z-axis/move/up/micron/200000" type="button" class="btn btn-success btn-sm">200mm ⇧</a> <a href="/z-axis/move/up/micron/100000" type="button" class="btn btn-success btn-sm">100mm ⇧</a> <a href="/z-axis/move/up/micron/50000" type="button" class="btn btn-success btn-sm">50mm ⇧</a> <a href="/z-axis/move/up/micron/10000" type="button" class="btn btn-success btn-sm">10mm ⇧</a> <a href="/z-axis/move/up/micron/1000" type="button" class="btn btn-success btn-sm">1mm ⇧</a> <a href="/z-axis/move/up/micron/500" type="button" class="btn btn-success btn-sm">0.5mm ⇧</a> <a href="/z-axis/move/up/micron/100" type="button" class="btn btn-success btn-sm">0.1mm ⇧</a> <a href="/z-axis/move/up/pulse/100" type="button" class="btn btn-success btn-sm side_right" translate>100 Pulse ⇧</a> <a href="/z-axis/move/up/pulse/10" type="button" class="btn btn-success btn-sm side_right" translate>10 Pulse ⇧</a> <a href="/z-axis/move/up/pulse/1" type="button" class="btn btn-success btn-sm side_right" translate>1 Pulse ⇧</a> </div> </div> {% if ZAxisPin %} <br> <legend translate>Move to layer</legend> <form class="edit-page" method="POST"> <fieldset> <div class="control-group"> <label class="control-label" for="appendedtext" translate>Plate</label> <select name="ProfileID" class="form-control" required> {% for profile in profiles %} <option value="{{profile.ProfileID}}">{{profile.Title}}</option> {% endfor %} </select> </div> <br> <div class="control-group"> <label class="control-label" translate>Layer</label> <input id="appendedtext" name="LayerID" class="form-control" placeholder="Layer ID" type="text" required> <br> <br> <div class="controls"> <button value="down" class="btn btn-danger" translate>Move to Layer</button> </div> </div> </fieldset> </form> {% endif %} </div> </div> {% endblock %}
nanodlp/ui
templates/calibration/z-calibration.html
HTML
mit
5,204