code
stringlengths
4
1.01M
language
stringclasses
2 values
require 'optparse' require 'pathname' module EdifactConverter class CommandLineParser class << self attr_writer :options def options @options ||= {} end def parser @parser ||= begin OptionParser.new do|opts| opts.banner = "Usage: #{$COMMAND_NAME} [options] file" opts.on( '-x', '--xml', 'Convert from Edifact to XML' ) do options[:source] = :edifact end opts.on( '-e', '--edi', 'Convert from XML to Edifact' ) do options[:source] = :xml end opts.on( '-1', '--xml11', 'Only convert to XML 1-1') do options[:xml11] = true end opts.on( '-f', '--format', 'Format edifact output with newlines') do options[:format] = true end opts.on( '--html', 'Only convert to XML 1-1') do options[:html] = true end opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do |file| options[:logfile] = file end opts.on( '-o', '--output FILE', 'Write output to FILE' ) do |file| options[:to_file] = file end opts.on( '-v', '--version', "Prints version of #{$COMMAND_NAME}") do puts "#{$COMMAND_NAME} version #{VERSION}" exit end opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end end end end def parse parser.parse! if ARGV.size != 1 puts "Wrong number of arguments, run #{$COMMAND_NAME} -h for a list of possible arguments." exit end options[:input] = Pathname.new ARGV.first unless options[:source] if options[:input].extname =~ /xml/ options[:source] = :xml else options[:source] = :edifact end end options end end end end
Java
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. /* * Copyright 2000-2010 JetBrains s.r.o. * * 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. */ package com.microsoft.alm.plugin.idea.tfvc.ui; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.util.ui.AbstractTableCellEditor; import com.intellij.util.ui.CellEditorComponentWithBrowseButton; import com.microsoft.alm.plugin.context.ServerContext; import com.microsoft.alm.plugin.idea.common.resources.TfPluginBundle; import com.microsoft.alm.plugin.idea.common.utils.VcsHelper; import com.microsoft.alm.plugin.idea.tfvc.ui.servertree.ServerBrowserDialog; import org.apache.commons.lang.StringUtils; import javax.swing.JTable; import javax.swing.JTextField; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ServerPathCellEditor extends AbstractTableCellEditor { private final String title; private final Project project; private final ServerContext serverContext; private CellEditorComponentWithBrowseButton<JTextField> component; public ServerPathCellEditor(final String title, final Project project, final ServerContext serverContext) { this.title = title; this.project = project; this.serverContext = serverContext; } public Object getCellEditorValue() { return component.getChildComponent().getText(); } public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) { final ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { createBrowserDialog(); } }; component = new CellEditorComponentWithBrowseButton<JTextField>(new TextFieldWithBrowseButton(listener), this); component.getChildComponent().setText((String) value); return component; } /** * Creates the browser dialog for file selection */ @VisibleForTesting protected void createBrowserDialog() { final String serverPath = getServerPath(); if (StringUtils.isNotEmpty(serverPath)) { final ServerBrowserDialog dialog = new ServerBrowserDialog(title, project, serverContext, serverPath, true, false); if (dialog.showAndGet()) { component.getChildComponent().setText(dialog.getSelectedPath()); } } else { Messages.showErrorDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_MSG), TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_TITLE)); } } /** * Get a server path to pass into the dialog * * @return */ @VisibleForTesting protected String getServerPath() { String serverPath = (String) getCellEditorValue(); // if there is no entry in the cell to find the root server path with then find it from the server context if (StringUtils.isEmpty(serverPath) && serverContext != null && serverContext.getTeamProjectReference() != null) { serverPath = VcsHelper.TFVC_ROOT.concat(serverContext.getTeamProjectReference().getName()); } return serverPath; } }
Java
package org.peerbox.presenter; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.layout.Pane; public class MainController implements INavigatable { @FXML private Pane mainPane; /* * (non-Javadoc) * * @see org.peerbox.presenter.INavigatable#setContent(javafx.scene.Node) */ @Override public void setContent(Node content) { mainPane.getChildren().clear(); mainPane.getChildren().add(content); mainPane.requestLayout(); } }
Java
// // LightningSendDownView.h // TNTLoveFreshBee // // Created by apple on 16/10/14. // Copyright © 2016年 LiDan. All rights reserved. // #import <UIKit/UIKit.h> @protocol didLightningSendDownViewCommitDelegate <NSObject> @optional - (void)didLightningSendDownViewCommit; @end @interface LightningSendDownView : UIView @property(weak,nonatomic) id<didLightningSendDownViewCommitDelegate>delegate; @end
Java
<?php /* Template Name: Full Page Width Template */ get_header(); while ( have_posts() ) { the_post(); get_template_part( 'content', 'page-full' ); } // end of the loop get_footer();
Java
print("hello!!!!")
Java
var monsterArray = { "name": "岩龙", "other": [ "0", "0", "0", "0", "0", "0", "0", "0", "0", "" ], "weakness": [ { "data": [ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" ] } ] };
Java
/// <reference path="../definitions/mocha.d.ts"/> /// <reference path="../definitions/node.d.ts"/> /// <reference path="../definitions/Q.d.ts"/> import Q = require('q'); import assert = require('assert'); import path = require('path'); import fs = require('fs'); describe('General Suite', function () { this.timeout(20000); before((done) => { // init here done(); }); after(function () { }); it('Find invalid task.json', (done) => { this.timeout(20000); // get a list of all _build/task folders var tasksRootFolder = path.resolve(__dirname, '../Tasks'); var taskFolders: string[] = []; fs.readdirSync(tasksRootFolder).forEach(folderName => { if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) { taskFolders.push(path.join(tasksRootFolder, folderName)); } }) // verify no BOM for (var i = 0; i < taskFolders.length; i++) { var taskFolder = taskFolders[i]; var taskjson = path.join(taskFolder, 'task.json'); var jsonString = fs.readFileSync(taskjson).toString(); if (jsonString.indexOf('\uFEFF') >= 0) { console.warn('The task.json starts with a byte-order mark. This may cause JSON.parse to fail.'); console.warn('The byte-order mark has been removed from the task.json file under the _build directory.'); console.warn('Copy the file over the source file in the task folder and commit it.'); var fixedJsonString = jsonString.replace(/[\uFEFF]/g, ''); fs.writeFileSync(taskjson, fixedJsonString); assert(false, 'Offending file (byte-order mark removed): ' + taskjson); } try { var task = JSON.parse(fs.readFileSync(taskjson).toString()); } catch (err) { assert(false, err.message + '\n\tUnable to parse JSON from: ' + taskjson); } } done(); }) it('Find nested task.json', (done) => { this.timeout(20000); // Path to the _build/Tasks folder. var tasksFolder = path.resolve(__dirname, '../Tasks'); // Recursively find all task.json files. var folders: string[] = [tasksFolder]; while (folders.length > 0) { // Pop the next folder. var folder: string = folders.pop(); // Read the directory. fs.readdirSync(folder).forEach(item => { var itemPath: string = path.join(folder, item); if (fs.statSync(itemPath).isDirectory() && itemPath != path.join(tasksFolder, 'Tests')) { // Push the child directory. folders.push(itemPath); } else if (item.toUpperCase() == "TASK.JSON" && path.resolve(folder, '..').toUpperCase() != tasksFolder.toUpperCase()) { // A task.json file was found nested recursively within the task folder. assert(false, 'A task.json file was found nested recursively within the task folder. This will break the servicing step. Offending file: ' + itemPath); } }); } done(); }) it('Find .js with uppercase', (done) => { this.timeout(20000); // Path to the _build/Tasks folder. var tasksRootFolder = path.resolve(__dirname, '../Tasks'); var taskFolders: string[] = []; fs.readdirSync(tasksRootFolder).forEach(folderName => { if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) { taskFolders.push(path.join(tasksRootFolder, folderName)); } }) for (var i = 0; i < taskFolders.length; i++) { var taskFolder = taskFolders[i]; var taskjson = path.join(taskFolder, 'task.json'); var task = JSON.parse(fs.readFileSync(taskjson).toString()); if (task.execution && task.execution['Node']) { var jsFiles = fs.readdirSync(taskFolder).filter(file => { return file.search(/\.js$/) > 0; }) jsFiles.forEach(jsFile => { if (jsFile.search(/[A-Z]/g) >= 0) { console.error('Has uppercase in .js file name for tasks: ' + path.relative(tasksRootFolder, taskjson)); assert(false, 'Has uppercase is dangerous for xplat tasks.' + taskjson); } }) var targetJs = task.execution['Node'].target; if (targetJs.search(/[A-Z]/g) >= 0) { console.error('Has uppercase in task.json\'s execution.node.target for tasks: ' + path.relative(tasksRootFolder, taskjson)); assert(false, 'Has uppercase is dangerous for xplat tasks.' + taskjson); } } } done(); }) it('Find unsupported demands', (done) => { this.timeout(20000); var supportedDemands: string[] = ['AndroidSDK', 'ant', 'AzurePS', 'Chef', 'DotNetFramework', 'java', 'JDK', 'maven', 'MSBuild', 'MSBuild_x64', 'npm', 'node.js', 'PowerShell', 'SqlPackage', 'VisualStudio', 'VisualStudio_IDE', 'VSTest', 'WindowsKit', 'WindowsSdk', 'cmake', 'cocoapods', 'curl', 'Cmd', 'SCVMMAdminConsole', 'sh', 'KnifeReporting', 'Xamarin.Android', 'Xamarin.iOS', 'xcode']; supportedDemands.forEach(demand => { if (supportedDemands.indexOf(demand.toLocaleLowerCase()) < 0) { supportedDemands.push(demand.toLocaleLowerCase()); } }); // Path to the _build/Tasks folder. var tasksRootFolder = path.resolve(__dirname, '../Tasks'); var taskFolders: string[] = []; fs.readdirSync(tasksRootFolder).forEach(folderName => { if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) { taskFolders.push(path.join(tasksRootFolder, folderName)); } }) var unsupportedDemands: string[] = []; for (var i = 0; i < taskFolders.length; i++) { var taskFolder = taskFolders[i]; var taskjson = path.join(taskFolder, 'task.json'); var task = JSON.parse(fs.readFileSync(taskjson).toString()); if (task.hasOwnProperty('demands')) { task['demands'].forEach(demand => { if (supportedDemands.indexOf(demand.toLocaleLowerCase()) < 0) { console.warn('find unsupported demand: ' + demand + ' in ' + taskjson); console.warn('fix the unit test if the new demand is added on purpose.'); unsupportedDemands.push(demand); } }); } } if (unsupportedDemands.length > 0) { assert(false, 'find unsupported demands, please take necessary operation to fix this. unsupported demands count: ' + unsupportedDemands.length); } done(); }) it('Find unsupported runsOn', (done) => { this.timeout(20000); var supportedRunsOn: string[] = ['Agent', 'DeploymentGroup', 'Server']; supportedRunsOn.forEach(runsOn => { if (supportedRunsOn.indexOf(runsOn.toLocaleLowerCase()) < 0) { supportedRunsOn.push(runsOn.toLocaleLowerCase()); } }); // Path to the _build/Tasks folder. var tasksRootFolder = path.resolve(__dirname, '../Tasks'); var taskFolders: string[] = []; fs.readdirSync(tasksRootFolder).forEach(folderName => { if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) { taskFolders.push(path.join(tasksRootFolder, folderName)); } }) var unsupportedRunsOnCount = 0; for (var i = 0; i < taskFolders.length; i++) { var taskFolder = taskFolders[i]; var taskjson = path.join(taskFolder, 'task.json'); var task = JSON.parse(fs.readFileSync(taskjson).toString()); if (task.hasOwnProperty('runsOn')) { task['runsOn'].forEach(runsOn => { if (supportedRunsOn.indexOf(runsOn.toLocaleLowerCase()) < 0) { ++unsupportedRunsOnCount; console.warn('found unsupported runsOn: ' + runsOn + ' in ' + taskjson); } }); } } if (unsupportedRunsOnCount > 0){ assert(false, 'found unsupported runsOn. please make necessary action to fix this. unsupported runsOn count: ' + unsupportedRunsOnCount); } done(); }) it('Find invalid server Task', (done) => { this.timeout(20000); // Path to the _build/Tasks folder. var tasksRootFolder = path.resolve(__dirname, '../Tasks'); var taskFolders: string[] = []; fs.readdirSync(tasksRootFolder).forEach(folderName => { if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) { taskFolders.push(path.join(tasksRootFolder, folderName)); } }) var supportedServerExecutionHandlers: string[] = [ 'RM:ManualIntervention', 'ServiceBus', 'HttpRequest']; var supportedTaskEvents: string[] = [ 'TaskAssigned', 'TaskStarted', 'TaskCompleted']; var invalidTaskFound: boolean = false; for (var i = 0; i < taskFolders.length; i++) { var taskFolder = taskFolders[i]; var taskjson = path.join(taskFolder, 'task.json'); var task = JSON.parse(fs.readFileSync(taskjson).toString()); if (task.hasOwnProperty('runsOn') && task['runsOn'].some(x => x.toLowerCase() == 'server')) { if (task['runsOn'].length > 1) { assert(false, 'Found invalid value of runsOn in ' + taskjson + '. RunsOn should only be server for server task.'); } if (task.hasOwnProperty('demands') && task['demands'].length > 0) { assert(false, 'Found invalid value for demands in ' + taskjson + '. Demands should be either empty or absent for server task.'); } if (task.hasOwnProperty('minimumAgentVersion')){ assert(false, 'Found minimumAgentVersion in ' + taskjson + '. This should not be present for server task.'); } if (!task.hasOwnProperty('execution')) { assert(false, 'No execution section found for server task in ' + taskjson + '.'); } var handlers = Object.keys(task['execution']); if (handlers.length != 1) { assert(false, 'Number of execution handlers should be 1. Invalid section found in ' + taskjson + '.'); } var handlerName : string = handlers[0]; if (!supportedServerExecutionHandlers.some(x => x.toLowerCase() == handlerName.toLowerCase())){ assert(false, 'Found Invalid task handler name : ' + handlerName + ' in ' + taskjson + '.'); } var execution = task['execution'][handlerName]; if (execution.hasOwnProperty('events')) { var taskEvents = execution['events']; Object.keys(taskEvents).forEach( eventName => { if (!supportedTaskEvents.some(x => x.toLowerCase() == eventName.toLowerCase())) { assert(false, 'Found Invalid task event name ' + eventName + 'in ' + taskjson + '.') } }); } } } done(); }) it('Find invalid message key in task.json', (done) => { this.timeout(20000); // get all task.json and module.json paths under _build/Tasks. var tasksRootFolder = path.resolve(__dirname, '../Tasks'); var jsons: string[] = []; fs.readdirSync(tasksRootFolder).forEach(name => { let itemPath = path.join(tasksRootFolder, name); if (name == 'Common') { fs.readdirSync(itemPath).forEach(name => { let nestedItemPath = path.join(itemPath, name); if (fs.statSync(nestedItemPath).isDirectory()) { let moduleJsonPath = path.join(nestedItemPath, 'module.json'); try { fs.statSync(moduleJsonPath); } catch (err) { return; } jsons.push(moduleJsonPath); } }); } else if (fs.statSync(itemPath).isDirectory()) { jsons.push(path.join(itemPath, 'task.json')); } }); for (var i = 0; i < jsons.length; i++) { var json = jsons[i]; var obj = JSON.parse(fs.readFileSync(json).toString()); if (obj.hasOwnProperty('messages')) { for (var key in obj.messages) { var jsonName = path.relative(tasksRootFolder, json); assert(key.search(/\W+/gi) < 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' contain non-word characters, only allows [a-zA-Z0-9_].')); if (typeof (obj.messages[key]) === 'object') { assert(obj.messages[key].loc, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a loc string.')); assert(obj.messages[key].loc.toString().length >= 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a loc string.')); assert(obj.messages[key].fallback, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a fallback string.')); assert(obj.messages[key].fallback.toString().length > 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a fallback string.')); } else if (typeof (obj.messages[key]) === 'string') { assert(obj.messages[key].toString().length > 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a loc string.')); } } } } done(); }) it('Find missing string in .ts', (done: MochaDone) => { this.timeout(20000); // search the source dir for all _build/Tasks and module folders. let tasksPath = path.resolve(__dirname, '../Tasks'); let taskPaths: string[] = []; fs.readdirSync(tasksPath).forEach((itemName: string) => { let itemPath = path.join(tasksPath, itemName); if (itemName != 'Common' && fs.statSync(itemPath).isDirectory()) { taskPaths.push(itemPath); } }); let commonPath = path.join(tasksPath, 'Common'); var commonItems = []; try { commonItems = fs.readdirSync(commonPath); } catch (err) { if (err.code != 'ENOENT') { assert('Unexpected error reading dir: ' + commonPath); } } commonItems.forEach((itemName: string) => { let itemPath = path.join(commonPath, itemName); if (fs.statSync(itemPath).isDirectory()) { taskPaths.push(itemPath); } }); var testFailed: boolean = false; taskPaths.forEach((taskPath: string) => { var locStringMismatch: boolean = false; // load the task.json or module.json if exists let taskJson; for (let jsonName of ['task.json', 'module.json']) { let jsonPath = path.join(taskPath, jsonName); try { fs.statSync(jsonPath); } catch (err) { return; } taskJson = JSON.parse(fs.readFileSync(jsonPath).toString()); break; } // recursively find all .ts files let tsFiles: string[] = []; let dirs: string[] = [taskPath]; while (dirs.length) { let dir: string = dirs.pop(); fs.readdirSync(dir).forEach((itemName: string) => { let itemPath: string = path.join(dir, itemName); if (fs.statSync(itemPath).isDirectory() && itemName != 'node_modules' && itemPath != path.join(taskPath, 'Tests')) { dirs.push(itemPath); } else if (itemName.search(/\.ts$/) > 0) { tsFiles.push(itemPath); } }); } // search for all loc string keys let locStringKeys: string[] = []; tsFiles.forEach((tsFile: string) => { let content = fs.readFileSync(tsFile).toString().replace(/\r\n/g, '\n').replace(/\r/g, '\n'); let lines: string[] = content.split('\n'); lines.forEach(line => { // remove all spaces. line = line.replace(/ /g, ''); let regx = /tl\.loc\(('(\w+)'|"(\w+)")/i; let res = regx.exec(line); if (res) { let key; if (res[2]) { key = res[2]; } else if (res[3]) { key = res[3]; } locStringKeys.push(key); } }); }); // load the keys from the task.json/module.json let locStringKeysFromJson: string[] = []; if (taskJson && taskJson.hasOwnProperty('messages')) { Object.keys(taskJson.messages).forEach((key: string) => { locStringKeysFromJson.push(key); }); } // find missing keys var missingLocStringKeys: string[] = []; locStringKeys.forEach((locKey: string) => { if (locStringKeysFromJson.indexOf(locKey) === -1 && !locKey.match(/^LIB_/)) { // some tasks refernce lib strings locStringMismatch = true; missingLocStringKeys.push(locKey); } }) if (locStringMismatch) { testFailed = true; console.error('add missing loc string keys to messages section for task.json/module.json: ' + path.relative(tasksPath, taskPath)); console.error(JSON.stringify(missingLocStringKeys)); } }); assert(!testFailed, 'there are missing loc string keys in task.json/module.json.'); done(); }) it('Find missing string in .ps1/.psm1', (done) => { this.timeout(20000); // Push all _build/Tasks folders onto the stack. var folders: string[] = []; var tasksRootFolder = path.resolve(__dirname, '../Tasks'); fs.readdirSync(tasksRootFolder).forEach(folderName => { var folder = path.join(tasksRootFolder, folderName); if (folderName != 'Common' && fs.statSync(folder).isDirectory()) { folders.push(folder); } }) // Push each Common module folder onto the stack. The Common folder does not // get copied under _build so scan the source copy instead. var commonFolder = path.resolve(__dirname, "../Tasks/Common"); var commonItems = []; try { commonItems = fs.readdirSync(commonFolder); } catch (err) { if (err.code != 'ENOENT') { assert('Unexpected error reading dir: ' + commonFolder); } } commonItems.forEach(folderName => { var folder = path.join(commonFolder, folderName); if (fs.statSync(folder).isDirectory()) { folders.push(folder); } }) folders.forEach(taskFolder => { // Load the task.json or module.json if one exists. var jsonFile = path.join(taskFolder, 'task.json'); var obj = { "messages": {} } if (fs.existsSync(jsonFile) || fs.existsSync(jsonFile = path.join(taskFolder, "module.json"))) { obj = JSON.parse(fs.readFileSync(jsonFile).toString()); } else { jsonFile = '' } // Recursively find all PS files. var psFiles: string[] = []; var folderStack: string[] = [taskFolder]; while (folderStack.length > 0) { var folder = folderStack.pop(); if (path.basename(folder).toLowerCase() == "node_modules" || // Skip nested node_modules folder. path.basename(folder).toLowerCase() == "ps_modules") { // Skip nested ps_modules folder. continue; } if (folder == path.join(taskFolder, 'Tests')) { // Skip [...]/Task/Tests and [...]/Common/Tests folders. continue; } fs.readdirSync(folder).forEach(itemName => { var itemPath = path.join(folder, itemName); if (fs.statSync(itemPath).isDirectory()) { folderStack.push(itemPath); } else if (itemPath.toLowerCase().search(/\.ps1$/) > 0 || itemPath.toLowerCase().search(/\.psm1$/) > 0) { psFiles.push(itemPath); } }) } psFiles.forEach(psFile => { var ps = fs.readFileSync(psFile).toString().replace(/\r\n/g, '\n').replace(/\r/g, '\n'); var lines: string[] = ps.split('\n'); lines.forEach(line => { if (line.search(/Get-VstsLocString/i) > 0) { var result = /Get-VstsLocString +-Key +('[^']+'|"[^"]+"|[^ )]+)/i.exec(line); if (!result) { assert(false, 'Bad format string in file ' + psFile + ' on line: ' + line); } var key = result[1].replace(/['"]/g, ""); assert( obj.hasOwnProperty('messages') && obj.messages.hasOwnProperty(key), "Loc resource key not found in task.json/module.json. Resource key: '" + key + "', PS file: '" + psFile + "', JSON file: '" + jsonFile + "'."); } }); }) }) done(); }) });
Java
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Gang } from '../models/gang'; import { Session } from '../models/session'; import { CREW_2_ROUTE } from '../../app/app.routes.model'; import { HttpClient } from '@angular/common/http'; @Injectable() export class CrewService { private crewOne: Observable<Gang>; private crewTwo: Observable<Gang>; constructor(private http: HttpClient) { } public getCrewDataForPath(path: string): Observable<Gang> { if (path === CREW_2_ROUTE) { return this.getCrewTwoData(); } else { return this.getCrewOneData(); } } public getCrewOneData(): Observable<Gang> { if (!this.crewOne) { this.crewOne = this.getCrew('assassins'); } return this.crewOne; } public getCrewTwoData(): Observable<Gang> { if (!this.crewTwo) { this.crewTwo = this.getCrew('assassins2'); } return this.crewTwo; } private getCrew(filename: string): Observable<Gang> { return this.http.get('/assets/data/' + filename + '.json').map((gang: Gang) => { gang.sessions = this.sortSessions(gang.sessions); return gang; }); } private sortSessions(sessions: Session[]): Session[] { return sessions.map((session: Session) => { session.date = Date.parse(<any> session.date); return session; }).sort((a, b) => a.date - b.date); } }
Java
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_SUPPORT_STANDARD #define BOOST_SPIRIT_INCLUDE_SUPPORT_STANDARD #if defined(_MSC_VER) #pragma once #endif #include <lslboost/spirit/home/support/char_encoding/standard.hpp> #endif
Java
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy from typing import Any, Awaitable, Optional, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer from .. import models from ._configuration import SqlVirtualMachineManagementClientConfiguration from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class SqlVirtualMachineManagementClient: """The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener. :ivar availability_group_listeners: AvailabilityGroupListenersOperations operations :vartype availability_group_listeners: azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations :ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations :vartype sql_virtual_machine_groups: azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations :ivar sql_virtual_machines: SqlVirtualMachinesOperations operations :vartype sql_virtual_machines: azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: Subscription ID that identifies an Azure subscription. :type subscription_id: str :param base_url: Service URL. Default value is 'https://management.azure.com'. :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize) self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request( self, request: HttpRequest, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = await client._send_request(request) <AsyncHttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.AsyncHttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "SqlVirtualMachineManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
Java
// // kmeans.h // VoterMLA // // Created by MD Shihabul Kabir on 12/5/16. // Copyright © 2016 MD Shihabul Kabir. All rights reserved. // #ifndef kmeans_h #define kmeans_h #include "county.h" #include <vector> //K-Means Clustering Namespace namespace KmeansCluster { //Data Structure to help K-Means Clustering class KMeans{ private: //setup three clusters for the clustering and two for last centroids and current centroids std::vector<CountyStruct::County>cluster1,cluster2,cluster3,last,current,all; public: //method find the closest cluster to add void addToClosest(CountyStruct::County&acounty); //method to initialize rand centroids and clusters void initialize(std::vector<CountyStruct::County> counties); //method to get the mean of a cluster std::vector<float> mean(std::vector<CountyStruct::County>&cluster); //method to get centroid closest to mean of cluster CountyStruct::County getCentroid(std::vector<CountyStruct::County>&cluster,std::vector<float> mean); //method to get the centroid of a cluster CountyStruct::County centroid(std::vector<CountyStruct::County>&counties); //method to setup centroids bool setupCentroids(); //method to make the clusters void cluster(); //method to get the distance from a point to rest of cluster float avgDistance(std::vector<CountyStruct::County>&cluster,int index); //method to find distance from cluster from a point float distanceFromCluster(CountyStruct::County&c,std::vector<CountyStruct::County>&cluster); //method to return silhoute value float silh(std::vector<CountyStruct::County>&a,std::vector<CountyStruct::County>&b,int index); //method to print the silhoute for each cluster void printSil(); }; } #endif /* kmeans_h */
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>T837185195841212416</title> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600"> <link rel="stylesheet" href="/style.css"> <link rel="stylesheet" href="/custom.css"> <link rel="alternate" type="application/rss+xml" title="Curt Clifton" href="http://curt.micro.blog/feed.xml" /> <link rel="alternate" type="application/json" title="Curt Clifton" href="http://curt.micro.blog/feed.json" /> <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" /> <link rel="me" href="https://micro.blog/curt" /> <link rel="me" href="https://twitter.com/curtclifton" /> <link rel="authorization_endpoint" href="https://indieauth.com/auth" /> <link rel="token_endpoint" href="https://tokens.indieauth.com/token" /> <link rel="micropub" href="https://micro.blog/micropub" /> <link rel="webmention" href="https://micro.blog/webmention" /> </head> <body> <div class="container"> <header class="masthead"> <h1 class="masthead-title--small"> <a href="/">Curt Clifton</a> </h1> </header> <div class="content post h-entry"> <div class="post-date"> <time class="dt-published" datetime="2017-03-02 06:17:00 +0000">02 Mar 2017</time> </div> <div class="e-content"> <p>Whoever, owing allegiance to [U.S.],… adheres to their enemies… is guilty of treason and shall suffer death… #fb <a href="https://t.co/Uid0RAMMs1">https://t.co/Uid0RAMMs1</a></p> </div> </div> </div> </body> </html>
Java
#include "NL_ImguiD3D11Renderer.h" #include <d3d11.h> #include <d3dcompiler.h> #include <imgui.h> namespace NLE { namespace GRAPHICS { struct VERTEX_CONSTANT_BUFFER { float mvp[4][4]; }; ImguiD3D11Renderer::ImguiD3D11Renderer() : _vertexBuffer(nullptr), _indexBuffer(nullptr), _vertexShaderBlob(nullptr), _vertexShader(nullptr), _inputLayout(nullptr), _vertexConstantBuffer(nullptr), _pixelShaderBlob(nullptr), _pixelShader(nullptr), _fontSampler(nullptr), _fontTextureView(nullptr), _rasterizerState(nullptr), _blendState(nullptr), _depthStencilState(nullptr), _vertexBufferSize(5000), _indexBufferSize(10000) { } ImguiD3D11Renderer::~ImguiD3D11Renderer() { } bool ImguiD3D11Renderer::initialize(ID3D11Device* device, ID3D11DeviceContext* devCon) { if (!createDeviceObjects(device, devCon)) return false; if (!createFontAndTextures(device, devCon)) return false; return true; } bool ImguiD3D11Renderer::createDeviceObjects(ID3D11Device* device, ID3D11DeviceContext* devCon) { // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) // If you would like to use this DX11 sample code but remove this dependency you can: // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [prefered solution] // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. // Create the vertex shader { static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ float2 pos : POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ PS_INPUT output;\ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ output.col = input.col;\ output.uv = input.uv;\ return output;\ }"; D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &_vertexShaderBlob, nullptr); if (!_vertexShaderBlob) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! return false; if (device->CreateVertexShader((DWORD*)_vertexShaderBlob->GetBufferPointer(), _vertexShaderBlob->GetBufferSize(), nullptr, &_vertexShader) != S_OK) return false; // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (device->CreateInputLayout(local_layout, 3, _vertexShaderBlob->GetBufferPointer(), _vertexShaderBlob->GetBufferSize(), &_inputLayout) != S_OK) return false; // Create the constant buffer { D3D11_BUFFER_DESC desc; desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER); desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; device->CreateBuffer(&desc, nullptr, &_vertexConstantBuffer); } } // Create the pixel shader { static const char* pixelShader = "struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ sampler sampler0;\ Texture2D texture0;\ \ float4 main(PS_INPUT input) : SV_Target\ {\ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ return out_col; \ }"; D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &_pixelShaderBlob, nullptr); if (!_pixelShaderBlob) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! return false; if (device->CreatePixelShader((DWORD*)_pixelShaderBlob->GetBufferPointer(), _pixelShaderBlob->GetBufferSize(), nullptr, &_pixelShader) != S_OK) return false; } // Create the blending setup { D3D11_BLEND_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.AlphaToCoverageEnable = false; desc.RenderTarget[0].BlendEnable = true; desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; device->CreateBlendState(&desc, &_blendState); } // Create the rasterizer state { D3D11_RASTERIZER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.FillMode = D3D11_FILL_SOLID; desc.CullMode = D3D11_CULL_NONE; desc.ScissorEnable = true; desc.DepthClipEnable = true; device->CreateRasterizerState(&desc, &_rasterizerState); } // Create depth-stencil State { D3D11_DEPTH_STENCIL_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.DepthEnable = false; desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; desc.DepthFunc = D3D11_COMPARISON_ALWAYS; desc.StencilEnable = false; desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; desc.BackFace = desc.FrontFace; device->CreateDepthStencilState(&desc, &_depthStencilState); } return true; } bool ImguiD3D11Renderer::createFontAndTextures(ID3D11Device* device, ID3D11DeviceContext* devCon) { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system { D3D11_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; ID3D11Texture2D *pTexture = NULL; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; device->CreateTexture2D(&desc, &subResource, &pTexture); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; device->CreateShaderResourceView(pTexture, &srvDesc, &_fontTextureView); pTexture->Release(); } // Store our identifier io.Fonts->TexID = (void *)_fontTextureView; // Create texture sampler { D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; device->CreateSamplerState(&desc, &_fontSampler); } return true; } void ImguiD3D11Renderer::render(ID3D11Device* device, ID3D11DeviceContext* devCon, ImDrawData* drawData) { // Create and grow vertex/index buffers if needed if (!_vertexBuffer || _vertexBufferSize < drawData->TotalVtxCount) { if (_vertexBuffer) { _vertexBuffer->Release(); _vertexBuffer = nullptr; } _vertexBufferSize = drawData->TotalVtxCount + 5000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = _vertexBufferSize * sizeof(ImDrawVert); desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; if (device->CreateBuffer(&desc, nullptr, &_vertexBuffer) < 0) return; } if (!_indexBuffer || _indexBufferSize < drawData->TotalIdxCount) { if (_indexBuffer) { _indexBuffer->Release(); _indexBuffer = nullptr; } _indexBufferSize = drawData->TotalIdxCount + 10000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = _indexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D11_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; if (device->CreateBuffer(&desc, nullptr, &_indexBuffer) < 0) return; } // Copy and convert all vertices into a single contiguous buffer D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource; if (devCon->Map(_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK) return; if (devCon->Map(_indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK) return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData; for (int n = 0; n < drawData->CmdListsCount; n++) { const ImDrawList* cmd_list = drawData->CmdLists[n]; memcpy(vtx_dst, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert)); memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.size(); idx_dst += cmd_list->IdxBuffer.size(); } devCon->Unmap(_vertexBuffer, 0); devCon->Unmap(_indexBuffer, 0); // Setup orthographic projection matrix into our constant buffer { D3D11_MAPPED_SUBRESOURCE mapped_resource; if (devCon->Map(_vertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) return; VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData; float L = 0.0f; float R = ImGui::GetIO().DisplaySize.x; float B = ImGui::GetIO().DisplaySize.y; float T = 0.0f; float mvp[4][4] = { { 2.0f / (R - L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / (T - B), 0.0f, 0.0f }, { 0.0f, 0.0f, 0.5f, 0.0f }, { (R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f }, }; memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); devCon->Unmap(_vertexConstantBuffer, 0); } // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) struct BACKUP_DX11_STATE { UINT ScissorRectsCount, ViewportsCount; D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; ID3D11RasterizerState* RS; ID3D11BlendState* BlendState; FLOAT BlendFactor[4]; UINT SampleMask; UINT StencilRef; ID3D11DepthStencilState* DepthStencilState; ID3D11ShaderResourceView* PSShaderResource; ID3D11SamplerState* PSSampler; ID3D11PixelShader* PS; ID3D11VertexShader* VS; UINT PSInstancesCount, VSInstancesCount; ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology; ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; DXGI_FORMAT IndexBufferFormat; ID3D11InputLayout* InputLayout; }; BACKUP_DX11_STATE old; old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; devCon->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects); devCon->RSGetViewports(&old.ViewportsCount, old.Viewports); devCon->RSGetState(&old.RS); devCon->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask); devCon->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); devCon->PSGetShaderResources(0, 1, &old.PSShaderResource); devCon->PSGetSamplers(0, 1, &old.PSSampler); old.PSInstancesCount = old.VSInstancesCount = 256; devCon->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount); devCon->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount); devCon->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); devCon->IAGetPrimitiveTopology(&old.PrimitiveTopology); devCon->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); devCon->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); devCon->IAGetInputLayout(&old.InputLayout); // Setup viewport D3D11_VIEWPORT vp; memset(&vp, 0, sizeof(D3D11_VIEWPORT)); vp.Width = ImGui::GetIO().DisplaySize.x; vp.Height = ImGui::GetIO().DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0.0f; devCon->RSSetViewports(1, &vp); // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; devCon->IASetInputLayout(_inputLayout); devCon->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset); devCon->IASetIndexBuffer(_indexBuffer, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); devCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); devCon->VSSetShader(_vertexShader, NULL, 0); devCon->VSSetConstantBuffers(0, 1, &_vertexConstantBuffer); devCon->PSSetShader(_pixelShader, NULL, 0); devCon->PSSetSamplers(0, 1, &_fontSampler); // Setup render state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; devCon->OMSetBlendState(_blendState, blend_factor, 0xffffffff); devCon->OMSetDepthStencilState(_depthStencilState, 0); devCon->RSSetState(_rasterizerState); // Render command lists int vtx_offset = 0; int idx_offset = 0; for (int n = 0; n < drawData->CmdListsCount; n++) { const ImDrawList* cmd_list = drawData->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w }; devCon->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId); devCon->RSSetScissorRects(1, &r); devCon->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset); } idx_offset += pcmd->ElemCount; } vtx_offset += cmd_list->VtxBuffer.size(); } // Restore modified DX state devCon->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); devCon->RSSetViewports(old.ViewportsCount, old.Viewports); devCon->RSSetState(old.RS); if (old.RS) old.RS->Release(); devCon->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release(); devCon->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release(); devCon->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release(); devCon->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release(); devCon->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release(); for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release(); devCon->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release(); devCon->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release(); devCon->IASetPrimitiveTopology(old.PrimitiveTopology); devCon->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); devCon->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release(); devCon->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); } } }
Java
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @subpackage Annotation * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: FileAttachment.php 24594 2012-01-05 21:27:01Z matthew $ */ /** Internally used classes */ // require_once 'Zend/Pdf/Element.php'; // require_once 'Zend/Pdf/Element/Array.php'; // require_once 'Zend/Pdf/Element/Dictionary.php'; // require_once 'Zend/Pdf/Element/Name.php'; // require_once 'Zend/Pdf/Element/Numeric.php'; // require_once 'Zend/Pdf/Element/String.php'; /** Zend_Pdf_Annotation */ // require_once 'Zend/Pdf/Annotation.php'; /** * A file attachment annotation contains a reference to a file, * which typically is embedded in the PDF file. * * @package Zend_Pdf * @subpackage Annotation * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Annotation_FileAttachment extends Zend_Pdf_Annotation { /** * Annotation object constructor * * @throws Zend_Pdf_Exception */ public function __construct(Zend_Pdf_Element $annotationDictionary) { if ($annotationDictionary->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Annotation dictionary resource has to be a dictionary.'); } if ($annotationDictionary->Subtype === null || $annotationDictionary->Subtype->getType() != Zend_Pdf_Element::TYPE_NAME || $annotationDictionary->Subtype->value != 'FileAttachment') { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Subtype => FileAttachment entry is requires'); } parent::__construct($annotationDictionary); } /** * Create link annotation object * * @param float $x1 * @param float $y1 * @param float $x2 * @param float $y2 * @param string $fileSpecification * @return Zend_Pdf_Annotation_FileAttachment */ public static function create($x1, $y1, $x2, $y2, $fileSpecification) { $annotationDictionary = new Zend_Pdf_Element_Dictionary(); $annotationDictionary->Type = new Zend_Pdf_Element_Name('Annot'); $annotationDictionary->Subtype = new Zend_Pdf_Element_Name('FileAttachment'); $rectangle = new Zend_Pdf_Element_Array(); $rectangle->items[] = new Zend_Pdf_Element_Numeric($x1); $rectangle->items[] = new Zend_Pdf_Element_Numeric($y1); $rectangle->items[] = new Zend_Pdf_Element_Numeric($x2); $rectangle->items[] = new Zend_Pdf_Element_Numeric($y2); $annotationDictionary->Rect = $rectangle; $fsDictionary = new Zend_Pdf_Element_Dictionary(); $fsDictionary->Type = new Zend_Pdf_Element_Name('Filespec'); $fsDictionary->F = new Zend_Pdf_Element_String($fileSpecification); $annotationDictionary->FS = $fsDictionary; return new Zend_Pdf_Annotation_FileAttachment($annotationDictionary); } }
Java
/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */ dbm.registerClass("dbm.thirdparty.facebook.constants.EventTypes", null, function(objectFunctions, staticFunctions, ClassReference) { //console.log("dbm.thirdparty.facebook.constants.EventTypes"); //REFERENCE: http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/ var EventTypes = dbm.importClass("dbm.thirdparty.facebook.constants.EventTypes"); staticFunctions.AUTH_LOGIN = "auth.login"; staticFunctions.AUTH_RESPONSE_CHANGE = "auth.authResponseChange"; staticFunctions.AUTH_STATUS_CHANGE = "auth.statusChange"; staticFunctions.AUTH_LOGOUT = "auth.logout"; staticFunctions.AUTH_PROMPT = "auth.prompt"; staticFunctions.XFBML_RENDER = "xfbml.render"; staticFunctions.EDGE_CREATE = "edge.create"; staticFunctions.EDGE_REMOVE = "edge.remove"; staticFunctions.COMMENT_CREATE = "comment.create"; staticFunctions.COMMENT_REMOVE = "comment.remove"; staticFunctions.MESSAGE_SEND = "message.send"; });
Java
module TweetStream class Terminated < ::StandardError; end class Error < ::StandardError; end class ConnectionError < TweetStream::Error; end # A ReconnectError is raised when the maximum number of retries has # failed to re-establish a connection. class ReconnectError < StandardError attr_accessor :timeout, :retries def initialize(timeout, retries) self.timeout = timeout self.retries = retries super("Failed to reconnect after #{retries} tries.") end end end
Java
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. #pragma warning disable CA1801 // Remove unused parameter #pragma warning disable IDE0060 // Remove unused parameter using System; using System.Linq; using System.Text; namespace OtherDll { /// <summary> /// Aids with testing dataflow analysis _not_ doing interprocedural DFA. /// </summary> /// <remarks> /// Since Roslyn doesn't support cross-binary DFA, and this class is /// defined in a different binary, using this class from test source code /// is a way to test handling of non-interprocedural results in dataflow /// analysis implementations. /// </remarks> public class OtherDllClass<T> where T : class { public OtherDllClass(T? constructedInput) { this.ConstructedInput = constructedInput; } public T? ConstructedInput { get; set; } public T? Default { get => default; set { } } public string RandomString { get { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); return Encoding.ASCII.GetString(bytes); } set { } } public T? ReturnsConstructedInput() { return this.ConstructedInput; } public T? ReturnsDefault() { return default; } public T? ReturnsInput(T? input) { return input; } public T? ReturnsDefault(T? input) { return default; } public string ReturnsRandom(string input) { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); return Encoding.ASCII.GetString(bytes); } public void SetsOutputToConstructedInput(out T? output) { output = this.ConstructedInput; } public void SetsOutputToDefault(out T? output) { output = default; } public void SetsOutputToInput(T? input, out T? output) { output = input; } public void SetsOutputToDefault(T? input, out T? output) { output = default; } public void SetsOutputToRandom(string input, out string output) { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); output = Encoding.ASCII.GetString(bytes); } public void SetsReferenceToConstructedInput(ref T? output) { output = this.ConstructedInput; } public void SetsReferenceToDefault(ref T? output) { output = default; } public void SetsReferenceToInput(T? input, ref T? output) { output = input; } public void SetsReferenceToDefault(T? input, ref T? output) { output = default; } public void SetsReferenceToRandom(string input, ref string output) { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); output = Encoding.ASCII.GetString(bytes); } } }
Java
<?php namespace FashionGuide\Oauth2\Exceptions; class AppException extends \Exception { }
Java
#!/bin/bash # Set up your StartSSL certificates/keys for nginx-proxy # This script expects your certificate and key files in this folder following # the nginx-proxy naming convention. # For example: foo.example.com.crt foo.example.com.key # are the .crt and .key file for the domain foo.example.com # Make sure script is ran from correct directory if [[ ! -e script.sh ]]; then if [[ -d certs ]]; then cd certs || { echo >&2 "Bundle directory exists but I can't cd there."; exit 1; } else echo >&2 "Please cd into the bundle before running this script."; exit 1; fi fi CERT_CLASS="class1" CERT_CA_FILE="sub.${CERT_CLASS}.server.ca.pem" DHPARAM_FILE="dhparam.pem" # Get the StartSSL Root CA and Class 1 Intermediate Server CA certificates if [ ! -f ${CERT_CA_FILE} ]; then wget https://www.startssl.com/certs/${CERT_CA_FILE} fi # Generate dhparam.pem if needed. if [ ! -f ${DHPARAM_FILE} ]; then echo "${DHPARAM_FILE} not found." echo "Generating ${DHPARAM_FILE} with openssl" openssl dhparam -out ${DHPARAM_FILE} 2048 fi # Create a private key and certificate and transfer them to your server. for file in *.key; do DOMAIN=${file%.*} if [ ! -f ./unified/${DOMAIN}.crt ]; then echo "DHPARAM: Copying ${DOMAIN}.${DHPARAM_FILE}" cp ./${DHPARAM_FILE} ./unified/${DOMAIN}.${DHPARAM_FILE} echo "CRT: Creating unified ${DOMAIN}.crt" cat ./${DOMAIN}.crt ${CERT_CA_FILE} > ./unified/${DOMAIN}.crt # Keys should already be decrypted echo "KEY: Copying ${DOMAIN}.key" cp ./${DOMAIN}.key ./unified/${DOMAIN}.key echo "" fi # Protect your key files from prying eyes chmod 600 ./${DOMAIN}.key chmod 600 ./unified/${DOMAIN}.key done
Java
'use strict'; // This is the webpack config used for JS unit tests const Encore = require('@symfony/webpack-encore'); const encoreConfigure = require('./webpack.base.config'); const webpackCustomize = require('./webpack.customize'); // Initialize Encore before requiring the .config file Encore.configureRuntimeEnvironment('dev-server'); encoreConfigure(Encore); const webpack = require('webpack'); const merge = require('webpack-merge'); const ManifestPlugin = require('@symfony/webpack-encore/lib/webpack/webpack-manifest-plugin'); const baseWebpackConfig = Encore.getWebpackConfig(); webpackCustomize(baseWebpackConfig); const webpackConfig = merge(baseWebpackConfig, { // use inline sourcemap for karma-sourcemap-loader devtool: '#inline-source-map', resolveLoader: { alias: { // necessary to to make lang="scss" work in test when using vue-loader's ?inject option // see discussion at https://github.com/vuejs/vue-loader/issues/724 'scss-loader': 'sass-loader' } }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"testing"' } }) ] }); // no need for app entry during tests delete webpackConfig.entry; // Set writeToFileEmit option of the ManifestPlugin to false for (const plugin of webpackConfig.plugins) { if ((plugin instanceof ManifestPlugin) && plugin.opts) { plugin.opts.writeToFileEmit = false; } } module.exports = webpackConfig;
Java
/*********************** * fallback mode panel * ***********************/ PanelWidget, PanelApplet, PanelToplevel { padding: 0; background-color: @osd_bg; background-image: none; color: #222222; } PanelApplet { border-width: 0; } PanelSeparator { border-width: 0; background-color: @osd_bg; background-image: none; color: @osd_fg; } .gnome-panel-menu-bar, PanelApplet > GtkMenuBar.menubar, PanelApplet > GtkMenuBar.menubar.menuitem, PanelMenuBar.menubar, PanelMenuBar.menubar.menuitem { -Panelpanel-icon-visible: true; border-width: 0; background-color: @osd_bg; background-image: none; } PanelAppletFrame { border-width: 0; background-color: @osd_bg; background-image: none; } PanelApplet .button { -GtkButton-inner-border: 2; border-width: 0; border-radius: 5px; border-color: transparent; background-color: @osd_bg; background-image: none; color: #222222; } PanelApplet .button:active, PanelApplet .button:active:prelight { border-width: 0 ; border-radius: 5px; background-color: shade(@button_normal_color, 0.925); background-image: none; color: shade(@theme_selected_fg_color, 0.95); } PanelApplet .button:prelight { background-color: shade(@button_normal_color, 1.06); background-image: none; color: #222222; } WnckPager, WnckTasklist { background-color: @osd_bg; } /************ * nautilus * ************/ .nautilus-canvas-item { border-radius: 2px; } .nautilus-desktop.nautilus-canvas-item { color: white; text-shadow: 1px 1px black; } .nautilus-desktop.nautilus-canvas-item:active { } .nautilus-desktop.nautilus-canvas-item:selected { } .nautilus-desktop.nautilus-canvas-item:active, .nautilus-desktop.nautilus-canvas-item:prelight, .nautilus-desktop.nautilus-canvas-item:selected { } NautilusWindow .toolbar { border-width: 0; border-style: none; } NautilusWindow .primary-toolbar .button.raised.linked.text-button, NautilusWindow .primary-toolbar .raised.linked .button.text-button, NautilusWindow .toolbar .button.raised.linked.text-button, NautilusWindow .toolbar .raised.linked .button.text-button, NautilusWindow .toolbar .linked .button.text-button, NautilusWindow .header-bar .button.raised.linked.text-button, NautilusWindow .header-bar .raised.linked .button.text-button, NautilusWindow .header-bar .linked .button.text-button, NautilusWindow .header-bar .button.text-button, NautilusWindow .toolbar .button.text-button { } NautilusWindow .sidebar .frame { border-style: none; } NautilusWindow > GtkGrid > .pane-separator, NautilusWindow > GtkGrid > .pane-separator:hover { border-width: 0; border-style: none; } NautilusNotebook.notebook tab { padding: 0; } NautilusNotebook .frame, NautilusWindow .sidebar .frame { border-width: 0; } NautilusQueryEditor .primary-toolbar.toolbar { border-width: 0; } NautilusQueryEditor .toolbar { border-width: 0; } NautilusQueryEditor .toolbar:nth-child(2) { } NautilusQueryEditor .toolbar:last-child, NautilusQueryEditor .primary-toolbar.toolbar:only-child { border-width: 0; } /* NautilusWindow .sidebar, NautilusWindow .sidebar.view, NautilusWindow .sidebar .view, NautilusWindow .sidebar.view:prelight, NautilusWindow .sidebar .view:prelight { background-color: @bg_color; } */ /****************** * gnome terminal * ******************/ VteTerminal { background-color: @base_color; color: @text_color; } TerminalWindow, TerminalWindow GtkNotebook, TerminalWindow GtkNotebook.notebook { background-color: @base_color; color: @text_color; border-width: 0; } TerminalWindow .scrollbars-junction, TerminalWindow .scrollbar.trough, TerminalWindow .scrollbar.trough.vertical { background-color: @base_color; } TerminalWindow .scrollbar.button, TerminalWindow .scrollbar.button:active, TerminalWindow .scrollbar.button:active:hover { } TerminalWindow .scrollbar.slider { background-color: shade(@bg_color,1.0); } TerminalWindow .scrollbar.slider:hover, TerminalWindow .scrollbar.slider.vertical:hover { background-color: shade(@bg_color, 1.1); } TerminalWindow .scrollbar.slider:active, TerminalWindow .scrollbar.slider.vertical:active { background-color: shade(@bg_color, 1.1); } /********* * gedit * *********/ GeditWindow .pane-separator, GeditWindow .pane-separator:hover { border-width: 0; border-style: none; background-color: @theme_bg_color; } GeditPanel.title GtkLabel { padding: 4px 0; } GeditPanel.vertical .title { padding: 4px 0 4px 3px; border-style: none; } GeditPanel .toolbar { border-style: none; background-color: transparent; } GeditDocumentsPanel .view { background-color: @theme_base_color; } GeditPanel.vertical .notebook { padding: 0; border-width: 0; } GeditPanel.horizontal .notebook { padding: 0; border-width: 0; } GeditWindow .notebook { border-width: 0; } GeditPanel .notebook tab, GeditWindow .notebook tab { border-width: 0; } GeditStatusMenuButton { color: @theme_fg_color; text-shadow: none; } GeditStatusMenuButton.button, GeditStatusMenuButton.button:hover, GeditStatusMenuButton.button:active, GeditStatusMenuButton.button:active:hover { text-shadow: none; font-weight: normal; border-image: none; border-style: none; border-width: 0; border-radius: 5px; color: @theme_fg_color; } GeditStatusMenuButton.button:hover, GeditStatusMenuButton.button:active, GeditStatusMenuButton.button:active:hover { color: @theme_selected_fg_color; } GeditStatusMenuButton.button:active { } GeditViewFrame .gedit-search-slider { padding: 4px; border-radius: 0 0 5px 5px; border-width: 0 1px 1px 1px; border-style: solid; border-color: @entry_border_color; background-color: @theme_base_color; } GeditViewFrame .gedit-search-slider .not-found { background-color: @error_bg_color; background-image: none; color: @error_fg_color; } GeditViewFrame .gedit-search-slider .entry { padding: 5px 5px 6px 5px; } GeditViewFrame .gedit-search-slider .not-found:selected { background-color: shade(@theme_selected_bg_color, 1.2); color: @theme_selected_fg_color; } GeditFileBrowserWidget .primary-toolbar.toolbar { padding: 2px; border: none; background-color: @theme_bg_color; background-image: none; } GeditFileBrowserWidget .primary-toolbar.toolbar GtkComboBox *{ color: @theme_fg_color; } GeditFileBrowserWidget .primary-toolbar.toolbar GtkComboBox *:hover, GeditFileBrowserWidget .primary-toolbar.toolbar GtkComboBox .menu * { color: @theme_selected_fg_color; } .gedit-search-entry-occurrences-tag { color: @theme_text_color; margin: 2px; padding: 2px; } /*************** * font-viewer * ***************/ SushiFontWidget { padding: 6px 12px; } /************* * gucharmap * *************/ GucharmapChartable { background-color: @theme_base_color; } GucharmapChartable:active, GucharmapChartable:focus, GucharmapChartable:selected { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } /* gnome-documents */ .documents-dropdown, .documents-dropdown .view { background-color: @theme_bg_color; } .documents-dropdown.frame { padding: 6px; border-width: 0 1px 1px 1px; border-style: solid; border-radius: 0 0 5px 5px; border-color: @entry_border_color; } .documents-dropdown .view.radio, .documents-dropdown .view.radio:focus { background-image: url("assets/blank.png");; background-color: transparent; } .documents-dropdown .view.radio:active, .documents-dropdown .view.radio:active:focus, .documents-dropdown .view.radio:active:hover, .documents-dropdown .view.radio:hover { background-color: transparent; background-image: url("assets/radio-checked.png"); } .documents-entry-tag { background-color: transparent; color: @theme_text_color; border-radius: 5px; border-width: 0; margin: 2px; padding: 4px; } .documents-entry-tag:hover { } .documents-entry-tag.button, .documents-entry-tag.button:focus, .documents-entry-tag.button:hover, .documents-entry-tag.button:hover:focus, .documents-entry-tag.button:active, .documents-entry-tag.button:active:focus { color: @theme_selected_fg_color; } /* epiphany */ EphyToolbar .entry:first-child, EphyToolbar .entry:focus:first-child { border-bottom-right-radius: 0; border-top-right-radius: 0; } EphyToolbar .entry:last-child, EphyToolbar .entry:focus:last-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } EphyToolbar .location-entry .button:last-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } EphyToolbar .location-entry .button:first-child { border-bottom-right-radius: 0; border-top-right-radius: 0; } EphyOverview GtkScrolledWindow { border-style: none; background-color: @theme_base_color; } EphyWindow.background EphyEmbed.vertical GtkScrolledWindow.frame { border-style: none; } EphyWindow.background EphyEmbed.vertical EphyOverview .documents-scrolledwin { border-style: none; } EphyWindow.background EphyNotebook.notebook EphyEmbed.vertical GtkScrolledWindow { border-style: none; } /* Gnome Contacts */ ContactsContactSheet .button, ContactsContactSheet .button:focus { color: @theme_text_color; text-shadow: none; } ContactsContactSheet .button:active, ContactsContactSheet .button:hover, ContactsContactSheet .button:active:focus, ContactsContactSheet .button:hover:focus { color: @theme_selected_fg_color; text-shadow: none; } /* evince */ EvWindow.background > GtkBox.vertical > GtkPaned.horizontal > GtkBox.vertical > GtkOverlay > GtkScrolledWindow.frame { border-width: 0; border-radius: 0; } EvWindow.background EvSidebar.vertical .frame { border-width: 0; border-radius: 0; } EvWindow.background EvSidebar.vertical .notebook .frame { border-width: 0; } EvSidebar .button, EvSidebar .button:focus { color: @theme_text_color; text-shadow: none; } EvSidebar .button:active, EvSidebar .button:hover, EvSidebar .button:active:focus, EvSidebar .button:hover:focus { color: @theme_selected_fg_color; text-shadow: none; } /* file-roller */ RBSource .toolbar .button, FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel { text-shadow: none; icon-shadow: none; color: shade(@theme_text_color, 1.1); } CcWindow CcUserPanel CcEditableEntry .button, CcWindow CcUserPanel UmEditableCombo .button, CcWindow CcUserPanel UmEditableButton .button, CcWindow CcUserPanel CcEditableEntry .button:focus, CcWindow CcUserPanel UmEditableCombo .button:focus, CcWindow CcUserPanel UmEditableButton .button:focus, RBSource .toolbar .button, FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button { text-shadow: none; icon-shadow: none; color: shade(@theme_text_color, 1.1); } CcWindow CcUserPanel CcEditableEntry .button:hover, CcWindow CcUserPanel UmEditableCombo .button:hover, CcWindow CcUserPanel UmEditableButton .button:hover, CcWindow CcUserPanel CcEditableEntry .button:active, CcWindow CcUserPanel UmEditableCombo .button:active, CcWindow CcUserPanel UmEditableButton .button:active, RBSource .toolbar .button:hover, RBSource .toolbar .button:active, FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel:hover, FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel:active { color: @theme_selected_fg_color; } CcWindow CcUserPanel CcEditableEntry .button:insensitive, CcWindow CcUserPanel UmEditableCombo .button:insensitive, CcWindow CcUserPanel UmEditableButton .button:insensitive, RBSource .toolbar .button:insensitive, FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel:insensitive { color: shade(@entry_border_color, 0.8); } /********************* * NEMO File manager * *********************/ /* for breadcrumbs path bar */ .nemo-pathbar-button, NemoPathbarButton { border-radius: 5px; border-width: 1px; border-style: solid; border-color: transparent; text-shadow: none; icon-shadow: none; box-shadow: none; background-color: @button_normal_color; background-image: none; color: @theme_selected_fg_color; } NemoPathbarButton:active, NemoPathbarButton:active:hover { box-shadow: none; background-color: @theme_selected_bg_color; background-image: none; color: shade(@theme_selected_fg_color, 0.95); } NemoPathbarButton:hover { box-shadow: none; text-shadow: none; icon-shadow: none; background-color: shade(@button_normal_color, 1.06); background-image: none; color: @theme_selected_fg_color; } NemoPathbarButton:insensitive { box-shadow: none; background-color: shade(@button_normal_color, 1.17); background-image: none; color: shade(@entry_border_color, 1.05); } NemoPathbarButton *:insensitive { color: shade(@entry_border_color, 1.05); } /* For Places Sidebar diskfull indicators */ NemoPlacesTreeView { } NemoPlacesTreeView:selected { -NemoPlacesTreeView-disk-full-bg-color: @entry_border_color; -NemoPlacesTreeView-disk-full-fg-color: @button_normal_color; } NemoPlacesTreeView:hover { } NemoPlacesTreeView:selected:hover { } NemoWindow * { } NemoWindow .view { background-color: @theme_base_color; } NemoWindow .rubberband, NemoWindow .view.rubberband { background-color: alpha (@theme_selected_bg_color, 0.3); } /* inactive pane */ .nemo-inactive-pane .view { background-color: shade(@theme_bg_color, 1.03); }
Java
@echo off REM Script to install the updates net user Administrator p@ssw0rd /active:yes SET install_dir=%~dp0 REM Getting rid of the \ at the end SET install_dir=%install_dir:~0,-1% cd %install_dir% dir /b %install_dir%\*.cab > updatelist.txt for /f "delims=" %%i in (updatelist.txt) do ( echo Processing %%i call applyupdate -stage %%i ) echo. echo Commit updates applyupdate -commit
Java
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_petitioneer_session'
Java
// Release 1: User Stories // As a user, I want to be able to create a new grocery list. After that, I need to be able to add an item with a quantity to the list, remove an item, and update the quantities if they change. I need a way to print out the list in a format that is very readable. // Release 2: Pseudocode // input: string of items separated by spaces // output: object // create a new object as new variable // convert string to array (split) // take each item in array and add to object as a property with a default quantity/value of 1 // // Release 3: Initial Solution // function to create list // var foodList = ("salmon iceCream macAndCheese") // var groceryList = {}; // var createList = function(foodList) { // var foodArray = foodList.split(" "); // for (var i = 0; i < foodArray.length; i++){ // groceryList[(foodArray[i])] = 1; // } // console.log(groceryList); // } // createList(foodList) // // function to add item to list // var addItem = function(newItem) { // groceryList[newItem] = 1; // console.log(groceryList); // } // addItem("peas") // // function to remove item from list // var removeItem = function(itemToLose) { // delete groceryList[itemToLose]; // console.log(groceryList); // } // removeItem("peas") // // function to update quantity // var updateList = function(updateItem, newQuantity) { // groceryList[updateItem] = newQuantity; // console.log(groceryList); // } // updateList("macAndCheese", 5) // // function to display list // var displayList = function(groceryList) { // for (food in groceryList) { // console.log(food + ": " + groceryList[food]); // } // } // displayList(groceryList) // Release 4: Refactor // function to create list var groceryList = {}; var displayList = function(groceryList) { console.log("Your Grocery List:") for (food in groceryList) { console.log(food + ": " + groceryList[food]); } console.log("----------") } var createList = function(foodList) { var foodArray = foodList.split(" "); for (var i = 0; i < foodArray.length; i++){ groceryList[(foodArray[i])] = 1; } displayList(groceryList); } var addItem = function(newItem) { groceryList[newItem] = 1; displayList(groceryList); } var removeItem = function(itemToLose) { delete groceryList[itemToLose]; displayList(groceryList); } var updateList = function(updateItem, newQuantity) { groceryList[updateItem] = newQuantity; displayList(groceryList); } var foodList = ("funfettiMix bananas chocolateCoveredAlmonds") createList(foodList) addItem("peaches") updateList("peaches", 20) removeItem("bananas") // Release 5: Reflect // What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.) // I solidified accessing different properties in an object. I was able to add strings from an array into an empty object and set their default value. To change those values I knew I needed to access the property using bracket notation, and change the value it was = to. // What was the most difficult part of this challenge? // I forgot I needed to convert the string to an array, but once I did that with the .split(" ") method, all of the strings were easily accessible to add to the new object. // Did an array or object make more sense to use and why? // This was weirdly WAY easier with JavaScript than it was initially with Ruby (probably because we were on our second week of Ruby at this point!). It was so easy to add each string from an array into the object as a property and set it's default. Accessing these properties to update or delete was made easier by using bracket notation. Instead of complicated hash methods and having to convert strings to arrays to hashes, all I had to do was split the string and add each string to the object with a default value.
Java
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <script src='matrices.js'></script> <style> .indent { padding-left: 2em; } </style> </head> <body> <h3>Color space:</h3> Spec: <select id='e_color_space'> <option value='rec601' selected>Rec601</option> <option value='rec709'>Rec709</option> <option value='rec2020'>Rec2020/Rec2100</option> </select> <div class='indent'> Kr: <input id='e_kr'> <br> Kg: <input id='e_kg'> <br> Kb: <input id='e_kb'> </div> <br>Array order: <select id='e_array_major'> <option value='row' selected>Row-major (common)</option> <option value='column'>Column-major (for OpenGL)</option> </select> <br>Precision: <input id='e_precision' value='5'> <pre id='e_color_space_output'>-</pre> <hr> <h3>Quantization</h3> Bits: <input id='e_bits'> <br>Range: <select id='e_range_type'> <option value='narrow' selected>Narrow</option> <option value='full'>Full</option> </select> <div class='indent'> Yquant: [ <input id='e_yq_min'> , <input id='e_yq_max'> ] <br> Cb, Cr: [ <input id='e_uvq_min'> , <input id='e_uvq_max'> ] (<span id='e_uvq_info'></span>) </div> <pre id='e_quant_output'>-</pre> <hr> <h3>Conversion:</h3> <pre id='e_matrix_output'>-</pre> YCbCr: <input id='e_y' value=100> <input id='e_cb' value=100> <input id='e_cr' value=100> <br> RGB: <input id='e_r'> <input id='e_g'> <input id='e_b'> <script> 'use strict'; function round(x) { const precision = parseInt(e_precision.value); const pointsPow = Math.pow(10, precision); return Math.round(x * pointsPow) / pointsPow; } function matToOutputVar(var_name, x) { const precision = parseInt(e_precision.value); if (e_array_major.value === 'column') { x = matTrans(x); } return var_name + ' =\n' + matString(x, precision); }; // - function getRangeInfo() { const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const cbcr_neg_1 = parseFloat(e_uvq_min.value); const cbcr_pos_1 = parseFloat(e_uvq_max.value); const cbcr0 = (cbcr_neg_1 + cbcr_pos_1) / 2; return { y0: parseFloat(e_yq_min.value) / normalizer, y1: parseFloat(e_yq_max.value) / normalizer, cbcr0: cbcr0 / normalizer, cbcr1: cbcr_pos_1 / normalizer, }; } // - // Make these easy to use in console: let yuvFromRgb, rgbFromYuv; let ycbcrFromYuv; let ycbcrFromRgb, rgbFromYcbcr; function refreshQuant() { const r = getRangeInfo(); ycbcrFromYuv = [ [r.y1-r.y0, 0, 0, r.y0], [0, r.cbcr1-r.cbcr0, 0, r.cbcr0], [0, 0, r.cbcr1-r.cbcr0, r.cbcr0] ]; const yuvFromRgb_4x4 = matResized(yuvFromRgb, 4, 4); ycbcrFromRgb = matMul(ycbcrFromYuv, yuvFromRgb_4x4); rgbFromYcbcr = matInv(ycbcrFromRgb); //const back = matInv(rgbFromYcbcr); //console.log('ycbcrFromRgb-1-1', fnMatToString(back)); const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const cbcrDiff = r.cbcr1 - r.cbcr0; function roundNorm(x) { return round(x*normalizer); } e_quant_output.textContent = [ `Yq: [${roundNorm(r.y0)}, ${roundNorm(r.y1)}]`, `Cb, Cr: ${roundNorm(r.cbcr0)} +/- ${roundNorm(cbcrDiff)}` + ` => [${roundNorm(r.cbcr0-cbcrDiff)}, ${roundNorm(r.cbcr0+cbcrDiff)}]`, '', `Y: [${round(r.y0)}, ${round(r.y1)}]`, `U, V: ${round(r.cbcr0)} +/- ${round(cbcrDiff)}` + ` => [${round(r.cbcr0-cbcrDiff)}, ${round(r.cbcr0+cbcrDiff)}]`, '', matToOutputVar('ycbcrFromYuv', ycbcrFromYuv) ].join('\n'); e_matrix_output.textContent = [ matToOutputVar('ycbcrFromRgb', ycbcrFromRgb), '', matToOutputVar('rgbFromYcbcr', rgbFromYcbcr), ].join('\n'); lastConvertFunc(); } [ e_yq_min, e_yq_max, e_uvq_min, e_uvq_max, ].forEach(e => { e.addEventListener('change', refreshQuant); }); // - function refreshUvqInfo() { const r = getRangeInfo(); const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const cbcr0 = r.cbcr0 * normalizer; const cbcrDiff = (r.cbcr1 - r.cbcr0) * normalizer; e_uvq_info.textContent = `${round(cbcr0)} +/- ${round(cbcrDiff)}`; } e_uvq_min.addEventListener('change', refreshUvqInfo); e_uvq_max.addEventListener('change', refreshUvqInfo); // - function refreshRangeInfo() { const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; if (e_range_type.value == 'full') { // rec2020 defines these: // Y: D = Round((2^n-1) * E) | E = [0.0, 1.0] // AKA Dy = 255*Ey + 0 // Cb,Cr: D = Round((2^n-1) * E + 2^(n-1)) | E = [-0.5, 0.5] // AKA Dcb,Dcr = 255*Ey + 128, or 128 +/- 127.5. (512 +/- 511.5) // Next, it then specifies peak/achrome/peak as 1/512/1023, // but by its formulas, +0.5 => round(1023*0.5+512) = round(512+511.5) // = round(1023.5) = *1024*. Uhh, oops! // It seems to me what they wanted instead was 512 +/- 511, or: // Cb,Cr: D = Round((2^n-2) * E + 2^(n-1)) e_yq_min.value = 0; e_yq_max.value = normalizer; e_uvq_min.value = 1; e_uvq_max.value = normalizer; } else { let y0 = 16; let y1 = 235; // 16+219 let cbcr0 = 128; let cbcr1 = 240; // 128+224/2 // 10- and 12-bit narrow are just scaled 8-bit narrow. y0 <<= bits - 8; y1 <<= bits - 8; cbcr0 <<= bits - 8; cbcr1 <<= bits - 8; e_yq_min.value = y0; e_yq_max.value = y1; e_uvq_min.value = cbcr0 - (cbcr1 - cbcr0); e_uvq_max.value = cbcr1; } refreshUvqInfo(); refreshQuant(); } e_bits.addEventListener('change', refreshRangeInfo); e_range_type.addEventListener('change', refreshRangeInfo); // - function refreshColorSpace() { const kr = parseFloat(e_kr.value); const kg = parseFloat(e_kg.value); const kb = parseFloat(e_kb.value); const uRange = 1-kb; const vRange = 1-kr; yuvFromRgb = [ [kr, kg, kb], [-kr/uRange, -kg/uRange, (1-kb)/uRange], [(1-kr)/vRange, -kg/vRange, -kb/vRange] ]; rgbFromYuv = matInv(yuvFromRgb); e_color_space_output.textContent = [ matToOutputVar('yuvFromRgb', yuvFromRgb), '', matToOutputVar('rgbFromYuv', rgbFromYuv), ].join('\n'); refreshRangeInfo(); } e_kr.addEventListener('change', refreshColorSpace); e_kg.addEventListener('change', refreshColorSpace); e_kb.addEventListener('change', refreshColorSpace); // - function presetColorSpace() { const colorSpace = e_color_space.value; if (colorSpace === 'rec601') { e_kr.value = 0.299; e_kg.value = 0.587; e_kb.value = 0.114; e_bits.value = 8; } else if (colorSpace === 'rec709') { e_kr.value = 0.2126; e_kg.value = 0.7152; e_kb.value = 0.0722; e_bits.value = 8; } else if (colorSpace === 'rec2020') { e_kr.value = 0.2627; e_kg.value = '0.6780'; // String to preserve the trailing zero. e_kb.value = 0.0593; e_bits.value = 10; } refreshColorSpace(); } e_color_space.addEventListener('change', presetColorSpace); // - [e_array_major, e_precision].forEach(e => { e.addEventListener('change', () => { refreshColorSpace(); refreshQuant(); }); }); // - function convert(srcElems, destFromSrc, destElems) { const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const src = srcElems.map(e => parseFloat(e.value) / normalizer); src.push(1); const dest = matMulVec(destFromSrc, src); for (let i = 0; i < 3; i++) { let val = dest[i]; //val = Math.max(0, Math.min(val, 1)); // clamp to [0,1] destElems[i].value = round(val*normalizer); } } // - const RGB_ELEMS = [e_r, e_g, e_b]; const YCBCR_ELEMS = [e_y, e_cb, e_cr]; function fromRgb() { convert(RGB_ELEMS, ycbcrFromRgb, YCBCR_ELEMS); lastConvertFunc = fromRgb; } function fromYcbcr() { convert(YCBCR_ELEMS, rgbFromYcbcr, RGB_ELEMS); lastConvertFunc = fromYcbcr; } let lastConvertFunc = fromYcbcr; RGB_ELEMS.forEach(e => e.addEventListener('change', fromRgb)); YCBCR_ELEMS.forEach(e => e.addEventListener('change', fromYcbcr)); // - presetColorSpace(); refreshQuant(); </script> </body> </html>
Java
Dagaz.Controller.persistense = "setup"; Dagaz.Model.WIDTH = 8; Dagaz.Model.HEIGHT = 8; ZRF = { JUMP: 0, IF: 1, FORK: 2, FUNCTION: 3, IN_ZONE: 4, FLAG: 5, SET_FLAG: 6, POS_FLAG: 7, SET_POS_FLAG: 8, ATTR: 9, SET_ATTR: 10, PROMOTE: 11, MODE: 12, ON_BOARD_DIR: 13, ON_BOARD_POS: 14, PARAM: 15, LITERAL: 16, VERIFY: 20 }; Dagaz.Model.BuildDesign = function(design) { design.checkVersion("z2j", "2"); design.checkVersion("animate-captures", "false"); design.checkVersion("smart-moves", "false"); design.checkVersion("show-blink", "false"); design.checkVersion("show-hints", "false"); design.addDirection("w"); // 0 design.addDirection("e"); // 1 design.addDirection("s"); // 2 design.addDirection("ne"); // 3 design.addDirection("n"); // 4 design.addDirection("se"); // 5 design.addDirection("sw"); // 6 design.addDirection("nw"); // 7 design.addPlayer("White", [1, 0, 4, 6, 2, 7, 3, 5]); design.addPlayer("Black", [0, 1, 4, 5, 2, 3, 7, 6]); design.addPosition("a8", [0, 1, 8, 0, 0, 9, 0, 0]); design.addPosition("b8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("c8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("d8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("e8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("f8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("g8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("h8", [-1, 0, 8, 0, 0, 0, 7, 0]); design.addPosition("a7", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h7", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a6", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h6", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a5", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h5", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a4", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h4", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a3", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h3", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a2", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h2", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a1", [0, 1, 0, -7, -8, 0, 0, 0]); design.addPosition("b1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("c1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("d1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("e1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("f1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("g1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("h1", [-1, 0, 0, 0, -8, 0, 0, -9]); design.addPosition("X1", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X2", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X3", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X4", [0, 0, 0, 0, 0, 0, 0, 0]); design.addZone("last-rank", 1, [0, 1, 2, 3, 4, 5, 6, 7]); design.addZone("last-rank", 2, [56, 57, 58, 59, 60, 61, 62, 63]); design.addZone("third-rank", 1, [40, 41, 42, 43, 44, 45, 46, 47]); design.addZone("third-rank", 2, [16, 17, 18, 19, 20, 21, 22, 23]); design.addZone("black", 1, [56, 58, 60, 62, 49, 51, 53, 55, 40, 42, 44, 46, 33, 35, 37, 39, 24, 26, 28, 30, 17, 19, 21, 23, 8, 10, 12, 14, 1, 3, 5, 7]); design.addZone("black", 2, [56, 58, 60, 62, 49, 51, 53, 55, 40, 42, 44, 46, 33, 35, 37, 39, 24, 26, 28, 30, 17, 19, 21, 23, 8, 10, 12, 14, 1, 3, 5, 7]); design.addZone("home", 1, [56, 57, 58, 59, 60, 61, 62, 63, 48, 49, 50, 51, 52, 53, 54, 55]); design.addZone("home", 2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); design.addCommand(0, ZRF.FUNCTION, 24); // from design.addCommand(0, ZRF.PARAM, 0); // $1 design.addCommand(0, ZRF.FUNCTION, 22); // navigate design.addCommand(0, ZRF.FUNCTION, 1); // empty? design.addCommand(0, ZRF.FUNCTION, 20); // verify design.addCommand(0, ZRF.IN_ZONE, 0); // last-rank design.addCommand(0, ZRF.FUNCTION, 0); // not design.addCommand(0, ZRF.IF, 4); design.addCommand(0, ZRF.PROMOTE, 4); // Queen design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.JUMP, 2); design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.FUNCTION, 28); // end design.addCommand(1, ZRF.FUNCTION, 24); // from design.addCommand(1, ZRF.PARAM, 0); // $1 design.addCommand(1, ZRF.FUNCTION, 22); // navigate design.addCommand(1, ZRF.FUNCTION, 1); // empty? design.addCommand(1, ZRF.FUNCTION, 20); // verify design.addCommand(1, ZRF.IN_ZONE, 1); // third-rank design.addCommand(1, ZRF.FUNCTION, 20); // verify design.addCommand(1, ZRF.PARAM, 1); // $2 design.addCommand(1, ZRF.FUNCTION, 22); // navigate design.addCommand(1, ZRF.FUNCTION, 1); // empty? design.addCommand(1, ZRF.FUNCTION, 20); // verify design.addCommand(1, ZRF.FUNCTION, 25); // to design.addCommand(1, ZRF.FUNCTION, 28); // end design.addCommand(2, ZRF.FUNCTION, 24); // from design.addCommand(2, ZRF.PARAM, 0); // $1 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.FUNCTION, 2); // enemy? design.addCommand(2, ZRF.FUNCTION, 20); // verify design.addCommand(2, ZRF.IN_ZONE, 0); // last-rank design.addCommand(2, ZRF.FUNCTION, 0); // not design.addCommand(2, ZRF.IF, 4); design.addCommand(2, ZRF.PROMOTE, 4); // Queen design.addCommand(2, ZRF.FUNCTION, 25); // to design.addCommand(2, ZRF.JUMP, 2); design.addCommand(2, ZRF.FUNCTION, 25); // to design.addCommand(2, ZRF.FUNCTION, 28); // end design.addCommand(3, ZRF.FUNCTION, 24); // from design.addCommand(3, ZRF.PARAM, 0); // $1 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 2); // enemy? design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.FUNCTION, 5); // last-to? design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.LITERAL, 0); // Pawn design.addCommand(3, ZRF.FUNCTION, 10); // piece? design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.FUNCTION, 26); // capture design.addCommand(3, ZRF.PARAM, 1); // $2 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 6); // mark design.addCommand(3, ZRF.PARAM, 2); // $3 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 4); // last-from? design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.FUNCTION, 7); // back design.addCommand(3, ZRF.FUNCTION, 25); // to design.addCommand(3, ZRF.FUNCTION, 28); // end design.addCommand(4, ZRF.FUNCTION, 24); // from design.addCommand(4, ZRF.PARAM, 0); // $1 design.addCommand(4, ZRF.FUNCTION, 22); // navigate design.addCommand(4, ZRF.FUNCTION, 1); // empty? design.addCommand(4, ZRF.FUNCTION, 0); // not design.addCommand(4, ZRF.IF, 7); design.addCommand(4, ZRF.FORK, 3); design.addCommand(4, ZRF.FUNCTION, 25); // to design.addCommand(4, ZRF.FUNCTION, 28); // end design.addCommand(4, ZRF.PARAM, 1); // $2 design.addCommand(4, ZRF.FUNCTION, 22); // navigate design.addCommand(4, ZRF.JUMP, -8); design.addCommand(4, ZRF.FUNCTION, 3); // friend? design.addCommand(4, ZRF.FUNCTION, 0); // not design.addCommand(4, ZRF.FUNCTION, 20); // verify design.addCommand(4, ZRF.FUNCTION, 25); // to design.addCommand(4, ZRF.FUNCTION, 28); // end design.addCommand(5, ZRF.FUNCTION, 24); // from design.addCommand(5, ZRF.PARAM, 0); // $1 design.addCommand(5, ZRF.FUNCTION, 22); // navigate design.addCommand(5, ZRF.PARAM, 1); // $2 design.addCommand(5, ZRF.FUNCTION, 22); // navigate design.addCommand(5, ZRF.FUNCTION, 3); // friend? design.addCommand(5, ZRF.FUNCTION, 0); // not design.addCommand(5, ZRF.FUNCTION, 20); // verify design.addCommand(5, ZRF.FUNCTION, 25); // to design.addCommand(5, ZRF.FUNCTION, 28); // end design.addCommand(6, ZRF.FUNCTION, 24); // from design.addCommand(6, ZRF.PARAM, 0); // $1 design.addCommand(6, ZRF.FUNCTION, 22); // navigate design.addCommand(6, ZRF.FUNCTION, 3); // friend? design.addCommand(6, ZRF.FUNCTION, 0); // not design.addCommand(6, ZRF.FUNCTION, 20); // verify design.addCommand(6, ZRF.FUNCTION, 25); // to design.addCommand(6, ZRF.FUNCTION, 28); // end design.addCommand(7, ZRF.IN_ZONE, 3); // home design.addCommand(7, ZRF.FUNCTION, 20); // verify design.addCommand(7, ZRF.FUNCTION, 1); // empty? design.addCommand(7, ZRF.FUNCTION, 20); // verify design.addCommand(7, ZRF.FUNCTION, 25); // to design.addCommand(7, ZRF.FUNCTION, 28); // end design.addPriority(0); // drop-type design.addPriority(1); // normal-type design.addPiece("Pawn", 0, 800); design.addMove(0, 0, [4], 1); design.addMove(0, 1, [4, 4], 1); design.addMove(0, 2, [7], 1); design.addMove(0, 2, [3], 1); design.addMove(0, 3, [1, 4, 4], 1); design.addMove(0, 3, [0, 4, 4], 1); design.addPiece("Rook", 1, 5000); design.addMove(1, 4, [4, 4], 1); design.addMove(1, 4, [2, 2], 1); design.addMove(1, 4, [0, 0], 1); design.addMove(1, 4, [1, 1], 1); design.addDrop(1, 7, [], 0); design.addPiece("Knight", 2, 3350); design.addMove(2, 5, [4, 7], 1); design.addMove(2, 5, [4, 3], 1); design.addMove(2, 5, [2, 6], 1); design.addMove(2, 5, [2, 5], 1); design.addMove(2, 5, [0, 7], 1); design.addMove(2, 5, [0, 6], 1); design.addMove(2, 5, [1, 3], 1); design.addMove(2, 5, [1, 5], 1); design.addDrop(2, 7, [], 0); design.addPiece("Bishop", 3, 3450); design.addMove(3, 4, [7, 7], 1); design.addMove(3, 4, [6, 6], 1); design.addMove(3, 4, [3, 3], 1); design.addMove(3, 4, [5, 5], 1); design.addDrop(3, 7, [], 0); design.addPiece("Queen", 4, 9750); design.addMove(4, 4, [4, 4], 1); design.addMove(4, 4, [2, 2], 1); design.addMove(4, 4, [0, 0], 1); design.addMove(4, 4, [1, 1], 1); design.addMove(4, 4, [7, 7], 1); design.addMove(4, 4, [6, 6], 1); design.addMove(4, 4, [3, 3], 1); design.addMove(4, 4, [5, 5], 1); design.addDrop(4, 7, [], 0); design.addPiece("King", 5, 600000); design.addMove(5, 6, [4], 1); design.addMove(5, 6, [2], 1); design.addMove(5, 6, [0], 1); design.addMove(5, 6, [1], 1); design.addMove(5, 6, [7], 1); design.addMove(5, 6, [6], 1); design.addMove(5, 6, [3], 1); design.addMove(5, 6, [5], 1); design.addDrop(5, 7, [], 0); design.setup("White", "Pawn", 48); design.setup("White", "Pawn", 49); design.setup("White", "Pawn", 50); design.setup("White", "Pawn", 51); design.setup("White", "Pawn", 52); design.setup("White", "Pawn", 53); design.setup("White", "Pawn", 54); design.setup("White", "Pawn", 55); design.reserve("White", "Pawn", 0); design.reserve("White", "Knight", 2); design.reserve("White", "Bishop", 2); design.reserve("White", "Rook", 2); design.reserve("White", "Queen", 1); design.reserve("White", "King", 1); design.setup("Black", "Pawn", 8); design.setup("Black", "Pawn", 9); design.setup("Black", "Pawn", 10); design.setup("Black", "Pawn", 11); design.setup("Black", "Pawn", 12); design.setup("Black", "Pawn", 13); design.setup("Black", "Pawn", 14); design.setup("Black", "Pawn", 15); design.reserve("Black", "Pawn", 0); design.reserve("Black", "Knight", 2); design.reserve("Black", "Bishop", 2); design.reserve("Black", "Rook", 2); design.reserve("Black", "Queen", 1); design.reserve("Black", "King", 1); } Dagaz.View.configure = function(view) { view.defBoard("Board"); view.defPiece("WhitePawn", "White Pawn"); view.defPiece("BlackPawn", "Black Pawn"); view.defPiece("WhiteRook", "White Rook"); view.defPiece("BlackRook", "Black Rook"); view.defPiece("WhiteKnight", "White Knight"); view.defPiece("BlackKnight", "Black Knight"); view.defPiece("WhiteBishop", "White Bishop"); view.defPiece("BlackBishop", "Black Bishop"); view.defPiece("WhiteQueen", "White Queen"); view.defPiece("BlackQueen", "Black Queen"); view.defPiece("WhiteKing", "White King"); view.defPiece("BlackKing", "Black King"); view.defPiece("Ko", "Ko"); view.defPosition("a8", 2, 2, 68, 68); view.defPosition("b8", 70, 2, 68, 68); view.defPosition("c8", 138, 2, 68, 68); view.defPosition("d8", 206, 2, 68, 68); view.defPosition("e8", 274, 2, 68, 68); view.defPosition("f8", 342, 2, 68, 68); view.defPosition("g8", 410, 2, 68, 68); view.defPosition("h8", 478, 2, 68, 68); view.defPosition("a7", 2, 70, 68, 68); view.defPosition("b7", 70, 70, 68, 68); view.defPosition("c7", 138, 70, 68, 68); view.defPosition("d7", 206, 70, 68, 68); view.defPosition("e7", 274, 70, 68, 68); view.defPosition("f7", 342, 70, 68, 68); view.defPosition("g7", 410, 70, 68, 68); view.defPosition("h7", 478, 70, 68, 68); view.defPosition("a6", 2, 138, 68, 68); view.defPosition("b6", 70, 138, 68, 68); view.defPosition("c6", 138, 138, 68, 68); view.defPosition("d6", 206, 138, 68, 68); view.defPosition("e6", 274, 138, 68, 68); view.defPosition("f6", 342, 138, 68, 68); view.defPosition("g6", 410, 138, 68, 68); view.defPosition("h6", 478, 138, 68, 68); view.defPosition("a5", 2, 206, 68, 68); view.defPosition("b5", 70, 206, 68, 68); view.defPosition("c5", 138, 206, 68, 68); view.defPosition("d5", 206, 206, 68, 68); view.defPosition("e5", 274, 206, 68, 68); view.defPosition("f5", 342, 206, 68, 68); view.defPosition("g5", 410, 206, 68, 68); view.defPosition("h5", 478, 206, 68, 68); view.defPosition("a4", 2, 274, 68, 68); view.defPosition("b4", 70, 274, 68, 68); view.defPosition("c4", 138, 274, 68, 68); view.defPosition("d4", 206, 274, 68, 68); view.defPosition("e4", 274, 274, 68, 68); view.defPosition("f4", 342, 274, 68, 68); view.defPosition("g4", 410, 274, 68, 68); view.defPosition("h4", 478, 274, 68, 68); view.defPosition("a3", 2, 342, 68, 68); view.defPosition("b3", 70, 342, 68, 68); view.defPosition("c3", 138, 342, 68, 68); view.defPosition("d3", 206, 342, 68, 68); view.defPosition("e3", 274, 342, 68, 68); view.defPosition("f3", 342, 342, 68, 68); view.defPosition("g3", 410, 342, 68, 68); view.defPosition("h3", 478, 342, 68, 68); view.defPosition("a2", 2, 410, 68, 68); view.defPosition("b2", 70, 410, 68, 68); view.defPosition("c2", 138, 410, 68, 68); view.defPosition("d2", 206, 410, 68, 68); view.defPosition("e2", 274, 410, 68, 68); view.defPosition("f2", 342, 410, 68, 68); view.defPosition("g2", 410, 410, 68, 68); view.defPosition("h2", 478, 410, 68, 68); view.defPosition("a1", 2, 478, 68, 68); view.defPosition("b1", 70, 478, 68, 68); view.defPosition("c1", 138, 478, 68, 68); view.defPosition("d1", 206, 478, 68, 68); view.defPosition("e1", 274, 478, 68, 68); view.defPosition("f1", 342, 478, 68, 68); view.defPosition("g1", 410, 478, 68, 68); view.defPosition("h1", 478, 478, 68, 68); view.defPopup("Promote", 127, 100); view.defPopupPosition("X1", 10, 7, 68, 68); view.defPopupPosition("X2", 80, 7, 68, 68); view.defPopupPosition("X3", 150, 7, 68, 68); view.defPopupPosition("X4", 220, 7, 68, 68); }
Java
#ifndef __GTHREE_VECTOR_KEYFRAME_TRACK_H__ #define __GTHREE_VECTOR_KEYFRAME_TRACK_H__ #if !defined (__GTHREE_H_INSIDE__) && !defined (GTHREE_COMPILATION) #error "Only <gthree/gthree.h> can be included directly." #endif #include <gthree/gthreekeyframetrack.h> G_BEGIN_DECLS #define GTHREE_TYPE_VECTOR_KEYFRAME_TRACK (gthree_vector_keyframe_track_get_type ()) #define GTHREE_VECTOR_KEYFRAME_TRACK(inst) (G_TYPE_CHECK_INSTANCE_CAST ((inst), \ GTHREE_TYPE_VECTOR_KEYFRAME_TRACK, \ GthreeVectorKeyframeTrack)) #define GTHREE_IS_VECTOR_KEYFRAME_TRACK(inst) (G_TYPE_CHECK_INSTANCE_TYPE ((inst), \ GTHREE_TYPE_VECTOR_KEYFRAME_TRACK)) #define GTHREE_VECTOR_KEYFRAME_TRACK_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_CLASS ((inst), GTHREE_TYPE_VECTOR_KEYFRAME_TRACK, GthreeVectorKeyframeTrackClass)) typedef struct { GthreeKeyframeTrack parent; } GthreeVectorKeyframeTrack; typedef struct { GthreeKeyframeTrackClass parent_class; } GthreeVectorKeyframeTrackClass; G_DEFINE_AUTOPTR_CLEANUP_FUNC (GthreeVectorKeyframeTrack, g_object_unref) GTHREE_API GType gthree_vector_keyframe_track_get_type (void) G_GNUC_CONST; GTHREE_API GthreeKeyframeTrack *gthree_vector_keyframe_track_new (const char *name, GthreeAttributeArray *times, GthreeAttributeArray *values); G_END_DECLS #endif /* __GTHREE_VECTOR_KEYFRAME_TRACK_H__ */
Java
<?php namespace PHPAuth; class Auth { protected $dbh; public $config; public $lang; public function __construct(\PDO $dbh, $config, $language = "en_GB") { $this->dbh = $dbh; $this->config = $config; if (version_compare(phpversion(), '5.5.0', '<')) { die('PHP 5.5.0 required for Auth engine!'); } // Load language require "languages/{$language}.php"; $this->lang = $lang; date_default_timezone_set($this->config->site_timezone); } public function login($email, $password, $remember = 0, $captcha = NULL) { $return['error'] = true; $block_status = $this->isBlocked(); if ($block_status == "verify") { $return['message'] = $this->lang["user_verify_failed"]; return $return; } if ($block_status == "block") { $return['message'] = $this->lang["user_blocked"]; return $return; } $validateEmail = $this->validateEmail($email); $validatePassword = $this->validatePassword($password); if ($validateEmail['error'] == 1) { $this->addAttempt(); $return['message'] = $this->lang["email_password_invalid"]; return $return; } elseif ($validatePassword['error'] == 1) { $this->addAttempt(); $return['message'] = $this->lang["email_password_invalid"]; return $return; } elseif ($remember != 0 && $remember != 1) { $this->addAttempt(); $return['message'] = $this->lang["remember_me_invalid"]; return $return; } $uid = $this->getUID(strtolower($email)); if (!$uid) { $this->addAttempt(); $return['message'] = $this->lang["email_password_incorrect"]; return $return; } $user = $this->getBaseUser($uid); if (!password_verify($password, $user['password'])) { $this->addAttempt(); $return['message'] = $this->lang["email_password_incorrect"]; return $return; } if ($user['isactive'] != 1) { $this->addAttempt(); $return['message'] = $this->lang["account_inactive"]; return $return; } $sessiondata = $this->addSession($user['uid'], $remember); if ($sessiondata == false) { $return['message'] = $this->lang["system_error"] . " #01"; return $return; } $return['error'] = false; $return['message'] = $this->lang["logged_in"]; $return['hash'] = $sessiondata['hash']; $return['expire'] = $sessiondata['expiretime']; $return['cookie_name'] = $this->config->cookie_name; return $return; } public function isEmailTaken($email) { $query = $this->dbh->prepare("SELECT count(*) FROM {$this->config->table_users} WHERE email = ?"); $query->execute(array($email)); if ($query->fetchColumn() == 0) { return false; } return true; } protected function addUser($email, $password, $params = array(), &$sendmail) { $return['error'] = true; $query = $this->dbh->prepare("INSERT INTO {$this->config->table_users} (isactive) VALUES (0)"); if (!$query->execute()) { $return['message'] = $this->lang["system_error"] . " #03"; return $return; } $uid = $this->dbh->lastInsertId("{$this->config->table_users}_id_seq"); $email = htmlentities(strtolower($email)); $isactive = 1; $password = $this->getHash($password); if (is_array($params)&& count($params) > 0) { $customParamsQueryArray = Array(); foreach($params as $paramKey => $paramValue) { $customParamsQueryArray[] = array('value' => $paramKey . ' = ?'); } $setParams = ', ' . implode(', ', array_map(function ($entry) { return $entry['value']; }, $customParamsQueryArray)); } else { $setParams = ''; } $query = $this->dbh->prepare("UPDATE {$this->config->table_users} SET email = ?, password = ?, isactive = ? {$setParams} WHERE id = ?"); $bindParams = array_values(array_merge(array($email, $password, $isactive), $params, array($uid))); if (!$query->execute($bindParams)) { $query = $this->dbh->prepare("DELETE FROM {$this->config->table_users} WHERE id = ?"); $query->execute(array($uid)); $return['message'] = $this->lang["system_error"] . " #04"; return $return; } $return['error'] = false; return $return; } public function getHash($password) { return password_hash($password, PASSWORD_BCRYPT, ['cost' => $this->config->bcrypt_cost]); } public function getUID($email) { $query = $this->dbh->prepare("SELECT id FROM {$this->config->table_users} WHERE email = ?"); $query->execute(array($email)); if(!$row = $query->fetch(\PDO::FETCH_ASSOC)) { return false; } return $row['id']; } public function isLogged() { return (isset($_COOKIE[$this->config->cookie_name]) && $this->checkSession($_COOKIE[$this->config->cookie_name])); } public function getSessionHash() { return $_COOKIE[$this->config->cookie_name]; } protected function getBaseUser($uid) { $query = $this->dbh->prepare("SELECT email, password, isactive FROM {$this->config->table_users} WHERE id = ?"); $query->execute(array($uid)); $data = $query->fetch(\PDO::FETCH_ASSOC); if (!$data) { return false; } $data['uid'] = $uid; return $data; } protected function addSession($uid, $remember) { $ip = $this->getIp(); $user = $this->getBaseUser($uid); if (!$user) { return false; } $data['hash'] = sha1($this->config->site_key . microtime()); $agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; $this->deleteExistingSessions($uid); if ($remember == true) { $data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_remember)); $data['expiretime'] = strtotime($data['expire']); } else { $data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_forget)); $data['expiretime'] = 0; } $data['cookie_crc'] = sha1($data['hash'] . $this->config->site_key); $query = $this->dbh->prepare("INSERT INTO {$this->config->table_sessions} (uid, hash, expiredate, ip, agent, cookie_crc) VALUES (?, ?, ?, ?, ?, ?)"); if (!$query->execute(array($uid, $data['hash'], $data['expire'], $ip, $agent, $data['cookie_crc']))) { return false; } $data['expire'] = strtotime($data['expire']); return $data; } protected function deleteSession($hash) { $query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE hash = ?"); $query->execute(array($hash)); return $query->rowCount() == 1; } public function checkSession($hash) { $ip = $this->getIp(); $block_status = $this->isBlocked(); if ($block_status == "block") { $return['message'] = $this->lang["user_blocked"]; return false; } if (strlen($hash) != 40) { return false; } $query = $this->dbh->prepare("SELECT id, uid, expiredate, ip, agent, cookie_crc FROM {$this->config->table_sessions} WHERE hash = ?"); $query->execute(array($hash)); if (!$row = $query->fetch(\PDO::FETCH_ASSOC)) { return false; } $sid = $row['id']; $uid = $row['uid']; $expiredate = strtotime($row['expiredate']); $currentdate = strtotime(date("Y-m-d H:i:s")); $db_ip = $row['ip']; $db_agent = $row['agent']; $db_cookie = $row['cookie_crc']; if ($currentdate > $expiredate) { $this->deleteExistingSessions($uid); return false; } if ($ip != $db_ip) { return false; } if ($db_cookie == sha1($hash . $this->config->site_key)) { return true; } return false; } public function getSessionUID($hash) { $query = $this->dbh->prepare("SELECT uid FROM {$this->config->table_sessions} WHERE hash = ?"); $query->execute(array($hash)); if (!$row = $query->fetch(\PDO::FETCH_ASSOC)) { return false; } return $row['uid']; } protected function deleteExistingSessions($uid) { $query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE uid = ?"); $query->execute(array($uid)); return $query->rowCount() == 1; } public function register($email, $password, $repeatpassword, $params = Array(), $captcha = NULL, $sendmail = NULL) { $return['error'] = true; $block_status = $this->isBlocked(); if ($block_status == "verify") { //if ($this->checkCaptcha($captcha) == false) { $return['message'] = $this->lang["user_verify_failed"]; return $return; //} } if ($block_status == "block") { $return['message'] = $this->lang["user_blocked"]; return $return; } if ($password !== $repeatpassword) { $return['message'] = $this->lang["password_nomatch"]; return $return; } // Validate email $validateEmail = $this->validateEmail($email); if ($validateEmail['error'] == 1) { $return['message'] = $validateEmail['message']; return $return; } // Validate password $validatePassword = $this->validatePassword($password); if ($validatePassword['error'] == 1) { $return['message'] = $validatePassword['message']; return $return; } /*$zxcvbn = new Zxcvbn(); if ($zxcvbn->passwordStrength($password)['score'] < intval($this->config->password_min_score)) { $return['message'] = $this->lang['password_weak']; return $return; }*/ if ($this->isEmailTaken($email)) { $this->addAttempt(); $return['message'] = $this->lang["email_taken"]; return $return; } $addUser = $this->addUser($email, $password, $params, $sendmail); if ($addUser['error'] != 0) { $return['message'] = $addUser['message']; return $return; } $return['error'] = false; $return['message'] = ($sendmail == true ? $this->lang["register_success"] : $this->lang['register_success_emailmessage_suppressed'] ); return $return; } public function logout($hash) { if (strlen($hash) != 40) { return false; } return $this->deleteSession($hash); } protected function validatePassword($password) { $return['error'] = true; if (strlen($password) < (int)$this->config->verify_password_min_length ) { $return['message'] = $this->lang["password_short"]; return $return; } $return['error'] = false; return $return; } protected function validateEmail($email) { $return['error'] = true; if (strlen($email) < (int)$this->config->verify_email_min_length ) { $return['message'] = $this->lang["email_short"]; return $return; } elseif (strlen($email) > (int)$this->config->verify_email_max_length ) { $return['message'] = $this->lang["email_long"]; return $return; }/* elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $return['message'] = $this->lang["email_invalid"]; return $return; } if ( (int)$this->config->verify_email_use_banlist ) { $bannedEmails = json_decode(file_get_contents(__DIR__ . "/files/domains.json")); if (in_array(strtolower(explode('@', $email)[1]), $bannedEmails)) { $return['message'] = $this->lang["email_banned"]; return $return; } }*/ $return['error'] = false; return $return; } public function isBlocked() { $ip = $this->getIp(); $this->deleteAttempts($ip, false); $query = $this->dbh->prepare("SELECT count(*) FROM {$this->config->table_attempts} WHERE ip = ?"); $query->execute(array($ip)); $attempts = $query->fetchColumn(); if ($attempts < intval($this->config->attempts_before_verify)) { return "allow"; } if ($attempts < intval($this->config->attempts_before_ban)) { //return "verify"; return "block"; } return "block"; } protected function addAttempt() { $ip = $this->getIp(); $attempt_expiredate = date("Y-m-d H:i:s", strtotime($this->config->attack_mitigation_time)); $query = $this->dbh->prepare("INSERT INTO {$this->config->table_attempts} (ip, expiredate) VALUES (?, ?)"); return $query->execute(array($ip, $attempt_expiredate)); } protected function deleteAttempts($ip, $all = false) { if ($all==true) { $query = $this->dbh->prepare("DELETE FROM {$this->config->table_attempts} WHERE ip = ?"); return $query->execute(array($ip)); } $query = $this->dbh->prepare("SELECT id, expiredate FROM {$this->config->table_attempts} WHERE ip = ?"); $query->execute(array($ip)); while ($row = $query->fetch(\PDO::FETCH_ASSOC)) { $expiredate = strtotime($row['expiredate']); $currentdate = strtotime(date("Y-m-d H:i:s")); if ($currentdate > $expiredate) { $queryDel = $this->dbh->prepare("DELETE FROM {$this->config->table_attempts} WHERE id = ?"); $queryDel->execute(array($row['id'])); } } } protected function getIp() { if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') { return $_SERVER['HTTP_X_FORWARDED_FOR']; } else { return $_SERVER['REMOTE_ADDR']; } } }
Java
namespace InfluxData.Net.InfluxDb.Models.Responses { public class User { /// <summary> /// User name. /// </summary> public string Name { get; set; } /// <summary> /// Whether or not the user is an administrator. /// </summary> public bool IsAdmin { get; set; } } }
Java
package id3 import ( "bytes" "errors" "io" "time" ) var timestampFormats = []string{ "2006-01-02T15:04:05", "2006-01-02T15:04", "2006-01-02T15", "2006-01-02", "2006-01", "2006", } func parseTime(timeStr string) (time.Time, error) { for i := range timestampFormats { t, err := time.Parse(timestampFormats[i], timeStr) if err == nil { return t, nil } } return time.Time{}, errors.New("invalid time") } func readUntilTerminator(term []byte, buf []byte) ([]byte, error) { for i := 0; i+len(term)-1 < len(buf); i += len(term) { if bytes.Equal(term, buf[i:i+len(term)]) { return buf[:i], nil } } return nil, io.EOF }
Java
<div class="demo-menu"> <div class="menu-section"> <p>You clicked on: {{ selected }}</p> <md-toolbar> <button md-icon-button [md-menu-trigger-for]="menu"> <md-icon>more_vert</md-icon> </button> </md-toolbar> <md-menu #menu="mdMenu"> <button md-menu-item *ngFor="let item of items" (click)="select(item.text)" [disabled]="item.disabled"> {{ item.text }} </button> </md-menu> </div> <div class="menu-section"> <p> Clicking these will navigate:</p> <md-toolbar> <button md-icon-button [md-menu-trigger-for]="anchorMenu"> <md-icon>more_vert</md-icon> </button> </md-toolbar> <md-menu #anchorMenu="mdMenu"> <a md-menu-item *ngFor="let item of items" href="http://www.google.com" [disabled]="item.disabled"> {{ item.text }} </a> </md-menu> </div> <div class="menu-section"> <p> Position x: before </p> <md-toolbar class="end-icon"> <button md-icon-button [md-menu-trigger-for]="posXMenu"> <md-icon>more_vert</md-icon> </button> </md-toolbar> <md-menu x-position="before" #posXMenu="mdMenu" class="before"> <button md-menu-item *ngFor="let item of items" [disabled]="item.disabled"> {{ item.text }} </button> </md-menu> </div> <div class="menu-section"> <p> Position y: above </p> <md-toolbar> <button md-icon-button [md-menu-trigger-for]="posYMenu"> <md-icon>more_vert</md-icon> </button> </md-toolbar> <md-menu y-position="above" #posYMenu="mdMenu"> <button md-menu-item *ngFor="let item of items" [disabled]="item.disabled"> {{ item.text }} </button> </md-menu> </div> </div>
Java
using Argolis.Hydra.Annotations; using Argolis.Models; using Vocab; namespace TestHydraApi { public class IssueFilter : ITemplateParameters<Issue> { [Property(Schema.title)] public string Title { get; set; } [Property(Schema.BaseUri + "year")] [Range(Xsd.integer)] public int? Year { get; set; } } }
Java
// make a linked list that has one member // then make 5 nodes - with each node having 1,2,3,4,5 as data // then print them out // then work out how to reverse the list by only changing the pointers // then print again #include <stdio.h> #include <stdlib.h> // Including this header to use malloc struct node { int num; struct node *next; }; struct node *head = NULL; struct node *p = NULL; void insert(int num) { struct node *point = (struct node*) malloc(sizeof(struct node)); point->num = num; point->next = NULL; if(head==NULL) { head = point; head->next = point; return; } p = head; while(p->next != head){ p = p->next; } p->next = point; point->next = head; } void printNum() { struct node *pntr = head; printf("\nhead:"); while(pntr->next != head) { printf(" %d ", pntr->num); pntr = pntr->next; } printf(" %d ", pntr->num); printf("\n"); } int main() { insert(1); insert(2); insert(3); insert(4); insert(5); printNum(); }
Java
#pragma once #include <rikitiki/http/content_types.h> #include <vector> #include <map> #include <array> #include <mxcomp/reflection.h> #ifdef _MSC_VER #define constexpr #endif namespace rikitiki { class ConnContext; struct Response; template <typename T> struct ContentHandler_ { static constexpr std::array<ContentType::t, 1> ContentTypes() { return{ { ContentType::DEFAULT } }; }; }; struct OutProvider { template<typename S, typename T> static auto Make() -> void(*)(ConnContext&, S&) { return [](ConnContext& ctx, S& s) { T t; t << s; ctx << t; }; } }; struct InProvider { template<typename S, typename T> static auto Make() -> void(*)(ConnContext&, S&) { return [](ConnContext& ctx, S& s) { T t; ctx >> t; t >> s; }; } }; template <typename S, typename FProvider, typename... T> struct TypeConversions { typedef TypeConversions<S, FProvider, T...> thisType; typedef TypeConversions<std::vector<S>, FProvider, T...> VectorType; template <typename Th, typename...Tt> struct HandlerAdders { static void Add(thisType* _this){ HandlerAdders<Th>::Add(_this); HandlerAdders<Tt...>::Add(_this); } }; template <typename Th> struct HandlerAdders<Th> { static auto Add(thisType* _this) -> void { for (auto contentType : ContentHandler_<Th>::ContentTypes()){ assert(contentType > ContentType::DEFAULT && contentType < ContentType::MAX && "Invalid content type value in specialized handler"); _this->handlers[contentType] = FProvider::template Make<S, Th>(); } } }; typedef void(*Setter)(ConnContext&, S& s); std::vector<Setter> handlers; TypeConversions() { handlers.resize(ContentType::MAX); HandlerAdders<T...>::Add(this); } static thisType& Instance() { static thisType Instance; return Instance; } }; template<typename T, typename enable = void > struct valid_conversions { }; } #ifdef USE_JSONCPP #include <rikitiki/jsoncpp/jsoncpp> namespace rikitiki { using namespace mxcomp; template<typename T> struct valid_conversions<T, typename std::enable_if< std::is_function <decltype(MetaClass_<T>::fields)>::value >::type > { typedef TypeConversions<T, InProvider, Json::Value> In; typedef TypeConversions<T, OutProvider, Json::Value> Out; }; template <typename T> struct valid_conversions<std::vector<T>, typename std::enable_if< std::is_class<valid_conversions<T> >::value >::type > { typedef typename valid_conversions<T>::In::VectorType In; typedef typename valid_conversions<T>::Out::VectorType Out; }; } #endif
Java
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit037b77112e3f60b3fb10492299961fe0::getLoader();
Java
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Office = Microsoft.Office.Core; // TODO: Follow these steps to enable the Ribbon (XML) item: // 1: Copy the following code block into the ThisAddin, ThisWorkbook, or ThisDocument class. // protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject() // { // return new Ribbon(); // } // 2. Create callback methods in the "Ribbon Callbacks" region of this class to handle user // actions, such as clicking a button. Note: if you have exported this Ribbon from the Ribbon designer, // move your code from the event handlers to the callback methods and modify the code to work with the // Ribbon extensibility (RibbonX) programming model. // 3. Assign attributes to the control tags in the Ribbon XML file to identify the appropriate callback methods in your code. // For more information, see the Ribbon XML documentation in the Visual Studio Tools for Office Help. namespace BadgerAddin2010 { [ComVisible(true)] public class Ribbon : Office.IRibbonExtensibility { private Office.IRibbonUI ribbon; public Ribbon() { } #region IRibbonExtensibility Members public string GetCustomUI(string ribbonID) { //if ("Microsoft.Outlook.Mail.Read" == ribbonID) // return GetResourceText("BadgerAddin2010.Ribbon.xml"); //else return null; } #endregion #region Ribbon Callbacks //Create callback methods here. For more information about adding callback methods, visit http://go.microsoft.com/fwlink/?LinkID=271226 public void Ribbon_Load(Office.IRibbonUI ribbonUI) { this.ribbon = ribbonUI; } #endregion #region Helpers private static string GetResourceText(string resourceName) { Assembly asm = Assembly.GetExecutingAssembly(); string[] resourceNames = asm.GetManifestResourceNames(); for (int i = 0; i < resourceNames.Length; ++i) { if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0) { using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i]))) { if (resourceReader != null) { return resourceReader.ReadToEnd(); } } } } return null; } #endregion } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace MusicStore.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
Java
using System.Web.Mvc; using Microsoft.Practices.Unity; using Unity.Mvc4; namespace MVCForum.IOC { public static class Bootstrapper { public static IUnityContainer Initialise() { var container = BuildUnityContainer(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); return container; } private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); // register all your components with the container here // it is NOT necessary to register your controllers // e.g. container.RegisterType<ITestService, TestService>(); RegisterTypes(container); return container; } public static void RegisterTypes(IUnityContainer container) { } } }
Java
{% extends "content_template.html" %} {% from "components/page-header.html" import page_header %} {% from "components/copy-to-clipboard.html" import copy_to_clipboard %} {% block per_page_title %} Billing details {% endblock %} {% block content_column_content %} {{ page_header('Billing details') }} <p class="govuk-body"> You can use the information on this page to add the Cabinet Office as a supplier. Your organisation may need to do this before you can raise a purchase order (PO). </p> <p class="govuk-body"> <a class="govuk-link govuk-link--no-visited-state" href="{{ url_for('main.support') }}">Contact us</a> if you need any other details. </p> <h2 class="heading-medium govuk-!-margin-top-7" id="supplier-details"> Supplier details </h2> <p class="govuk-body"> Cabinet Office </p> <p class="govuk-body"> The White Chapel Building <br> 10 Whitechapel High Street <br> London <br> E1 8QS </p> <h3 class="heading-small" id="email-addresses"> Email addresses </h3> <ul class="govuk-list govuk-list--bullet"> {% for email in billing_details['notify_billing_email_addresses'] %} <li> {{ email }} </li> {% endfor %} </ul> <h3 class="heading-small" id="vat-number"> <abbr title="Value Added Tax">VAT</abbr> number </h3> <div class="govuk-!-margin-bottom-4"> {{ copy_to_clipboard( 'GB 88 88 010 80', thing='<abbr title="Value Added Tax">VAT</abbr> number', ) }} </div> <h2 class="heading-medium govuk-!-margin-top-7" id="bank-details"> Bank details </h2> <p class="govuk-body"> National Westminster Bank PLC (part of RBS group) <br> Government Banking Services Branch <br> 2nd Floor <br> 280 Bishopsgate <br> London <br> EC2M 4RB </p> <h3 class="heading-small" id="account-name"> Account name </h3> <p class="govuk-body"> Cabinet Office </p> <h3 class="heading-small" id="account-number"> Account number </h3> <div class="govuk-!-margin-bottom-4"> {{ copy_to_clipboard( billing_details['account_number'], thing='account number', ) }} </div> <h3 class="heading-small" id="sort-code"> Sort code </h3> <div class="govuk-!-margin-bottom-4"> {{ copy_to_clipboard( billing_details['sort_code'], thing='sort code', ) }} </div> <h3 class="heading-small" id="iban"> <abbr title="International Bank Account Number">IBAN</abbr> </h3> <div class="govuk-!-margin-bottom-4"> {{ copy_to_clipboard( billing_details['IBAN'], thing='IBAN', ) }} </div> <h3 class="heading-small" id="swift-code"> Swift code </h3> <div class="govuk-!-margin-bottom-4"> {{ copy_to_clipboard( billing_details['swift'], thing='Swift code', ) }} </div> <h2 class="heading-medium govuk-!-margin-top-7" id="invoice-address"> Invoice address </h2> <p class="govuk-body"> SSCL – Accounts Receivable <br> PO Box 221 <br> Thornton-Cleveleys <br> Blackpool <br> Lancashire <br> FY1 9JN </p> {% endblock %}
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using InTheHand.Net; using InTheHand.Net.Sockets; using InTheHand.Net.Bluetooth; namespace NXTLib { public static class Utils { public static string AddressByte2String(byte[] address, bool withcolons) { //BluetoothAddress adr = new BluetoothAddress(address); //string c = adr.ToString(); string[] str = new string[6]; for (int i = 0; i < 6; i++) str[i] = address[5 - i].ToString("x2"); string sep = ":"; if (!withcolons) { sep = ""; } string a = string.Join(sep, str); return a; } public static byte[] AddressString2Byte(string address, bool withcolons) { byte[] a = new byte[6]; int sep = 3; if (!withcolons) { sep = 2; } for (int i = 0; i < 6; i++) { byte b = byte.Parse(address.Substring(i * sep, 2), System.Globalization.NumberStyles.HexNumber); a[5 - i] = b; } return a; } public static List<Brick> Combine(List<Brick> bricks1, List<Brick> bricks2) { List<Brick> bricks = new List<Brick>(); bricks.AddRange(bricks1); bricks.AddRange(bricks2); return bricks; } private static Int64 GetValue(this string value) { if (string.IsNullOrWhiteSpace(value)) { return 0; } Int64 output; // TryParse returns a boolean to indicate whether or not // the parse succeeded. If it didn't, you may want to take // some action here. Int64.TryParse(value, out output); return output; } } }
Java
<!DOCTYPE html> <html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="https://newsblur.com/media/img/favicon.ico" type="image/png" /> <link rel="icon" href="https://newsblur.com/media/img/favicon_32.png" sizes="32x32"/> <link rel="icon" href="https://newsblur.com/media/img/favicon_64.png" sizes="64x64"/> <link rel="alternate" type="application/rss+xml" title="The NewsBlur Blog RSS feed" href="/feed.xml" /><!-- Begin Jekyll SEO tag v2.7.1 --> <title>Even the folders have RSS feeds | The NewsBlur Blog</title> <meta name="generator" content="Jekyll v4.2.0" /> <meta property="og:title" content="Even the folders have RSS feeds" /> <meta property="og:locale" content="en_US" /> <meta name="description" content="What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what." /> <meta property="og:description" content="What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what." /> <link rel="canonical" href="https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/" /> <meta property="og:url" content="https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/" /> <meta property="og:site_name" content="The NewsBlur Blog" /> <meta property="og:type" content="article" /> <meta property="article:published_time" content="2015-08-25T07:00:14-04:00" /> <meta name="twitter:card" content="summary" /> <meta property="twitter:title" content="Even the folders have RSS feeds" /> <script type="application/ld+json"> {"publisher":{"@type":"Organization","logo":{"@type":"ImageObject","url":"https://blog.newsblur.com/assets/newsblur_logo_512.png"}},"url":"https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/","@type":"BlogPosting","headline":"Even the folders have RSS feeds","dateModified":"2015-08-25T07:00:14-04:00","datePublished":"2015-08-25T07:00:14-04:00","description":"What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what.","mainEntityOfPage":{"@type":"WebPage","@id":"https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/"},"@context":"https://schema.org"}</script> <!-- End Jekyll SEO tag --> <link rel="stylesheet" href="/assets/main.css"> <link rel="stylesheet" type="text/css" href="https://cloud.typography.com/6565292/711824/css/fonts.css" /> <link rel="stylesheet" type="text/css" href="https://cloud.typography.com/6565292/731824/css/fonts.css" /><link type="application/atom+xml" rel="alternate" href="https://blog.newsblur.com/feed.xml" title="The NewsBlur Blog" /></head> <body><header class="site-header" role="banner"> <div class="wrapper"><a class="site-title" rel="author" href="/"> <div class="site-title-image"> <img src="/assets/newsblur_logo_512.png"> </div> <div class="site-title-text">The NewsBlur Blog</div> </a><nav class="site-nav"> <input type="checkbox" id="nav-trigger" class="nav-trigger" /> <label for="nav-trigger"> <span class="menu-icon"> <svg viewBox="0 0 18 15" width="18px" height="15px"> <path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"/> </svg> </span> </label> <div class="trigger"><a class="page-link" href="https://www.newsblur.com">Visit NewsBlur ➤</a></div> </nav></div> </header> <header class="site-subheader" role="banner"> <div class="wrapper"> <div class="top"> NewsBlur is a personal news reader that brings people together to talk about the world. </div> <div class="bottom"> A new sound of an old instrument. </div> </div> </header> <main class="page-content" aria-label="Content"> <div class="wrapper"> <article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting"> <header class="post-header"> <h1 class="post-title p-name" itemprop="name headline">Even the folders have RSS feeds</h1> <p class="post-meta"> <time class="dt-published" datetime="2015-08-25T07:00:14-04:00" itemprop="datePublished">Aug 25, 2015 </time></p> </header> <div class="post-content e-content" itemprop="articleBody"> <p>What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what.</p> <p>NewsBlur now supports RSS feeds for each of your folders. Just right-click on the folder, go to Folder Settings, and behold:</p> <p><img src="https://s3.amazonaws.com/static.newsblur.com/blog/folder_rss.png" alt="" /></p> <p>These folders keep track of sites you add and remove from them. They also allow you to filter out stories you don’t want to read or even choose to only show the stories you have in focus.</p> <p>All of your feed subscriptions in the folder, including subfolders, are merged into a single river of news in RSS format. Technically we use Atom 1.0 format for NewsBlur’s many RSS feeds, but I’m not choosing a side here.</p> <p>The Folder RSS feeds join the Shared Stories RSS feeds and the Saved Story Tag RSS feeds that you can already use if you are a premium subscriber.</p> </div><a class="u-url" href="/2015/08/25/even-the-folders-have-rss-feeds/" hidden></a> </article> </div> </main><footer class="site-footer h-card"> <data class="u-url" href="/"></data> <div class="wrapper"> <h2 class="footer-heading">The NewsBlur Blog</h2> <div class="footer-col-wrapper"> <div class="footer-col footer-col-1"><ul class="social-media-list"><li><a href="https://github.com/samuelclay"><svg class="svg-icon"><use xlink:href="/assets/minima-social-icons.svg#github"></use></svg> <span class="username">samuelclay</span></a></li><li><a href="https://www.twitter.com/newsblur"><svg class="svg-icon"><use xlink:href="/assets/minima-social-icons.svg#twitter"></use></svg> <span class="username">newsblur</span></a></li><li><a href="mailto:blog@newsblur.com?subject=Hello from the NewsBlur blog"><svg class="svg-icon"><use xlink:href="/assets/minima-social-icons.svg#email"></use></svg> <span class="username">blog@newsblur.com</span></a></li></ul> </div> <div class="footer-col footer-col-3"> <p>NewsBlur is a personal news reader that brings people together to talk about the world.<br /> A new sound of an old instrument.<br /> </p> </div> </div> </div> </footer> </body> </html>
Java
<ion-view view-title="Coffee Shop"> <ion-content> <div class="card"> <div class="item item-divider text-center"> <h2>{{biz.businessName}}</h2> </div> <div class="item text-center"> <div><strong>{{biz.street}}</strong></div> <div><strong>{{biz.city}}, {{biz.state}} {{biz.zip}}</strong></div> </div> <div class="item text-center"> <a class="item" href="tel:{{biz.phone}}" style="font-size: 150%;"> <i class="icon ion-ios7-telephone" style="font-size: 150%;"></i> Call {{biz.phone}} </a> </div> </div> <div class="card" map zoom="18" ng-init="initMap()" disable-default-u-i="false" disable-double-click-zoom="false" draggable="true" draggable-cursor="help" dragging-cursor="move" keyboard-shortcuts="false" max-zoom="20" min-zoom="8" tilt="0" map-type-id="ROADMAP" style=" height: 300px;"> </div> </ion-content> </ion-view>
Java
<?php /** * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace Clash82\EzPlatformStudioTipsBlockBundle\Installer; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use eZ\Publish\API\Repository\ContentTypeService; use eZ\Publish\API\Repository\Exceptions\ForbiddenException; use eZ\Publish\API\Repository\Exceptions\NotFoundException; use eZ\Publish\API\Repository\Exceptions\UnauthorizedException; use eZ\Publish\API\Repository\Repository; use eZ\Publish\API\Repository\UserService; class ContentTypeInstaller extends Command { /** @var int */ const ADMIN_USER_ID = 14; /** @var \eZ\Publish\API\Repository\Repository */ private $repository; /** @var \eZ\Publish\API\Repository\UserService */ private $userService; /** @var \eZ\Publish\API\Repository\ContentTypeService */ private $contentTypeService; /** * @param \eZ\Publish\API\Repository\Repository $repository * @param \eZ\Publish\API\Repository\UserService $userService * @param \eZ\Publish\API\Repository\ContentTypeService $contentTypeService */ public function __construct( Repository $repository, UserService $userService, ContentTypeService $contentTypeService ) { $this->repository = $repository; $this->userService = $userService; $this->contentTypeService = $contentTypeService; parent::__construct(); } protected function configure() { $this->setName('ezstudio:tips-block:install') ->setHelp('Creates a new `Tip` ContentType.') ->addOption( 'name', null, InputOption::VALUE_OPTIONAL, 'replaces default ContentType <info>name</info>', 'Tip' ) ->addOption( 'identifier', null, InputOption::VALUE_OPTIONAL, 'replaces default ContentType <info>identifier</info>', 'tip' ) ->addOption( 'group_identifier', null, InputOption::VALUE_OPTIONAL, 'replaces default ContentType <info>group_identifier</info>', 'Content' ); } protected function execute(InputInterface $input, OutputInterface $output) { $groupIdentifier = $input->getOption('group_identifier'); $identifier = $input->getOption('identifier'); $name = $input->getOption('name'); try { $contentTypeGroup = $this->contentTypeService->loadContentTypeGroupByIdentifier($groupIdentifier); } catch (NotFoundException $e) { $output->writeln(sprintf('ContentType group with identifier %s not found', $groupIdentifier)); return; } // create basic ContentType structure $contentTypeCreateStruct = $this->contentTypeService->newContentTypeCreateStruct($identifier); $contentTypeCreateStruct->mainLanguageCode = 'eng-GB'; $contentTypeCreateStruct->nameSchema = '<title>'; $contentTypeCreateStruct->names = [ 'eng-GB' => $identifier, ]; $contentTypeCreateStruct->descriptions = [ 'eng-GB' => 'Tip of the day', ]; // add Title field $titleFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('title', 'ezstring'); $titleFieldCreateStruct->names = [ 'eng-GB' => 'Title', ]; $titleFieldCreateStruct->descriptions = [ 'eng-GB' => 'Title', ]; $titleFieldCreateStruct->fieldGroup = 'content'; $titleFieldCreateStruct->position = 1; $titleFieldCreateStruct->isTranslatable = true; $titleFieldCreateStruct->isRequired = true; $titleFieldCreateStruct->isSearchable = true; $contentTypeCreateStruct->addFieldDefinition($titleFieldCreateStruct); // add Description field $bodyFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('body', 'ezrichtext'); $bodyFieldCreateStruct->names = [ 'eng-GB' => 'Body', ]; $bodyFieldCreateStruct->descriptions = [ 'eng-GB' => 'Body', ]; $bodyFieldCreateStruct->fieldGroup = 'content'; $bodyFieldCreateStruct->position = 2; $bodyFieldCreateStruct->isTranslatable = true; $bodyFieldCreateStruct->isRequired = true; $bodyFieldCreateStruct->isSearchable = true; $contentTypeCreateStruct->addFieldDefinition($bodyFieldCreateStruct); try { $contentTypeDraft = $this->contentTypeService->createContentType($contentTypeCreateStruct, [ $contentTypeGroup, ]); $this->contentTypeService->publishContentTypeDraft($contentTypeDraft); $output->writeln(sprintf( '<info>%s ContentType created with ID %d</info>', $name, $contentTypeDraft->id )); } catch (UnauthorizedException $e) { $output->writeln(sprintf('<error>%s</error>', $e->getMessage())); return; } catch (ForbiddenException $e) { $output->writeln(sprintf('<error>%s</error>', $e->getMessage())); return; } $output->writeln(sprintf( 'Place all your <info>%s</info> content objects into desired folder and then select it as a Parent container in eZ Studio Tips Block options form.', $name )); } protected function initialize(InputInterface $input, OutputInterface $output) { $this->repository->setCurrentUser( $this->userService->loadUser(self::ADMIN_USER_ID) ); } }
Java
# Starter Web App This is my attempt to create a dev workflow which hot reloads client and server side changes. Note: This is still a work in progress ## Installation git clone xyz rm -rf .git npm install gulp (npm run dev) open http://localhost:3000 ## Deployment gulp bundle (npm run bundle) ## What do you get ## Configuration HOST_NAME - used when logging and sending stats to statsd. default is jonsmac STATSD_HOST - the ip address for the statsd server
Java
# frankie - a plugin for sinatra that integrates with the facebooker gem # # written by Ron Evans (http://www.deadprogrammersociety.com) # # based on merb_facebooker (http://github.com/vanpelt/merb_facebooker) # and the Rails classes in Facebooker (http://facebooker.rubyforge.org/) from Mike Mangino, Shane Vitarana, & Chad Fowler # require 'sinatra/base' require 'yaml' require 'uri' gem 'mmangino-facebooker' require 'facebooker' module Sinatra module Frankie module Loader def load_facebook_config(file, env=:development) if File.exist?(file) yaml = YAML.load_file(file)[env.to_s] ENV['FACEBOOK_API_KEY'] = yaml['api_key'] ENV['FACEBOOK_SECRET_KEY'] = yaml['secret_key'] ENV['FACEBOOKER_RELATIVE_URL_ROOT'] = yaml['canvas_page_name'] end end end module Helpers def facebook_session @facebook_session end def facebook_session_parameters {:fb_sig_session_key=>params["fb_sig_session_key"]} end def set_facebook_session session_set = session_already_secured? || secure_with_token! || secure_with_facebook_params! if session_set capture_facebook_friends_if_available! Facebooker::Session.current = facebook_session end session_set end def facebook_params @facebook_params ||= verified_facebook_params end def session_already_secured? (@facebook_session = session[:facebook_session]) && session[:facebook_session].secured? end def secure_with_token! if params['auth_token'] @facebook_session = new_facebook_session @facebook_session.auth_token = params['auth_token'] @facebook_session.secure! session[:facebook_session] = @facebook_session end end def secure_with_facebook_params! return unless request_is_for_a_facebook_canvas? if ['user', 'session_key'].all? {|element| facebook_params[element]} @facebook_session = new_facebook_session @facebook_session.secure_with!(facebook_params['session_key'], facebook_params['user'], facebook_params['expires']) session[:facebook_session] = @facebook_session end end def create_new_facebook_session_and_redirect! session[:facebook_session] = new_facebook_session throw :halt, do_redirect(session[:facebook_session].login_url) unless @installation_required end def new_facebook_session Facebooker::Session.create(Facebooker::Session.api_key, Facebooker::Session.secret_key) end def capture_facebook_friends_if_available! return unless request_is_for_a_facebook_canvas? if friends = facebook_params['friends'] facebook_session.user.friends = friends.map do |friend_uid| Facebooker::User.new(friend_uid, facebook_session) end end end def blank?(value) (value == '0' || value.nil? || value == '') end def verified_facebook_params facebook_sig_params = params.inject({}) do |collection, pair| collection[pair.first.sub(/^fb_sig_/, '')] = pair.last if pair.first[0,7] == 'fb_sig_' collection end verify_signature(facebook_sig_params, params['fb_sig']) facebook_sig_params.inject(Hash.new) do |collection, pair| collection[pair.first] = facebook_parameter_conversions[pair.first].call(pair.last) collection end end # 48.hours.ago in sinatra def earliest_valid_session now = Time.now now -= (60 * 60 * 48) now end def verify_signature(facebook_sig_params,expected_signature) raw_string = facebook_sig_params.map{ |*args| args.join('=') }.sort.join actual_sig = Digest::MD5.hexdigest([raw_string, Facebooker::Session.secret_key].join) raise Facebooker::Session::IncorrectSignature if actual_sig != expected_signature raise Facebooker::Session::SignatureTooOld if Time.at(facebook_sig_params['time'].to_f) < earliest_valid_session true end def facebook_parameter_conversions @facebook_parameter_conversions ||= Hash.new do |hash, key| lambda{|value| value} end.merge('time' => lambda{|value| Time.at(value.to_f)}, 'in_canvas' => lambda{|value| !blank?(value)}, 'added' => lambda{|value| !blank?(value)}, 'expires' => lambda{|value| blank?(value) ? nil : Time.at(value.to_f)}, 'friends' => lambda{|value| value.split(/,/)} ) end def do_redirect(*args) if request_is_for_a_facebook_canvas? fbml_redirect_tag(args) else redirect args[0] end end def fbml_redirect_tag(url) "<fb:redirect url=\"#{url}\" />" end def request_is_for_a_facebook_canvas? return false if params["fb_sig_in_canvas"].nil? params["fb_sig_in_canvas"] == "1" end def application_is_installed? facebook_params['added'] end def ensure_authenticated_to_facebook set_facebook_session || create_new_facebook_session_and_redirect! end def ensure_application_is_installed_by_facebook_user @installation_required = true authenticated_and_installed = ensure_authenticated_to_facebook && application_is_installed? application_is_not_installed_by_facebook_user unless authenticated_and_installed authenticated_and_installed end def application_is_not_installed_by_facebook_user throw :halt, do_redirect(session[:facebook_session].install_url) end def set_fbml_format params['format']="fbml" if request_is_for_a_facebook_canvas? end def fb_url_for(url) url = "" if url == "/" url = URI.escape(url) return url if !request_is_for_a_facebook_canvas? "http://apps.facebook.com/#{ENV['FACEBOOKER_RELATIVE_URL_ROOT']}/#{url}" end def do_redirect(*args) if request_is_for_a_facebook_canvas? fbml_redirect_tag(args[0]) else redirect args[0] end end def self.registered(app) app.register Loader app.helpers Helpers end end end
Java
package tutorialHorizon.arrays; /** * Created by archithrapaka on 7/4/17. */ public class InsertionSort { public static void insertionSort(int[] items, int n) { int i, j; for (i = 1; i < n; i++) { j = i; while (j > 0 && (items[j] < items[j - 1])) { swap(items, j, j - 1); j--; } } } public static void swap(int[] items, int i, int j) { int temp = items[i]; items[i] = items[j]; items[j] = temp; } public static void display(int[] a) { for (int i : a) { System.out.print(i + " "); } } public static void main(String[] args) { int[] a = {100, 4, 30, 15, 98, 3}; insertionSort(a, a.length); display(a); } }
Java
import { createContext } from 'react'; export const defaultApiStatus = { offline: false, apiUnreachable: '', appVersionBad: false, }; export default createContext(defaultApiStatus);
Java
> Link jsreport browser sdk into your page and easily render a report from the browser or open limited version of jsreport studio inside any web application and let end users to customize their reports. There are various scenarios where this can be used. Typical example can be when application is sending invoices to the customers and allows them to modify invoice template to the required design. ##Getting started To start using jsreport browser sdk you need to: 1. Include jquery into page 2. Include jsreport `embed.js` into page 3. Create `jsreportInit` function in the global scope with similar meaning as `$.ready` 4. Use global object `jsreport` to open editor or render a template ```html <!DOCTYPE html> <html> <head lang="en"> <!-- jquery is required for jsreport embedding --> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="http://local.net:2000/extension/embedding/public/js/embed.js"></script> </head> <body> <script> //jsreport will call jsreportInit function from global scope when its initialized jsreportInit = function () { //use jsreport object to render reports or open editor }; </script> </body> </html> ``` ##Rendering template Use `jsreport.render` function to invoke template server side rendering. Function takes a whole template json definition or just a string shortid as a parameter. The output report is opened in a new browser tab by default. This can be overridden by setting the first function parameter to jquery object placeholder. ```js //render a template into the new tab jsreport.render({ conent: "foo", recipe: "phantom-pdf", engine: "jsrender" }); //render a template into the placeholder jsreport.render($("#placeholder"), { conent: "foo", recipe: "phantom-pdf", engine: "jsrender" }); ``` ##Opening editor Use `jseport.openEditor` function to pop up jsreport designer in the modal. This functions takes a whole template definition or just a string shortid as a parameter. Function returns an even emitter to which you can bind and listen to `close` or `template-change` events. ```js jsreport.openEditor(template .on("template-change", function (tmpl) { //store changes template= tmpl; }).on("close", function() { //save template to your storage }); ``` You can also submit additional options for jsreport extensions like sample data or custom script in the `openEditor` parameters. ```js jsreport.openEditor({ content: "<h1>Hello World</h1>", data: { dataJson: { price: "1234" } } }); ``` Where `dataJson` can be any json object or parse-able json string. You can also set up a [custom script](/learn/scripts) to the report template loading input data for the report preview. Using custom scripts user can even specify desired input data source on its own. ###Using jsreport storage The jsreport designer is by default stateless and doesn't store the template in any storage. It is expected you listen to the emitted events and store the template in your own storage if you want. To enable storing templates in the jsreport storage just add `useStandardStorage` option when opening editor: ```js //open template from jsreport storage jsreport.openEditor("Z1vT7FHyU", { useStandardStorage: true }); ``` ## Security Using `embed.js` to render or edit templates is possible only when the browser get's access to the jsreport server. Exposing unsecured jsreport server to the public audience doesn't need to be a good idea for the internet applications. In this case you can secure jsreport and keep using `embed.js` using following approaches. One option is to use secure jsreport server using [authentication](/learn/authentication) and [authorization](/learn/authorization) extension to limit access to the jsreport. Anonymous user using `embed.js` can be then authorized using secure token generated by [public-templates](/learn/public-templates) extension. Another options is to create a tunnel forwarding request to jsreport through your application. This hides jsreport behind your security layers and also eliminates cross domain calls. You basically just need to catch and resend requests to jsreport and add `serverUrl` query parameter to specify where the jsreport web client should route requests back. In other words you create a route in your web server which will proxy jsreport server. Example of such a proxy in asp.net can be found [here](https://github.com/jsreport/net/blob/master/jsreport/jsreport.Client/JsReportWebHandler.cs). Implementing such a tunnel in any other language should not be difficult.
Java
module.exports = { //"@context": { type: String, default: "http://schema.org" }, //"@type": { type: String, default: "Article" }, //>>Properties from NewsArticle //dateline: String,//The location where the NewsArticle was produced. //printColumn: String,//The number of the column in which the NewsArticle appears in the print edition. //printEdition: String,//The edition of the print product in which the NewsArticle appears. //printPage: String,//If this NewsArticle appears in print, this field indicates the name of the page on which the article is found. Please note that this field is intended for the exact page name (e.g. A5, B18). //printSection: String,//If this NewsArticle appears in print, this field indicates the print section in which the article appeared. //>>Properties from Article articleBody: String ,//The actual body of the article. //articleSection: String ,//Articles may belong to one or more 'sections' in a magazine or newspaper, such as Sports, Lifestyle, etc. //pageEnd: String or Number ,//The page on which the work ends; for example "138" or "xvi". //pageStart: String or Number ,//The page on which the work starts; for example "135" or "xiii". //pagination: String ,//Any description of pages that is not separated into pageStart and pageEnd; for example, "1-6, 9, 55" or "10-12, 46-49". wordCount: Number ,//The number of words in the text of the Article. //>>Properties from CreativeWork //about: Thing ,//The subject matter of the content. //accessibilityAPI: String ,//Indicates that the resource is compatible with the referenced accessibility API (WebSchemas wiki lists possible values). //accessibilityControl: String ,//Identifies input methods that are sufficient to fully control the described resource (WebSchemas wiki lists possible values). //accessibilityFeature: String ,//Content features of the resource, such as accessible media, alternatives and supported enhancements for accessibility (WebSchemas wiki lists possible values). //accessibilityHazard: String ,//A characteristic of the described resource that is physiologically dangerous to some users. Related to WCAG 2.0 guideline 2.3 (WebSchemas wiki lists possible values). //accountablePerson: Person ,//Specifies the Person that is legally accountable for the CreativeWork. //aggregateRating: AggregateRating ,//The overall rating, based on a collection of reviews or ratings, of the item. //alternativeHeadline: String ,//A secondary title of the CreativeWork. //associatedMedia: MediaObject ,//A media object that encodes this CreativeWork. This property is a synonym for encoding. //audience: Audience ,//The intended audience of the item, i.e. the group for whom the item was created. //audio: AudioObject ,//An embedded audio object. //author: Organization or Person ,//The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangeably. //award: String ,//An award won by this person or for this creative work. Supersedes awards. //character: Person ,//Fictional person connected with a creative work. //citation: String or CreativeWork ,//A citation or reference to another creative work, such as another publication, web page, scholarly article, etc. //comment: UserComments or Comment ,//Comments, typically from users, on this CreativeWork. //commentCount: Number ,//The number of comments this CreativeWork (e.g. Article, Question or Answer) has received. This is most applicable to works published in Web sites with commenting system; additional comments may exist elsewhere. //contentLocation: Place ,//The location of the content. //contentRating: String ,//Official rating of a piece of content—for example,'MPAA PG-13'. //contributor: Organization or Person ,//A secondary contributor to the CreativeWork. //copyrightHolder: Organization or Person ,//The party holding the legal copyright to the CreativeWork. copyrightYear: Number ,//The year during which the claimed copyright for the CreativeWork was first asserted. //creator: Organization or Person ,//The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. dateCreated: { type: Date,//The date on which the CreativeWork was created. default: Date.now }, dateModified: Date ,//The date on which the CreativeWork was most recently modified. datePublished: Date ,//Date of first broadcast/publication. //discussionUrl: URL ,//A link to the page containing the comments of the CreativeWork. //editor: Person ,//Specifies the Person who edited the CreativeWork. //educationalAlignment: AlignmentObject ,//An alignment to an established educational framework. //educationalUse: String ,//The purpose of a work in the context of education; for example, 'assignment', 'group work'. //encoding: MediaObject ,//A media object that encodes this CreativeWork. This property is a synonym for associatedMedia. Supersedes encodings. //exampleOfWork: CreativeWork ,//A creative work that this work is an example/instance/realization/derivation of. Inverse property: workExample. //genre: String ,//Genre of the creative work or group. //hasPart: CreativeWork ,//Indicates a CreativeWork that is (in some sense) a part of this CreativeWork. Inverse property: isPartOf. headline: String ,//Headline of the article. //inLanguage: String ,//The language of the content. please use one of the language codes from the IETF BCP 47 standard. //interactionCount: String ,//A count of a specific user interactions with this item—for example, 20 UserLikes, 5 UserComments, or 300 UserDownloads. The user interaction type should be one of the sub types of UserInteraction. //interactivityType: String ,//The predominant mode of learning supported by the learning resource. Acceptable values are 'active', 'expositive', or 'mixed'. //isBasedOnUrl: URL ,//A resource that was used in the creation of this resource. This term can be repeated for multiple sources. For example, http://example.com/great-multiplication-intro.html. //isFamilyFriendly: Boolean ,//Indicates whether this content is family friendly. //isPartOf: CreativeWork ,//Indicates a CreativeWork that this CreativeWork is (in some sense) part of. Inverse property: hasPart. //keywords: String ,//Keywords or tags used to describe this content. Multiple entries in a keywords list are typically delimited by commas. //learningResourceType: String ,//The predominant type or kind characterizing the learning resource. For example, 'presentation', 'handout'. //license: URL or CreativeWork ,//A license document that applies to this content, typically indicated by URL. //mentions: Thing ,//Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. //offers: Offer ,//An offer to provide this item—for example, an offer to sell a product, rent the DVD of a movie, or give away tickets to an event. //position: String or Number ,//The position of an item in a series or sequence of items. //producer: Organization or Person ,//The person or organization who produced the work (e.g. music album, movie, tv/radio series etc.). //provider: Organization or Person ,//The service provider, service operator, or service performer; the goods producer. Another party (a seller) may offer those services or goods on behalf of the provider. A provider may also serve as the seller. Supersedes carrier. //publisher: Organization ,//The publisher of the creative work. //publishingPrinciples: URL ,//Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. //recordedAt: Event ,//The Event where the CreativeWork was recorded. The CreativeWork may capture all or part of the event. Inverse property: recordedIn. //releasedEvent: PublicationEvent ,//The place and time the release was issued, expressed as a PublicationEvent. //review: Review ,//A review of the item. Supersedes reviews. //sourceOrganization: Organization ,//The Organization on whose behalf the creator was working. //text: String ,//The textual content of this CreativeWork. //thumbnailUrl: URL ,//A thumbnail image relevant to the Thing. //timeRequired: Duration ,//Approximate or typical time it takes to work with or through this learning resource for the typical intended target audience, e.g. 'P30M', 'P1H25M'. //translator: Organization or Person ,//Organization or person who adapts a creative work to different languages, regional differences and technical requirements of a target market. //typicalAgeRange: String ,//The typical expected age range, e.g. '7-9', '11-'. //version: Number ,//The version of the CreativeWork embodied by a specified resource. //video: VideoObject ,//An embedded video object. //workExample: CreativeWork ,//Example/instance/realization/derivation of the concept of this creative work. eg. The paperback edition, first edition, or eBook. Inverse property: exampleOfWork. //>>Properties from Thing //additionalType: URL ,//An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally. //alternateName: String ,//An alias for the item. //description: String ,//A short description of the item. image: require('./image-object'),//An image of the item. This can be a URL or a fully described ImageObject. //name: String ,//The name of the item. //potentialAction: Action ,//Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role. //sameAs: URL ,//URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Freebase page, or official website. //url: URL,//URL of the item. };
Java
from flask import Blueprint, request, render_template from ..load import processing_results from ..abbr import get_abbr_map abbr_map = get_abbr_map() liner_mod = Blueprint('liner', __name__, template_folder='templates', static_folder='static') @liner_mod.route('/liner', methods=['GET', 'POST']) def liner(): if request.method == 'POST': query = request.form['liner-text'] text = query.split('.')[:-1] if len(text) == 0: return render_template('projects/line.html', message='Please separate each line with "."') abbr_expanded_text = "" for word in query.split(): if word in abbr_map: abbr_expanded_text += abbr_map[word] else: abbr_expanded_text += word abbr_expanded_text += " " data, emotion_sents, score, line_sentiment, text, length = processing_results(text) return render_template('projects/line.html', data=[data, emotion_sents, score, zip(text, line_sentiment), length, abbr_expanded_text]) else: return render_template('projects/line.html')
Java
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class Dimension(Model): """Dimension of a resource metric. For e.g. instance specific HTTP requests for a web app, where instance name is dimension of the metric HTTP request. :param name: :type name: str :param display_name: :type display_name: str :param internal_name: :type internal_name: str :param to_be_exported_for_shoebox: :type to_be_exported_for_shoebox: bool """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'internal_name': {'key': 'internalName', 'type': 'str'}, 'to_be_exported_for_shoebox': {'key': 'toBeExportedForShoebox', 'type': 'bool'}, } def __init__(self, name=None, display_name=None, internal_name=None, to_be_exported_for_shoebox=None): super(Dimension, self).__init__() self.name = name self.display_name = display_name self.internal_name = internal_name self.to_be_exported_for_shoebox = to_be_exported_for_shoebox
Java
# Pluralsight React Components A library of React components created in "Creating Reusable React Components" on Pluralsight. ## Install ``` npm install ps-react-dr ``` ## Issues I'll add tips for common problems and address any known course issues here. ## Docs [Component documentation](http://dryzhkov.github.io/ps-react-dr)
Java
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/tools/qdbus/src/qdbusabstractadaptor.cpp --> <head> <title>Qt 4.3: List of All Members for QDBusAbstractAdaptor</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">List of All Members for QDBusAbstractAdaptor</h1> <p>This is the complete list of members for <a href="qdbusabstractadaptor.html">QDBusAbstractAdaptor</a>, including inherited members.</p> <p><table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td width="45%" valign="top"><ul> <li><div class="fn"/><a href="qdbusabstractadaptor.html#QDBusAbstractAdaptor">QDBusAbstractAdaptor</a> ( QObject * )</li> <li><div class="fn"/><a href="qdbusabstractadaptor.html#dtor.QDBusAbstractAdaptor">~QDBusAbstractAdaptor</a> ()</li> <li><div class="fn"/><a href="qdbusabstractadaptor.html#autoRelaySignals">autoRelaySignals</a> () const : bool</li> <li><div class="fn"/><a href="qobject.html#blockSignals">blockSignals</a> ( bool ) : bool</li> <li><div class="fn"/><a href="qobject.html#childEvent">childEvent</a> ( QChildEvent * )</li> <li><div class="fn"/><a href="qobject.html#children">children</a> () const : const QObjectList &amp;</li> <li><div class="fn"/><a href="qobject.html#connect">connect</a> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType ) : bool</li> <li><div class="fn"/><a href="qobject.html#connect-2">connect</a> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const : bool</li> <li><div class="fn"/><a href="qobject.html#connectNotify">connectNotify</a> ( const char * )</li> <li><div class="fn"/><a href="qobject.html#customEvent">customEvent</a> ( QEvent * )</li> <li><div class="fn"/><a href="qobject.html#deleteLater">deleteLater</a> ()</li> <li><div class="fn"/><a href="qobject.html#destroyed">destroyed</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#disconnect">disconnect</a> ( const QObject *, const char *, const QObject *, const char * ) : bool</li> <li><div class="fn"/><a href="qobject.html#disconnect-2">disconnect</a> ( const char *, const QObject *, const char * ) : bool</li> <li><div class="fn"/><a href="qobject.html#disconnect-3">disconnect</a> ( const QObject *, const char * ) : bool</li> <li><div class="fn"/><a href="qobject.html#disconnectNotify">disconnectNotify</a> ( const char * )</li> <li><div class="fn"/><a href="qobject.html#dumpObjectInfo">dumpObjectInfo</a> ()</li> <li><div class="fn"/><a href="qobject.html#dumpObjectTree">dumpObjectTree</a> ()</li> <li><div class="fn"/><a href="qobject.html#dynamicPropertyNames">dynamicPropertyNames</a> () const : QList&lt;QByteArray&gt;</li> <li><div class="fn"/><a href="qobject.html#event">event</a> ( QEvent * ) : bool</li> <li><div class="fn"/><a href="qobject.html#eventFilter">eventFilter</a> ( QObject *, QEvent * ) : bool</li> <li><div class="fn"/><a href="qobject.html#findChild">findChild</a> ( const QString &amp; ) const : T</li> <li><div class="fn"/><a href="qobject.html#findChildren">findChildren</a> ( const QString &amp; ) const : QList&lt;T&gt;</li> <li><div class="fn"/><a href="qobject.html#findChildren-2">findChildren</a> ( const QRegExp &amp; ) const : QList&lt;T&gt;</li> <li><div class="fn"/><a href="qobject.html#inherits">inherits</a> ( const char * ) const : bool</li> </ul></td><td valign="top"><ul> <li><div class="fn"/><a href="qobject.html#installEventFilter">installEventFilter</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#isWidgetType">isWidgetType</a> () const : bool</li> <li><div class="fn"/><a href="qobject.html#killTimer">killTimer</a> ( int )</li> <li><div class="fn"/><a href="qobject.html#metaObject">metaObject</a> () const : const QMetaObject *</li> <li><div class="fn"/><a href="qobject.html#moveToThread">moveToThread</a> ( QThread * )</li> <li><div class="fn"/><a href="qobject.html#objectName-prop">objectName</a> () const : QString</li> <li><div class="fn"/><a href="qobject.html#parent">parent</a> () const : QObject *</li> <li><div class="fn"/><a href="qobject.html#property">property</a> ( const char * ) const : QVariant</li> <li><div class="fn"/><a href="qobject.html#receivers">receivers</a> ( const char * ) const : int</li> <li><div class="fn"/><a href="qobject.html#removeEventFilter">removeEventFilter</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#sender">sender</a> () const : QObject *</li> <li><div class="fn"/><a href="qdbusabstractadaptor.html#setAutoRelaySignals">setAutoRelaySignals</a> ( bool )</li> <li><div class="fn"/><a href="qobject.html#objectName-prop">setObjectName</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qobject.html#setParent">setParent</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#setProperty">setProperty</a> ( const char *, const QVariant &amp; ) : bool</li> <li><div class="fn"/><a href="qobject.html#signalsBlocked">signalsBlocked</a> () const : bool</li> <li><div class="fn"/><a href="qobject.html#startTimer">startTimer</a> ( int ) : int</li> <li><div class="fn"/><a href="qobject.html#staticMetaObject-var">staticMetaObject</a> : const QMetaObject</li> <li><div class="fn"/><a href="qobject.html#thread">thread</a> () const : QThread *</li> <li><div class="fn"/><a href="qobject.html#timerEvent">timerEvent</a> ( QTimerEvent * )</li> <li><div class="fn"/><a href="qobject.html#tr">tr</a> ( const char *, const char *, int ) : QString</li> <li><div class="fn"/><a href="qobject.html#trUtf8">trUtf8</a> ( const char *, const char *, int ) : QString</li> </ul> </td></tr> </table></p> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td> <td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="30%" align="right"><div align="right">Qt 4.3.5</div></td> </tr></table></div></address></body> </html>
Java
typedef struct { f_t x, y; } vec_t, *vec; //inline f_t cross(vec a, vec b) { return a->x * b->y - a->y * b->x; } //inline vec vsub(vec a, vec b, vec res) { res->x = a->x - b->x; res->y = a->y - b->y; } // Does point c lie on the left side of directed edge a->b? // 1 if left, -1 if right, 0 if on the line int c_left_of_ab(vec a, vec b, vec c) { vec_t tmp1, tmp2; f_t x; vsub(b, a, &tmp1); vsub(c, b, &tmp2); x = cross(&tmp1, &tmp2); return x < 0 ? -1 : x > 0; }
Java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.common.mixin.api.mcp.tileentity; import net.minecraft.tileentity.TileEntityDropper; import org.spongepowered.api.block.tileentity.carrier.Dropper; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.asm.mixin.Mixin; @NonnullByDefault @Mixin(TileEntityDropper.class) public abstract class TileEntityDropperMixin_API extends TileEntityDispenserMixin_API implements Dropper { }
Java
<!doctype html> <html lang="en"> <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.0"> <title>Experiments - Weking</title> <link rel="stylesheet" href="dist/css/weking.css"> <link rel="stylesheet" href="dist/css/weking-theme.css"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <![endif]--> </head> <body> <!-- HEADER NAVBAR --> <nav class="navbar menu menu-primary-topState"> <div class="menu_header"> <label class="menu_a menu_brand" for="navbarTrigger"> <i class="icon icon_menu"></i> </label> <a class="menu_a menu_brand" href="index.html">Weking > Experiments</a> <div class="navbar_actionBtns"> <a class="btn btn-secondary-sm" href="https://github.com/weking/weking-frontend/archive/master.zip">Download</a> <a class="btn btn-default-ghost-sm" href="https://github.com/weking">Github</a> </div> </div> </nav> <input type="checkbox" id="navbarTrigger" class="navDrawer_trigger"> <section class="navDrawer"> <label for="navbarTrigger" class="navDrawer_overlay"></label> <section class="navDrawer_content menu col col-xs8-sm6-md4-lg2-vert"> <input checked class="menu_trigger" type="checkbox"> <ul class="menu_ul"> <li class="menu_li"><a class="menu_a" href="index.html">Home</a></li> <li class="menu_li"><a class="menu_a" href="get-started.html">Get Started</a></li> <li class="menu_li"><a class="menu_a" href="core.html">Core</a></li> <li class="menu_li"><a class="menu_a" href="addons.html">Addons</a></li> <li class="menu_li"><a class="menu_a" href="layout.html">Layout</a></li> <li class="menu_li"> <a class="menu_a" href="templates.html"> Templates <span class="label label-red">IN DEV</span> </a> </li> <li class="menu_li"> <a class="menu_a" href="experiments.html"> Experiments <span class="label label-red">IN DEV</span> </a> </li> </ul> </section> </section> <!-- HERO HEADING --> <header class="header header-primary-small"> <div class="header_wrap"> <div class="container"> <h1 class="typo_h1">Experiments</h1> </div> </div> </header> <!-- MAIN --> <main class="main"> <div class="container"> <section class="content card"> <div class="card_content"> <h2 class="typo_h2">Page in development</h2> </div> </section> </div> </main> <!-- SHARE FAB --> <div class="fab"> <span class="tooltip tooltip-left" data-tooltip="Share This Page"> <a class="fab_btn addthis_button_expanded btn btn-secondary-radius"> <i class="icon icon_share"></i> </a> </span> </div> <!-- PAGINATION --> <footer class="pagination row"> <a href="templates.html" class="pagination_item col col_xs9_sm6-orange typo_h3"> <i class="icon icon_arrow-back"></i> Templates </a> <span class="pagination_item col col_xs3_sm6-black typo_h3"></span> </footer> <!-- JScripts --> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-54ce258b7e3ce750" async="async"></script> <script async src="//assets.codepen.io/assets/embed/ei.js"></script> <script src="dist/js/script.js"></script> </body> </html>
Java
var fs = require('fs') var d3 = require('d3') var request = require('request') var cheerio = require('cheerio') var queue = require('queue-async') var _ = require('underscore') var glob = require("glob") var games = [] glob.sync(__dirname + "/raw-series/*").forEach(scrape) function scrape(dir, i){ var series = dir.split('/raw-series/')[1] process.stdout.write("parsing " + i + " " + series + "\r") var html = fs.readFileSync(dir, 'utf-8') var $ = cheerio.load(html) $('a').each(function(i){ var str = $(this).text() var href = $(this).attr('href') if (str == 'box scores' || !~href.indexOf('/boxscores/') || i % 2) return games.push({series: series, boxLink: $(this).attr('href').replace('/boxscores/', '')}) }) } fs.writeFileSync(__dirname + '/playoffGames.csv', d3.csv.format(games)) var q = queue(1) var downloaded = glob.sync(__dirname + '/raw-box/*.html').map(d => d.split('/raw-box/')[1]) games .map(d => d.boxLink) .filter(d => !_.contains(downloaded, d)) .forEach(d => q.defer(downloadBox, d)) function downloadBox(d, cb){ process.stdout.write("downloading " + d + "\r"); var url = 'http://www.basketball-reference.com/boxscores/' + d // console.log(url) setTimeout(cb, 1000) request(url, function(error, response, html){ var path = __dirname + '/raw-box/' + d fs.writeFileSync(path, html) }) }
Java
// FoalTS import { FileSystem } from '../../file-system'; export function createVSCodeConfig() { new FileSystem() // TODO: test this line .cdProjectRootDir() .ensureDir('.vscode') .cd('.vscode') .copy('vscode-config/launch.json', 'launch.json') .copy('vscode-config/tasks.json', 'tasks.json'); }
Java
import { strictEqual } from 'assert'; import { Config, HttpResponse, HttpResponseOK } from '../core'; import { SESSION_DEFAULT_COOKIE_HTTP_ONLY, SESSION_DEFAULT_COOKIE_NAME, SESSION_DEFAULT_COOKIE_PATH, SESSION_DEFAULT_CSRF_COOKIE_NAME, SESSION_DEFAULT_SAME_SITE_ON_CSRF_ENABLED, SESSION_USER_COOKIE_NAME, } from './constants'; import { removeSessionCookie } from './remove-session-cookie'; describe('removeSessionCookie', () => { let response: HttpResponse; beforeEach(() => response = new HttpResponseOK()); describe('should set a session cookie in the response', () => { context('given no configuration option is provided', () => { beforeEach(() => removeSessionCookie(response)); it('with the proper default name and value.', () => { const { value } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(value, ''); }); it('with the proper default "domain" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.domain, undefined); }); it('with the proper default "httpOnly" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.httpOnly, SESSION_DEFAULT_COOKIE_HTTP_ONLY); }); it('with the proper default "path" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.path, SESSION_DEFAULT_COOKIE_PATH); }); it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.sameSite, undefined); }); it('with the proper default "secure" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.secure, undefined); }); it('with the proper "maxAge" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.maxAge, 0); }); }); context('given configuration options are provided', () => { const cookieName = SESSION_DEFAULT_COOKIE_NAME + '2'; beforeEach(() => { Config.set('settings.session.cookie.name', cookieName); Config.set('settings.session.cookie.domain', 'example.com'); Config.set('settings.session.cookie.httpOnly', false); Config.set('settings.session.cookie.path', '/foo'); Config.set('settings.session.cookie.sameSite', 'strict'); Config.set('settings.session.cookie.secure', true); removeSessionCookie(response); }); afterEach(() => { Config.remove('settings.session.cookie.name'); Config.remove('settings.session.cookie.domain'); Config.remove('settings.session.cookie.httpOnly'); Config.remove('settings.session.cookie.path'); Config.remove('settings.session.cookie.sameSite'); Config.remove('settings.session.cookie.secure'); }); it('with the proper default name and value.', () => { const { value } = response.getCookie(cookieName); strictEqual(value, ''); }); it('with the proper default "domain" directive.', () => { const { options } = response.getCookie(cookieName); strictEqual(options.domain, 'example.com'); }); it('with the proper default "httpOnly" directive.', () => { const { options } = response.getCookie(cookieName); strictEqual(options.httpOnly, false); }); it('with the proper default "path" directive.', () => { const { options } = response.getCookie(cookieName); strictEqual(options.path, '/foo'); }); it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(cookieName); strictEqual(options.sameSite, 'strict'); }); it('with the proper default "secure" directive.', () => { const { options } = response.getCookie(cookieName); strictEqual(options.secure, true); }); it('with the proper "maxAge" directive.', () => { const { options } = response.getCookie(cookieName); strictEqual(options.maxAge, 0); }); }); }); context('given the CSRF protection is enabled in the config', () => { beforeEach(() => Config.set('settings.session.csrf.enabled', true)); afterEach(() => Config.remove('settings.session.csrf.enabled')); describe('should set a session cookie in the response', () => { context('given no configuration option is provided', () => { beforeEach(() => removeSessionCookie(response)); it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.sameSite, SESSION_DEFAULT_SAME_SITE_ON_CSRF_ENABLED); }); }); context('given configuration options are provided', () => { beforeEach(() => { Config.set('settings.session.cookie.sameSite', 'strict'); removeSessionCookie(response); }); afterEach(() => Config.remove('settings.session.cookie.sameSite')); it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME); strictEqual(options.sameSite, 'strict'); }); }); }); describe('should set a CSRF cookie in the response', () => { context('given no configuration option is provided', () => { beforeEach(() => removeSessionCookie(response)); it('with the proper default name and value.', () => { const { value } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(value, ''); }); it('with the proper default "domain" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(options.domain, undefined); }); it('with the proper default "httpOnly" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(options.httpOnly, false); }); it('with the proper default "path" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(options.path, SESSION_DEFAULT_COOKIE_PATH); }); it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(options.sameSite, SESSION_DEFAULT_SAME_SITE_ON_CSRF_ENABLED); }); it('with the proper default "secure" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(options.secure, undefined); }); it('with the proper "maxAge" directive.', () => { const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(options.maxAge, 0); }); }); context('given configuration options are provided', () => { const csrfCookieName = SESSION_DEFAULT_CSRF_COOKIE_NAME + '2'; beforeEach(() => { Config.set('settings.session.csrf.cookie.name', csrfCookieName); Config.set('settings.session.cookie.domain', 'example.com'); Config.set('settings.session.cookie.httpOnly', true); Config.set('settings.session.cookie.path', '/foo'); Config.set('settings.session.cookie.sameSite', 'strict'); Config.set('settings.session.cookie.secure', 'true'); removeSessionCookie(response); }); afterEach(() => { Config.remove('settings.session.csrf.cookie.name'); Config.remove('settings.session.cookie.domain'); Config.remove('settings.session.cookie.httpOnly'); Config.remove('settings.session.cookie.path'); Config.remove('settings.session.cookie.sameSite'); Config.remove('settings.session.cookie.secure'); }); it('with the proper default name and value.', () => { const { value } = response.getCookie(csrfCookieName); strictEqual(value, ''); }); it('with the proper default "domain" directive.', () => { const { options } = response.getCookie(csrfCookieName); strictEqual(options.domain, 'example.com'); }); it('with the proper default "httpOnly" directive.', () => { const { options } = response.getCookie(csrfCookieName); strictEqual(options.httpOnly, false); }); it('with the proper default "path" directive.', () => { const { options } = response.getCookie(csrfCookieName); strictEqual(options.path, '/foo'); }); it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(csrfCookieName); strictEqual(options.sameSite, 'strict'); }); it('with the proper default "secure" directive.', () => { const { options } = response.getCookie(csrfCookieName); strictEqual(options.secure, true); }); it('with the proper "maxAge" directive.', () => { const { options } = response.getCookie(csrfCookieName); strictEqual(options.maxAge, 0); }); }); }); }); context('given the CSRF protection is disabled in the config', () => { beforeEach(() => removeSessionCookie(response)); it('should not set a CSRF cookie in the response.', () => { const { value } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME); strictEqual(value, undefined); }); }); context('given the "user" argument is true', () => { describe('should set a "user" cookie in the response', () => { context('given no configuration option is provided', () => { beforeEach(() => removeSessionCookie(response, true)); it('with the proper default name and value.', () => { const { value } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(value, ''); }); it('with the proper default "domain" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.domain, undefined); }); it('with the proper default "httpOnly" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.httpOnly, false); }); it('with the proper default "path" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.path, SESSION_DEFAULT_COOKIE_PATH); }); // Adding the sameSite directive is useless. We keep it for consistency. it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.sameSite, undefined); }); it('with the proper default "secure" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.secure, undefined); }); it('with the proper "maxAge" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.maxAge, 0); }); }); context('given configuration options are provided', () => { beforeEach(() => { Config.set('settings.session.cookie.domain', 'example.com'); Config.set('settings.session.cookie.httpOnly', true); Config.set('settings.session.cookie.path', '/foo'); Config.set('settings.session.cookie.sameSite', 'strict'); Config.set('settings.session.cookie.secure', 'true'); removeSessionCookie(response, true); }); afterEach(() => { Config.remove('settings.session.cookie.domain'); Config.remove('settings.session.cookie.httpOnly'); Config.remove('settings.session.cookie.path'); Config.remove('settings.session.cookie.sameSite'); Config.remove('settings.session.cookie.secure'); }); it('with the proper default name and value.', () => { const { value } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(value, ''); }); it('with the proper default "domain" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.domain, 'example.com'); }); it('with the proper default "httpOnly" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.httpOnly, false); }); it('with the proper default "path" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.path, '/foo'); }); // Adding the sameSite directive is useless. We keep it for consistency. it('with the proper default "sameSite" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.sameSite, 'strict'); }); it('with the proper default "secure" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.secure, true); }); it('with the proper "maxAge" directive.', () => { const { options } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(options.maxAge, 0); }); }); }); }); context('given the "user" argument is false or undefined', () => { beforeEach(() => removeSessionCookie(response)); it('should not set a "user" cookie in the response.', () => { const { value } = response.getCookie(SESSION_USER_COOKIE_NAME); strictEqual(value, undefined); }); }); });
Java
doskey comit =python c:\Windows\ComIt\runWithoutRequests.py $*
Java
<?php class Neostrada { const API_HOST = 'https://api.neostrada.nl/'; private $_key; private $_secret; public function __construct($key, $secret) { $this->_key = $key; $this->_secret = $secret; } public function domain($domain) { return new Neostrada_Domain($this, $domain); } public function save(Neostrada_Domain $domain) { $data = []; foreach ($domain->getRecords() as $record) { $data[$record->neostradaDnsId] = $record->toNeostradaFormat(); } $this->request($domain, 'dns', [ 'dnsdata' => serialize($data), ]); return $this; } public function request(Neostrada_Domain $domain, $action, array $rawParams = []) { $params = [ 'domain' => $domain->getName(), 'extension' => $domain->getExtension(), ] + $rawParams; $params['api_sig'] = $this->_calculateSignature($action, $params); $params['action'] = $action; $params['api_key'] = $this->_key; $url = self::API_HOST . '?' . http_build_query($params, '', '&'); $c = curl_init(); if ($c === false) { throw new \RuntimeException('Could not initialize cURL'); } curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_HEADER, 0); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $rawData = curl_exec($c); if ($rawData === false) { throw new \RuntimeException('Could not complete cURL request: ' . curl_error($c)); } curl_close($c); $oldUseErrors = libxml_use_internal_errors(true); $xml = simplexml_load_string($rawData); if ($xml === false) { $message = libxml_get_errors()[0]->message; libxml_use_internal_errors($oldUseErrors); throw new \RuntimeException('Invalid XML: ' . $message); } libxml_use_internal_errors($oldUseErrors); $this->_validateResponse($xml); return $xml; } private function _validateResponse(SimpleXMLElement $xml) { if ((string) $xml->code !== '200') { throw new \UnexpectedValueException('Request failed [' . $xml->code . ']: ' . $xml->description); } } private function _calculateSignature($action, array $params = []) { $signature = $this->_secret . $this->_key . 'action' . $action; foreach ($params as $key => $value) { $signature .= $key . $value; } return md5($signature); } }
Java
--- layout: post title: "Vim实用技巧进阶(第10章:复制和粘贴) - Practical.Vim.2nd.Edition" keywords: "vim,practical-vim,copy,paste,register,clipboard,实用技巧" description: "Practical.Vim.2nd.Edition 实用技巧进阶 第10章:复制和粘贴" tagline: "Tip 60~64" date: '2018-11-01 09:44:57 +0800' category: linux tags: vim practical-vim linux --- > {{ page.description }} # 第10章 复制和粘贴 > Copy and Paste ## Tip 60 匿名寄存器的使用 {: #tip60} > Delete, Yank, and Put with Vim's Unnamed Register *Vim* 的 删除, 拷贝, 放置(delete, yank, put) 命令在日常使用中被设计得简单易用. *匿名寄存器* 就是使用频率最高的寄存器 通常, 我们提到的 *剪切*, *拷贝* 和 *粘贴* 都是将文本放在剪贴板上. 而在 *Vim* 术语中, 我们不说 *剪贴板*, 而是 `寄存器` #### 互换字符 Keystrokes | Buffer Contents ---- | ---- {start} | Practica lvi<code class="cursor">m</code> `F␣` | Practica<code class="cursor">&nbsp;</code>lvim `x` | Practica<code class="cursor">l</code>vim `p` | Practical<code class="cursor">&nbsp;</code>vim {: .table-multi-text} - `F␣` - 往前搜索 *空格* 字符, 并定位到匹配的位置 - `x` - 删除光标处的 *空格* 字符, 并把删除的字符存入到 *匿名寄存器* - `p` - 粘贴刚刚删除掉的 *空格* 综合起来: `xp` 这2个命令就相当于把光标处的2个字符互换了位置 #### 互换行 Keystrokes | Buffer Contents ---- | ---- {start} | <code class="cursor">2</code>) line two <br>1) line one <br>3) line three `dd` | <code class="cursor">1</code>) line one <br>3) line three `p` | 1) line one <br><code class="cursor">2</code>) line two <br>3) line three {: .table-multi-text} - `dd` - 删除光标处的行内容, 并把内容存入到 *匿名寄存器* - `p` - *vim* 这次知道粘贴的内容是行(line-wise), 所以把 *匿名寄存器* 的内容粘贴到了当前行下面 (注意前面的 `xp` 是粘贴在字符后面) 所以 `ddp` 就相当于当前行和下一行的互换位置 #### 复制行 Keystrokes | Buffer Contents ---- | ---- {start} | 1) line one <br><code class="cursor">2</code>) line two `yyp` | 1) line one <br>2) line two <br><code class="cursor">2</code>) line two {: .table-multi-text} `yyp` 和 `ddp` 类似, 都是面向行的; `yyp` 进行了行的复制, 并放到了 *匿名寄存器*, 然后按行的形式粘贴出来, 达到复制行的效果 #### 拷贝撞车 前面 *Vim* 的 *删除*, *拷贝* 和 *放置* 操作看起来都是非常直观的; 那么且看下面的示例 <pre> collection = getCollection(); process(somethingInTheWay, target); </pre> 现在我们想将 *somethingInTheWay* 替换为 *collection*, 看看我们如何操作: Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `P` | collection = getCollection();<br> process(somethingInTheWa<code class="cursor">y</code>, target); {: .table-multi-text} 一套操作下来, 跟预想的不一样啊??? `yiw` 把 *collection* 存到了 *匿名寄存器* 里, 但是后面的 `diw` 删除 *somethingInTheWay* 的同时, 把 *匿名寄存器* 给覆盖了, 所以粘贴出来却不是我们想要的 为了解决这一问题, 我们需要了解 *vim* 的 *寄存器* 是如何工作的 ## Tip 61 寄存器一览 {: #tip61} > Grok Vim's Registers *Vim* 不是使用单个剪贴板进行所有剪切, 复制和粘贴(cut, copy, paste)操作, 而是提供多个寄存器. 当我们使用删除, 拉取和放置(delete, yank, put)命令时,我们可以指定我们想要与之交互的寄存器 **Vim 术语差别**: `cut,copy,paste` 和 `delete,yank,put` <pre> cut, copy, paste 术语是普片理解的, 并且这些操作可用于大多数桌面软件程序和操作系统. Vim 也提供这些功能, 但它使用不同的术语: delete, yank, put. Vim的 put 命令实际上与粘贴操作相同. 幸运的是, 这两个单词都以字母 <code class="highlighter-rouge">p</code> 开头, 因此可以认为就是粘贴命令了. Vim 的 yank 命令相当于复制操作. 从历史上看, <code class="highlighter-rouge">c</code>命令已经分配给了更改操作, 因此vi的作者被给出了另一个名称. <code class="highlighter-rouge">y</code> 键可用, 因此复制操作变为 yank 命令. Vim 的 delete 命令相当于标准剪切操作. 也就是说, 它将指定的文本复制到寄存器中, 然后将其从文档中删除. 如果想真正的删除文本而不存入寄存器呢? Vim 提供一个特殊的寄存器: 黑洞(black hole). 东西存进去就相当于丢弃了, 黑洞寄存器 寻址符号为:<code class="highlighter-rouge">_</code> 所以真正的删除为: <code class="highlighter-rouge">"_{motion}</code> </pre> 所以, <span class="red">除非特殊说明, *Vim* 里说的 剪切, 复制, 粘贴操作, 通常上是指 delete, yank, put 操作</span>; 而 *Vim* 里的 剪切 和 复制 是不能在其他程序里进行粘贴的; 后面会介绍特殊的寄存器与剪贴板进行交互, 就可以在其他程序里进行粘贴操作了. #### 寄存器访问 语法 `"{register}` - `"ayiw` - 复制当前的词, 并存到寄存器 *a* 里, 可使用 `"ap` 粘贴出来 - `"bdd` - 删除当前行, 并存到寄存器 *b* 里, 可使用 `"bp` 粘贴出来 - `:delete c` - Ex命令, 删除当前行并存到寄存器 c, 粘贴删除的行可以使用 `:put c` #### 匿名寄存器(\"\") 匿名寄存器 寻址符号为: `"` 例如要粘贴命令为: `""p` 可简写为 `p` `x`, `s`, `d{motion}`, `c{motion}`, `y{motion}` 等命令(大写亦可)都会把内容另存一份到 *匿名寄存器*; 如果想指定放到某个寄存器里, 可以指定前缀: `"{register}`, 不指定就是默认的 *匿名寄存器* *匿名寄存器* 的内容很容易被覆盖掉, 所以某些时候要注意一下 #### yank寄存器(\"0) 但使用 `y{motion}` 命令时, 会把文本存到 *匿名寄存器* 同时也会存一份到 yank寄存器, 寻址符号为: `0` 顾名思义, yank寄存器 仅只对 `y{motion}` 拉取操作生效, 而其他的 `x`, `s`, `c{motion}`, `d{motion}` 等命令不行 我们回到上个小节的: [拷贝撞车](#拷贝撞车) 的示例 Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `"0P` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} - `diw` - 删除当前词, 并覆盖掉 *匿名寄存器* 里的内容; 但是 yank寄存器 的是没变的 - `"0P` - 把 yank寄存器 的内容粘贴出来, 正好就是我们想要的 查看 *匿名寄存器* 和 *yank寄存器* 的内容: <pre> ➾ :reg "0 ❮ --- Registers --- "" somethingInTheWay "0 collection </pre> #### 字母寄存器(\"a-\"z) *Vim* 提供了一组以26个小写字母(a-z)命名的寄存器 - `"ad{motion}` - 删除(剪切)并存入寄存器 *a* - `"ay{motion}` - 拉取(拷贝)并存入寄存器 *a* - `"ap` - 粘贴(放置)寄存器 *a* 的内容 Keystrokes | Buffer Contents ---- | ---- `"ayiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `"aP` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 但我们有多个想要粘贴的文本时, 字母命名的寄存器就很有用了 #### 黑洞寄存器(\"_) *黑洞寄存器* 就是一个丢弃内容的地方, 删除内容不会影响到 *匿名寄存器* Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `"_diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `P` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 删除的时候指定了 黑洞寄存器, 所以不会覆盖 匿名寄存器 的内容, 粘贴的文本就是之前拷贝的 #### 剪贴板寄存器(\"+ 和 \"*) 目前为止, 前面提到的寄存器都是Vim的内部寄存器. 如果我们想在Vim里进行拷贝, 然后在外部其他程序里粘贴呢? 这个时候就需要用到系统剪贴板了 系统剪贴板寄存器 寻址符号为: `+` 如果我们从外部程序剪切或者拷贝了文本, 那么在 Vim 里可以使用 `"+p` 来进行粘贴 (插入模式下可使用 `<C-r>+`); 相反, 如果我们在 Vim 里使用 `"+` 对文本进行拉取(yank)或删除, 那么文本就会存到 *系统剪贴板* 里, 外部程序就可以直接粘贴使用 *X11* 窗口系统有第二种称为主剪贴板. 是鼠标最近的选择的文本, 我们可以使用鼠标中键来粘贴 首要剪贴板的寻址符号: `*` Keystrokes | Buffer Contents ---- | ---- `"+` | X11 剪贴板, 用于 剪切, 复制和粘贴 `"*` | X11 主剪贴板, 选中的文本被拷贝, 用鼠标中键粘贴 {: .table-multi-text} `Windows`{: .red} 和 `Mac OS X`{: .red} 系统没有 *主剪贴板*, 所以 `"+` 和 `"*` 都表示 *系统剪贴板* 是否支持 *X11剪贴板* 可以使用 `:version` 来查看版本信息 - *+xterm_clipboard* 表示支持 - *-xterm_clipboard* 表示不支持 #### 表达式寄存器(\"=) Vim 寄存器可以简单的被认为是容纳一块文本的容器. 而 表达式寄存器 是个例外, 寻址符号为 `=` 但我们在插入模式或命令模式按下 `<C-r>=`, 然后命令行就会有 `=` 字符提示, 输入一个数字表达式(如:*1+2+3*)并按回车即可计算出结果, 并把结果回填到之前的位置 (见 Tip 16) #### 更多的寄存器 我们可以使用 delete 和 yank 命令显式设置 字母, 匿名和yank 等寄存器来存放内容. 此外, Vim提供了一些寄存器, 其值是隐式设置的. 这里统称为 只读寄存器 Keystrokes | Buffer Contents ---- | ---- `"%` | 当前文件名 `"#` | 候选文件名(缓存列表的候选文件) `".` | 最后插入的文本 `":` | 最后执行的Ex命令 `"/` | 最后的搜索 pattern {: .table-multi-text} 严格的说 `"/` 不是只读的, 因为可以通过 `:let` 进行设置, 不过这里也放到表格里了 **手册**: - *:h quote_quote* 匿名寄存器 - *:h quote0* yank寄存器 - *:h quote_alpha* 字母(a-z)寄存器 - *:h quote_* 黑洞寄存器 - *:h quote+* 剪贴板寄存器 - *:h quotestar* 主剪贴板寄存器 - *:h quote=* 表达式寄存器 - *:h quote.* 最后插入文本寄存器 - *:h quote/* 最后搜索模式寄存器 - *:h registers* 查看所有寄存器列表 ## Tip 62 寄存器替换选中的文本 {: #tip62} > Replace a Visual Selection with a Register 在可视化模式下使用 `p` 命令替换文本的同时, Vim 会把被替换的文本存入匿名寄存器中 Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `ve` | collection = getCollection();<br> process(<code class="visual">somethingInTheWa<code class="cursor">y</code></code>, target); `p` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 这应该是最直观和简洁的方式了, 省去了一个删除的步骤 (多一个选中的步骤, 不过更加直观一点) 上面示例, 再尝试一下按 `u` 撤销替换, 然后 `gv` 重新选中之前被替换的文本, 然后按 `p` 会怎样? 答案是什么都没变! 因为按 `u` 之前, 匿名寄存器已经被覆盖为替换前选中的文本了 (Feature or Bug?) #### 2个词互换 Keystrokes | Buffer Contents ---- | ---- {start} | <code class="cursor">I</code> like chips and fish. `fc` | I like <code class="cursor">c</code>hips and fish. `de` | I like <code class="cursor">&nbsp;</code>and fish. `mm` | I like <code class="cursor">&nbsp;</code>and fish. `ww` | I like and <code class="cursor">f</code>ish. `ve` | I like chips and <code class="visual">fis<code class="cursor">h</code></code>. `p` | I like and chip<code class="cursor">s</code>. <code class="highlighter-rouge">`m</code> | I like <code class="cursor">&nbsp;</code>and chips. `P` | I like fis<code class="cursor">h</code> and chips. {: .table-multi-text} - `de` - 删除 *chips* (并存入匿名寄存器中) - `mm` - 在光标处做了一个 *m* 标记, 方便一会儿跳转回来的 - `ve` - 选中 *fish* - `p` - 把选中的 *fish* 替换为匿名寄存器中的 *chips* 文本 (被替换的 *fish* 存入匿名寄存器中) - <code class="highlighter-rouge">`m</code> - 跳转回之前标记 *m* 的位置 (Tip 54) - `P` - 把匿名寄存器中的 *fish* 粘贴到光标位置之前 (大写的p) **手册**: - *:h v_p* ## Tip 63 寄存器粘贴 {: #tip63} > Paste from a Register 常规模式下的 放置(put) 命令的行为不一样, 这个取决于插入的文本是 面向字符(character-wise) 或 面向行(line-wise) 的 粘贴行为差异: 2种模式 | `p` | `P` | 存入 匿名寄存器 ---- | ---- | ---- | ---- 面向字符 | 光标之后 | 光标之前 | `x` `diw` `das` `yw` 等 面向行 | 光标下一行 | 光标上一行 | `dd` `yy` `dap` 等 {: .table-multi-text} 寄存器列表中带有 <span class="red">^J</span> 字符的就是换行, 试了一下出现在末尾会被认定为: 面向行 <pre> :reg --- Registers --- "" #### 字符模式粘贴<span class="red">^J</span> "0 粘贴行为差异 "1 #### 字符模式粘贴<span class="red">^J</span> "2 粘贴<span class="red">^J</span> 粘贴 </pre> #### 面向字符区域粘贴 假如我们的 匿名寄存器 已经存在了 *collection* 文本, 那么对比一下什么时候用: `p` 和 `P` 呢? 对比一下: <code class="highlighter-rouge">process<code class="cursor">(</code>, target);</code> 和 <code class="highlighter-rouge">process(<code class="cursor">,</code> target);</code> 第一种情况明显是 `p`, 后面是 `P`; 实时上错了之后经常按 `puP` 和 `Pup` 来形成肌肉记忆后就好了 上面小节介绍了直接替换选中的文本的粘贴[Tip 60](#tip60), 这里介绍插入模式下如何粘贴: - `<C-r>"` - 插入 匿名寄存器 里的内容 - `<C-r>0` - 插入 yank寄存器 里的内容 Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `ciw<C-r>0<Esc>` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 使用 `ciw` 命令可以带来额外的好处: 可以使用 `.` 命令进行当前词的替换! #### 面向行区域粘贴 前面我们说了, 面向行的 `p` 和 `P` 命令会将 匿名寄存器 的内容放置到 下一行/上一行 这里值得注意的是, Vim 还提供 `gp` 和 `gP` 命令. 不同的点在于:光标最后停留的位置是在粘贴内容之前和之后 演示文本: ```html <table> <tr> <td>Symbol</td> <td>Name</td> </tr> </table> ``` ![gP命令粘贴效果](/assets/archives/20181103122707_vim-gP-command.png) 多行文本复制时, `gP` 命令非常好用; 虽然 `P` 和 `gP` 命令都能达到预期的复制文本效果, 不过最后光标停留的位置还是 `gP` 更实用一点(修改更方便点) `p` 和 `P` 命令都能在多行文本进行粘贴时处理得很好. 不过在处理 面向字符区域文本时, `<C-r>{register}` 会更加直观一点 **手册**: - *:h p* - *:h linewise-register* ## Tip 64 系统剪贴板交互 {: #tip64} > Interact with the System Clipboard 除了 Vim 的内置粘贴(put)命令, 我们有时可以使用系统粘贴命令. 但是, 在终端内运行 Vim 时, 使用此功能偶尔会产生意外结果. 我们可以在使用系统粘贴命令之前启用 'paste' 选项来避免这些问题. #### 准备 禁用插件启动 vim <pre> $ vim -u NONE -N </pre> 启用自动缩进功能 <pre> :set autoindent </pre> 然后把下面这段 ruby 代码拷贝到系统剪贴板里: <pre> [1,2,3,4,5,6,7,8,9,10].each do |n| if n%5==0 puts "fizz" else puts n end end </pre> #### 系统粘贴快捷键 *Mac* 系统默认的粘贴快捷键为 <kbd>Cmd</kbd>+<kbd>v</kbd> 而 *Linux* 和 *Windows* 就没那么舒适了, 其系统默认的粘贴快捷键为 <kbd>Ctrl</kbd>+<kbd>v</kbd> 这个和 *Vim* 里的快捷键正好冲突: - 常规模式下 - `<C-v>` 是启用可视化模式 (Tip 21) - 插入模式下 - `<C-v>` 是插入特殊字符 (Tip 17) 一些 *Linux* 终端提供了另一套粘贴的快捷键: <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd> 或 <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>v</kbd> 别忘了还有我们的剪贴板寄存器 `"+{regiester}` 和 `"*{register}` #### 插入模式下粘贴 当我们切换到 *插入模式* 下, 然后使用系统快捷键进行粘贴时, 我们会得到如下结果:(缩进可能太一样) <pre> [1,2,3,4,5,6,7,8,9,10].each do |n| if n%5==0 puts "fizz" else puts n end end </pre> 这个缩进并没有达到我们的预期. 当我们在插入模式下使用系统粘贴快捷键时, *Vim* 会以手动输入的字符来对待. 当 *autoindent* 选项开启后, 每次创建新行时, *Vim* 会保留同级别的缩进. 而剪贴板中每行前面的空格都被添加到了自动缩进的前面, 导致每一行都向右越走越远 这个时候, 我们可以手动开启 `:set paste` 选项, 告知 *Vim* 我们要使用系统的粘贴命令. 插入模式下, 在进行系统粘贴, 就会得到我们想要的结果了. 而当我们使用完之后, 可以关闭 `:set paste!` 选项, 回到之前的状态. 在插入模式下如何切换 *paste* 选项呢? 我们可以设置 *pastetoggle* 选项 `:set pastetoggle=<f5>` 这样就可以同时在 *插入模式* 和 *常规模式* 下快速切换了. 如果觉得实用, 可以加到 *~/.vimrc* 文件里 #### 用系统剪贴板寄存器粘贴 如果 *Vim* 支持 *+clipboard* 功能的话, 可以直接使用剪贴板寄存器, 而不用来回的切换 *paste* 选项了. [Tip 61 剪贴板寄存器](#%E5%89%AA%E8%B4%B4%E6%9D%BF%E5%AF%84%E5%AD%98%E5%99%A8-%E5%92%8C-) 使用 `"+p` 或 `"*p` 的系统剪贴板粘贴 (会忽略 *paste* 和 *autoindent* 选项) **手册**: - *:h 'paste'* - *:h 'pastetoggle'*
Java
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Department extends Model { protected $fillable =['name']; }
Java
# (c) Liviu Balan <liv_romania@yahoo.com> # http://www.liviubalan.com/ # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. LIV_TUT_META_URL='http://www.liviubalan.com/git-log-command'
Java
module Fae module BaseModelConcern extend ActiveSupport::Concern require 'csv' attr_accessor :filter included do include Fae::Trackable if Fae.track_changes include Fae::Sortable end def fae_display_field # override this method in your model end def fae_nested_parent # override this method in your model end def fae_tracker_parent # override this method in your model end def fae_nested_foreign_key return if fae_nested_parent.blank? "#{fae_nested_parent}_id" end def fae_form_manager_model_name return 'Fae::StaticPage' if self.class.name.constantize.superclass.name == 'Fae::StaticPage' self.class.name end def fae_form_manager_model_id self.id end module ClassMethods def for_fae_index order(order_method) end def order_method klass = name.constantize if klass.column_names.include? 'position' return :position elsif klass.column_names.include? 'name' return :name elsif klass.column_names.include? 'title' return :title else raise "No order_method found, please define for_fae_index as a #{name} class method to set a custom scope." end end def filter(params) # override this method in your model for_fae_index end def fae_search(query) all.to_a.keep_if { |i| i.fae_display_field.present? && i.fae_display_field.to_s.downcase.include?(query.downcase) } end def to_csv CSV.generate do |csv| csv << column_names all.each do |item| csv << item.attributes.values_at(*column_names) end end end def fae_translate(*attributes) attributes.each do |attribute| define_method attribute.to_s do self.send "#{attribute}_#{I18n.locale}" end define_singleton_method "find_by_#{attribute}" do |val| self.send("find_by_#{attribute}_#{I18n.locale}", val) end end end def has_fae_image(image_name_symbol) has_one image_name_symbol, -> { where(attached_as: image_name_symbol.to_s) }, as: :imageable, class_name: '::Fae::Image', dependent: :destroy accepts_nested_attributes_for image_name_symbol, allow_destroy: true end def has_fae_file(file_name_symbol) has_one file_name_symbol, -> { where(attached_as: file_name_symbol.to_s) }, as: :fileable, class_name: '::Fae::File', dependent: :destroy accepts_nested_attributes_for file_name_symbol, allow_destroy: true end end private def fae_bust_navigation_caches Fae::Role.all.each do |role| Rails.cache.delete("fae_navigation_#{role.id}") end end end end
Java
#pragma once #include <boost/uuid/random_generator.hpp> #include <boost/uuid/uuid_io.hpp> #include "util/util.h" #include "util/stl_ext.h" namespace collections { extern boost::optional<std::vector<std::string>> wrap_string(const char *csource, int charsPerLine); class tes_string : public reflection::class_meta_mixin_t<tes_string> { public: tes_string() { metaInfo._className = "JString"; metaInfo.comment = "various string utility methods"; } static object_base * wrap(tes_context& ctx, const char* source, SInt32 charsPerLine) { auto strings = wrap_string(source, charsPerLine); if (!strings) { return nullptr; } return &array::objectWithInitializer([&](array &obj) { for (auto& str : *strings) { obj.u_container().emplace_back(std::move(str)); } }, ctx); } REGISTERF2(wrap, "sourceText charactersPerLine=60", "Breaks source text onto set of lines of almost equal size.\n\ Returns JArray object containing lines.\n\ Accepts ASCII and UTF-8 encoded strings only"); static UInt32 decodeFormStringToFormId(const char* form_string) { return util::to_integral(decodeFormStringToForm(form_string)); } static FormId decodeFormStringToForm(const char* form_string) { return boost::get_optional_value_or(forms::from_string(form_string), FormId::Zero); } static skse::string_ref encodeFormToString(FormId id) { return skse::string_ref{ boost::get_optional_value_or(forms::to_string(id), "") }; } static skse::string_ref encodeFormIdToString(UInt32 id) { return encodeFormToString( util::to_enum<FormId>(id) ); } REGISTERF2_STATELESS(decodeFormStringToFormId, "formString", "FormId|Form <-> \"__formData|<pluginName>|<lowFormId>\"-string converisons"); REGISTERF2_STATELESS(decodeFormStringToForm, "formString", ""); REGISTERF2_STATELESS(encodeFormToString, "value", ""); REGISTERF2_STATELESS(encodeFormIdToString, "formId", ""); private: static boost::uuids::random_generator generateUUID_gen; static util::spinlock generateUUID_lock; public: static std::string generateUUID() { return boost::uuids::to_string( util::perform_while_locked(generateUUID_lock, [](){ return generateUUID_gen(); }) ); } REGISTERF2_STATELESS(generateUUID, "", "Generates random uuid-string like 2e80251a-ab22-4ad8-928c-2d1c9561270e"); }; boost::uuids::random_generator tes_string::generateUUID_gen; util::spinlock tes_string::generateUUID_lock; TES_META_INFO(tes_string); TEST(tes_string, wrap) { tes_context_standalone ctx; auto testData = json_deserializer::json_from_file( util::relative_to_dll_path("test_data/tes_string/string_wrap.json").generic_string().c_str() ); EXPECT_TRUE( json_is_array(testData.get()) ); auto testWrap = [&](const char *string, int linesCount, int charsPerLine) { auto obj = tes_string::wrap(ctx, string, charsPerLine); if (linesCount == -1) { EXPECT_NIL(obj); } else { EXPECT_NOT_NIL(obj); EXPECT_TRUE(obj->s_count() >= linesCount); } }; size_t index = 0; json_t *value = nullptr; json_array_foreach(testData.get(), index, value) { int charsPerLine = -1; json_t *jtext = nullptr; int linesCountMinimum = -1; json_error_t error; int succeed = json_unpack_ex(value, &error, 0, "{s:i, s:o, s:i}", "charsPerLine", &charsPerLine, "text", &jtext, "linesCountMinimum", &linesCountMinimum); EXPECT_TRUE(succeed == 0); testWrap(json_string_value(jtext), linesCountMinimum, charsPerLine); } } TEST(tes_string, generateUUID) { auto uidString = tes_string::generateUUID(); EXPECT_FALSE(uidString.empty()); auto uidString2 = tes_string::generateUUID(); EXPECT_NE(uidString, uidString2); } }
Java
package biz.golek.whattodofordinner.business.contract.presenters; import biz.golek.whattodofordinner.business.contract.entities.Dinner; /** * Created by Bartosz Gołek on 2016-02-10. */ public interface EditDinnerPresenter { void Show(Dinner dinner); }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Robber frog factsheet on ARKive - Eleutherodactylus simulans</title> <link rel="canonical" href="http://www.arkive.org/robber-frog/eleutherodactylus-simulans/" /> <link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> </head> <body> <!-- onload="window.print()">--> <div id="container"> <div id="header"><a href="/"><img src="/rimg/factsheet/header_left.png" alt="" border="0" /><img src="/rimg/factsheet/header_logo.png" alt="" border="0" /><img src="/rimg/factsheet/header_right.png" alt="" border="0" /></a></div> <div id="content"> <h1>Robber frog (<i>Eleutherodactylus simulans</i>)</h1> <img alt="" src="/media/17/17E2922C-0DA3-4615-B79D-A1E11785D359/Presentation.Large/Eleutherodactylus-simulans.jpg"/> <table cellspacing="0" cellpadding="0" id="factList"> <tbody> <tr class="kingdom"><th align="left">Kingdom</th><td align="left">Animalia</td></tr> <tr class="phylum"><th align="left">Phylum</th><td align="left">Chordata</td></tr> <tr class="class"><th align="left">Class</th><td align="left">Amphibia</td></tr> <tr class="order"><th align="left">Order</th><td align="left">Anura</td></tr> <tr class="family"><th align="left">Family</th><td align="left">Eleutherodactylidae</td></tr> <tr class="genus"><th align="left">Genus</th><td align="left"><em>Eleutherodactylus (1)</em></td></tr> </tbody> </table> <h2><img src="/rimg/factsheet/Status.png" class="heading" /></h2><p class="Status"><p>Classified as Endangered (EN) on the IUCN Red List (1).</p></p><h2><img src="/rimg/factsheet/Description.png" class="heading" /></h2><p class="Description"><p>Information on <em>Eleutherodactylus simulans </em>is currently being researched and written and will appear here shortly.</p></p><h2><img src="/rimg/factsheet/Authentication.png" class="heading" /></h2><p class="AuthenticatioModel"><p>This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact: <br/><a href="mailto:arkive@wildscreen.org.uk">arkive@wildscreen.org.uk</a></p></p><h2><img src="/rimg/factsheet/References.png" class="heading" /></h2> <ol id="references"> <li id="ref1"> <a id="reference_1" name="reference_1"></a> IUCN Red List (July, 2010) <br/><a href="http://www.iucnredlist.org" target="_blank">http://www.iucnredlist.org</a></li> </ol> </div> </div> </body> </html>
Java
\chapter{Constanten} \section{Globale Constanten} Dikwijls gebruik je bepaalde waarden doorheen je hele programma. Zo zou je, in een programma dat veel berekeningen met circels moet doen, vaak het getal pi nodig hebben. Dat getal kan je elke keer opnieuw berekenen, maar dat is niet zo'n goed idee omdat de uitkomst van je berekening steeds hetzelfde is. Je zou daarom een globale variabele pi kunnen declareren: \begin{code} int pi = 3.1415926; \end{code} Nu kan je overal de waarde van pi gebruiken in je berekeningen. Maar stel je voor dat je ergens vergist: \begin{code} int value = 1; // ... more code ... if(pi = value) { // do something } \end{code} Je wil in de bovenstaande code controleren of `value' gelijk is aan pi. Maar je schrijft een enkele in plaats van een dubbele =. Zo'n fout is snel gemaakt en valt op het eerste zicht niet zo op. Het gevolg is dat na de uitvoering van die code het getal pi niet meer gelijk is aan zijn oorspronkelijke waarde. Al je berekeningen zullen dus fout zijn! Om dit soort fouten te voorkomen voorzien de meeste programmeertalen in een mogelijkheid om een variabele `constant' te maken. Dat wil zeggen dat ze na hun declaratie niet meer aangepast mogen worden. Om dat duidelijk te maken bestaat de afspraak om die variabelen steeds met hoofdletters te schrijven. Hoe schrijf je zo'n variabele? In C++ doe je dat door voor het type \verb|const| toe te voegen. Esenthel geeft je daarnaast de mogelijkheid om dat af te korten tot \verb|C|. (Net zoals je \verb|this| kan afkorten tot \verb|T|). Je schrijft dus: \begin{code} C PI = 3.1415926; \end{code} Dit heeft twee voordelen: \begin{enumerate} \item Je kan de waarde van PI niet langer per vergissing aanpassen. \item Als je het getal PI in je code wil aanpassen, dan moet je dat maar op \'e\'en plaats doen. \textsl{(In het geval van PI is dat wel h\'e\'el onwaarschijnlijk, maar bij andere constanten kan dat dikwijls wel. Als je bijvoorbeeld een constante variabele ATTACK\_RANGE gebruikt, dan kan je misschien later beslissen dat die toch iets te groot is.)} \end{enumerate} \begin{note} Omdat PI een nummer is dat alle programmeurs vaak nodig hebben, bestaat er al een constante PI in Esenthel. Niet enkel dat, er zijn ook al varianten voorzien, zoals PI\_2 (de helft van PI) en PI2 (twee maal PI). \end{note} \begin{exercise} Maak een programma met de volgende constanten: playerColor, playerSize, enemyColor en enemySize. De player is een rechthoek en de enemies zijn cirkels. \textit{(Het is een erg abstract spel.)} Toon een speler en verschillende enemies op het scherm. \end{exercise} \section{Const Argumenten} Er bestaat nog een andere situatie waarin je constanten gebruikt. Bekijk even de volgende functie: \begin{code} float calculateDistance(Vec2 & pos1, Vec2 & pos2); \end{code} Je kan deze functie gebruiken om de afstand tussen twee posities te berekenen. Je leerde al in hoofdstuk \ref{chapter:references} dat we de argumenten van die functie by reference doorgeven om het programma sneller te maken. Dat heeft \'e\'en nadeel. Je zou in principe de waarden van pos1 en pos2 kunnen aanpassen in de functie. En dan zijn ook de originele waarden in je programma aangepast. De naam van de functie laat in dit geval vermoeden dat dat niet zal gebeuren. Maar je weet nooit zeker of de progammeur van die functie zich niet vergist heeft. Als er dus ergens iets fout gaat met de variabele \verb|pos1| in je programma, dan kan je niet anders dan ook de code van de functie \eeFunc{calculateDistance} nakijken. En misschien gebruikt die functie intern nog een andere functie die eveneens pass by reference argumenten heeft. Dat zou betekenen dat je echt alle onderliggende functies moet nakijken om uit te sluiten dat de fout daar zit. Zoiets is in grote projecten niet werkbaar. En daarom kunnen we ook een functie argument constant maken, net zoals een globale variabele. Je schrijft de functie dan zo: \begin{code} float calculateDistance(C Vec2 & pos1, C Vec2 & pos2); \end{code} De gevolgen zijn dat: \begin{enumerate} \item je tijdens het maken van de functie een foutmelding krijgt wanneer je toch zou proberen pos1 of pos2 aan te passen; \item de gebruiker van je functie zeker weet dat de waarde nooit aangepast kan zijn in de functie; \item je bijna zeker weet dat een functie waar de argumenten \textbf{niet} constant zijn, die argumenten zal aanpassen. \end{enumerate} Vanaf nu volg je dus de regel dat je alle functie argumenten als een const reference doorgeeft, tenzij het de bedoeling is dat de aangepaste waarde in het oorspronkelijke programma terecht komt. Wat is nu een goede reden om een argument aan te passen? Kijk even naar de Esenthel functie: \begin{code} void Clamp(Vec2 & value, C Vec2 & min, C Vec2 & max); \end{code} Het is de bedoeling dat deze functie de eerste waarde binnen het gevraagde minimum en maximum houdt. Je gebruikt de functie op deze manier: \begin{code} Vec2 pos = Ms.pos(); Clamp(pos, Vec2(-0.4,-0.4), Vec2(0.4,0.4)); pos.draw(RED); \end{code} Het tweede en derde argument zijn constant. De functie \eeFunc{Clamp} kan dus niet het minimum of maximum aanpassen. Maar \eeFunc{pos} willen we natuurlijk net wel aanpassen. Hier gebruik je dus geen const reference. \begin{exercise} \begin{itemize} \item Doorzoek de Engine code naar meer functies die geen const reference gebruiken. Probeer te verklaren waarom ze dat niet doen. \item Schrijf een functie `ClampToScreen' die een gegeven coordinaat aanpast wanneer het buiten het scherm zou vallen. Test de functie met een eenvoudig programma. Gebruik je een const reference of niet? \item Schrijf een functie met een string argument die die string op het scherm plaatst. Je maakt een versie met een const reference en een versie met een gewone reference. Test beide versies met bestaande strings en met string literals. Waarom werkt de niet-const versie enkel met strings en niet met literals? \end{itemize} \end{exercise}
Java
package main import ( "github.com/weynsee/go-phrase/cli" "log" "os" ) func main() { args := os.Args[1:] c := cli.NewCLI("1.0.0", args) exitStatus, err := c.Run() if err != nil { log.Println(err) } os.Exit(exitStatus) }
Java
version https://git-lfs.github.com/spec/v1 oid sha256:2e4cfe75feb71c39771595f8dea4f59e216650e0454f3f56a2a5b38a062b94cf size 1360
Java
require 'spec_helper' describe ZK::Threadpool do before do @threadpool = ZK::Threadpool.new end after do @threadpool.shutdown end describe :new do it %[should be running] do @threadpool.should be_running end it %[should use the default size] do @threadpool.size.should == ZK::Threadpool.default_size end end describe :defer do it %[should run the given block on a thread in the threadpool] do @th = nil @threadpool.defer { @th = Thread.current } wait_until(2) { @th } @th.should_not == Thread.current end it %[should barf if the argument is not callable] do bad_obj = flexmock(:not_callable) bad_obj.should_not respond_to(:call) lambda { @threadpool.defer(bad_obj) }.should raise_error(ArgumentError) end it %[should not barf if the threadpool is not running] do @threadpool.shutdown lambda { @threadpool.defer { "hai!" } }.should_not raise_error end end describe :on_exception do it %[should register a callback that will be called if an exception is raised on the threadpool] do @ary = [] @threadpool.on_exception { |exc| @ary << exc } @threadpool.defer { raise "ZOMG!" } wait_while(2) { @ary.empty? } @ary.length.should == 1 e = @ary.shift e.should be_kind_of(RuntimeError) e.message.should == 'ZOMG!' end end describe :shutdown do it %[should set running to false] do @threadpool.shutdown @threadpool.should_not be_running end end describe :start! do it %[should be able to start a threadpool that had previously been shutdown (reuse)] do @threadpool.shutdown @threadpool.start!.should be_true @threadpool.should be_running @rval = nil @threadpool.defer do @rval = true end wait_until(2) { @rval } @rval.should be_true end end describe :on_threadpool? do it %[should return true if we're currently executing on one of the threadpool threads] do @a = [] @threadpool.defer { @a << @threadpool.on_threadpool? } wait_while(2) { @a.empty? } @a.should_not be_empty @a.first.should be_true end end describe :pause_before_fork_in_parent do it %[should stop all running threads] do @threadpool.should be_running @threadpool.should be_alive @threadpool.pause_before_fork_in_parent @threadpool.should_not be_alive end it %[should raise InvalidStateError if already paused] do @threadpool.pause_before_fork_in_parent lambda { @threadpool.pause_before_fork_in_parent }.should raise_error(ZK::Exceptions::InvalidStateError) end end describe :resume_after_fork_in_parent do before do @threadpool.pause_before_fork_in_parent end it %[should start all threads running again] do @threadpool.resume_after_fork_in_parent @threadpool.should be_alive end it %[should raise InvalidStateError if not in paused state] do @threadpool.shutdown lambda { @threadpool.resume_after_fork_in_parent }.should raise_error(ZK::Exceptions::InvalidStateError) end it %[should run callbacks deferred while paused] do calls = [] num = 5 latch = Latch.new(num) num.times do |n| @threadpool.defer do calls << n latch.release end end @threadpool.resume_after_fork_in_parent latch.await(2) calls.should_not be_empty end end end
Java
<div class="col-xs-7"> <div class="box"> <div class="box-header"> <h3 class="box-title">Order Table</h3> <div class="box-tools"> <div class="input-group input-group-sm" style="width: 150px;"> <input type="search" class="light-table-filter form-control pull-right" data-table="order-table" placeholder="Search"> <div class="input-group-btn"> <button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button> </div> </div> </div> </div> <!-- /.box-header --> <div class="box-body table-responsive no-padding"> <table class="table table-hover order-table"> <thead> <tr> <th>Product</th> <th>Customer</th> <th>Date</th> <th>Status</th> <th>Price</th> <th>Phone</th> <th></th> </tr> </thead> <tbody> <?php foreach ($order as $item): if($item->status == 0){ ?> <tr> <td><?php echo $item->product; ?></td> <td><?php echo $item->username; ?></td> <td><?php echo $item->datereceive; ?></td> <td><?php if($item->status == 0){ echo "Watting access..."; } else{ echo "Ok"; } ?></td> <td><?php echo $item->price ?></td> <td><?php echo $item->phone ?></td> <td> <?php echo Html::anchor('admin/order/'.$item->id, 'Click to Complete', array('onclick' => "return confirm('Are you sure?')")); ?> </td> </tr> <?php } endforeach; ?> </tbody> </table> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <div class="col-xs-1"></div> <div class="col-xs-4"> <div class="box"> <div class="box-header"> <h3 class="box-title">Order Sussess</h3> </div> <!-- /.box-header --> <div class="box-body table-responsive no-padding"> <?php if ($order): ?> <table class="table table-hover"> <tbody><tr> <th>Product</th> <th>Date</th> <th>Status</th> <th>Customer</th> </tr> <?php foreach ($order as $item): if($item->status == 1){ ?> <tr> <td><?php echo $item->product; ?></td> <td><?php echo $item->datereceive; ?></td> <td><?php echo $item->username; ?></td> <td><?php if($item->status == 0){ echo "Watting access..."; } else{ echo "Ok"; } ?></td> </tr> <?php } ?> <?php endforeach; ?> </tbody> </table> <?php endif; ?> </div> <!-- /.box-body --> </div> </div>
Java
// // UIFont+PongMadness.h // Pong Madness // // Created by Ludovic Landry on 2/27/13. // Copyright (c) 2013 MirageTeam. All rights reserved. // #import <UIKit/UIKit.h> @interface UIFont (PongMadness) + (UIFont *)brothersBoldFontOfSize:(CGFloat)pointSize; + (void)printAvailableFonts; @end
Java
// // #ifndef _Rectangle_h #define _Rectangle_h // Includes #include <Engine/Core/Shape.h> #include <Engine/Core/Vector.h> //============================================================================== namespace ptc { class Ray; class Rectangle : public Shape { public: Rectangle(); Rectangle( const Vector& center, const Vector& right, const Vector& normal, float width, //< in right dir float height ); //< in cross( right, normal ) dir void setIsDoubleSided( bool new_value ); bool getIsDoubleSided() const; IntersectDescr intersect( const Ray& ray ) override; private: Vector center_; Vector right_; Vector up_; Vector normal_; float width_; float height_; bool is_double_sided_; }; } // namespace ptc #endif // Include guard
Java
package multiwallet import ( "errors" "strings" "time" eth "github.com/OpenBazaar/go-ethwallet/wallet" "github.com/OpenBazaar/multiwallet/bitcoin" "github.com/OpenBazaar/multiwallet/bitcoincash" "github.com/OpenBazaar/multiwallet/client/blockbook" "github.com/OpenBazaar/multiwallet/config" "github.com/OpenBazaar/multiwallet/litecoin" "github.com/OpenBazaar/multiwallet/service" "github.com/OpenBazaar/multiwallet/zcash" "github.com/OpenBazaar/wallet-interface" "github.com/btcsuite/btcd/chaincfg" "github.com/op/go-logging" "github.com/tyler-smith/go-bip39" ) var log = logging.MustGetLogger("multiwallet") var UnsuppertedCoinError = errors.New("multiwallet does not contain an implementation for the given coin") type MultiWallet map[wallet.CoinType]wallet.Wallet func NewMultiWallet(cfg *config.Config) (MultiWallet, error) { log.SetBackend(logging.AddModuleLevel(cfg.Logger)) service.Log = log blockbook.Log = log if cfg.Mnemonic == "" { ent, err := bip39.NewEntropy(128) if err != nil { return nil, err } mnemonic, err := bip39.NewMnemonic(ent) if err != nil { return nil, err } cfg.Mnemonic = mnemonic cfg.CreationDate = time.Now() } multiwallet := make(MultiWallet) var err error for _, coin := range cfg.Coins { var w wallet.Wallet switch coin.CoinType { case wallet.Bitcoin: w, err = bitcoin.NewBitcoinWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Bitcoin] = w } else { multiwallet[wallet.TestnetBitcoin] = w } case wallet.BitcoinCash: w, err = bitcoincash.NewBitcoinCashWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.BitcoinCash] = w } else { multiwallet[wallet.TestnetBitcoinCash] = w } case wallet.Zcash: w, err = zcash.NewZCashWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Zcash] = w } else { multiwallet[wallet.TestnetZcash] = w } case wallet.Litecoin: w, err = litecoin.NewLitecoinWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Litecoin] = w } else { multiwallet[wallet.TestnetLitecoin] = w } case wallet.Ethereum: w, err = eth.NewEthereumWallet(coin, cfg.Params, cfg.Mnemonic, cfg.Proxy) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Ethereum] = w } else { multiwallet[wallet.TestnetEthereum] = w } } } return multiwallet, nil } func (w *MultiWallet) Start() { for _, wallet := range *w { wallet.Start() } } func (w *MultiWallet) Close() { for _, wallet := range *w { wallet.Close() } } func (w *MultiWallet) WalletForCurrencyCode(currencyCode string) (wallet.Wallet, error) { for _, wl := range *w { if strings.EqualFold(wl.CurrencyCode(), currencyCode) || strings.EqualFold(wl.CurrencyCode(), "T"+currencyCode) { return wl, nil } } return nil, UnsuppertedCoinError }
Java
// Copyright (c) 2012 Pieter Wuille // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "hash.h" #include "serialize.h" #include "streams.h" int CAddrInfo::GetTriedBucket(const uint256& nKey) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; } int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const { std::vector<unsigned char> vchSourceGroupKey = src.GetGroup(); uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_NEW_BUCKET_COUNT; } int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash(); return hash1 % ADDRMAN_BUCKET_SIZE; } bool CAddrInfo::IsTerrible(int64_t nNow) const { if (nLastTry && nLastTry >= nNow - 60) // never remove things tried in the last minute return false; if (nTime > nNow + 10 * 60) // came in a flying DeLorean return true; if (nTime == 0 || nNow - nTime > ADDRMAN_HORIZON_DAYS * 24 * 60 * 60) // not seen in recent history return true; if (nLastSuccess == 0 && nAttempts >= ADDRMAN_RETRIES) // tried N times and never a success return true; if (nNow - nLastSuccess > ADDRMAN_MIN_FAIL_DAYS * 24 * 60 * 60 && nAttempts >= ADDRMAN_MAX_FAILURES) // N successive failures in the last week return true; return false; } double CAddrInfo::GetChance(int64_t nNow) const { double fChance = 1.0; int64_t nSinceLastSeen = nNow - nTime; int64_t nSinceLastTry = nNow - nLastTry; if (nSinceLastSeen < 0) nSinceLastSeen = 0; if (nSinceLastTry < 0) nSinceLastTry = 0; // deprioritize very recent attempts away if (nSinceLastTry < 60 * 10) fChance *= 0.01; // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages. fChance *= pow(0.66, std::min(nAttempts, 8)); return fChance; } CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId) { std::map<CNetAddr, int>::iterator it = mapAddr.find(addr); if (it == mapAddr.end()) return NULL; if (pnId) *pnId = (*it).second; std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second); if (it2 != mapInfo.end()) return &(*it2).second; return NULL; } CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId) { int nId = nIdCount++; mapInfo[nId] = CAddrInfo(addr, addrSource); mapAddr[addr] = nId; mapInfo[nId].nRandomPos = vRandom.size(); vRandom.push_back(nId); if (pnId) *pnId = nId; return &mapInfo[nId]; } void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) { if (nRndPos1 == nRndPos2) return; assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size()); int nId1 = vRandom[nRndPos1]; int nId2 = vRandom[nRndPos2]; assert(mapInfo.count(nId1) == 1); assert(mapInfo.count(nId2) == 1); mapInfo[nId1].nRandomPos = nRndPos2; mapInfo[nId2].nRandomPos = nRndPos1; vRandom[nRndPos1] = nId2; vRandom[nRndPos2] = nId1; } void CAddrMan::Delete(int nId) { assert(mapInfo.count(nId) != 0); CAddrInfo& info = mapInfo[nId]; assert(!info.fInTried); assert(info.nRefCount == 0); SwapRandom(info.nRandomPos, vRandom.size() - 1); vRandom.pop_back(); mapAddr.erase(info); mapInfo.erase(nId); nNew--; } void CAddrMan::ClearNew(int nUBucket, int nUBucketPos) { // if there is an entry in the specified bucket, delete it. if (vvNew[nUBucket][nUBucketPos] != -1) { int nIdDelete = vvNew[nUBucket][nUBucketPos]; CAddrInfo& infoDelete = mapInfo[nIdDelete]; assert(infoDelete.nRefCount > 0); infoDelete.nRefCount--; vvNew[nUBucket][nUBucketPos] = -1; if (infoDelete.nRefCount == 0) { Delete(nIdDelete); } } } void CAddrMan::MakeTried(CAddrInfo& info, int nId) { // remove the entry from all new buckets for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) { int pos = info.GetBucketPosition(nKey, true, bucket); if (vvNew[bucket][pos] == nId) { vvNew[bucket][pos] = -1; info.nRefCount--; } } nNew--; assert(info.nRefCount == 0); // which tried bucket to move the entry to int nKBucket = info.GetTriedBucket(nKey); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); // first make space to add it (the existing tried entry there is moved to new, deleting whatever is there). if (vvTried[nKBucket][nKBucketPos] != -1) { // find an item to evict int nIdEvict = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nIdEvict) == 1); CAddrInfo& infoOld = mapInfo[nIdEvict]; // Remove the to-be-evicted item from the tried set. infoOld.fInTried = false; vvTried[nKBucket][nKBucketPos] = -1; nTried--; // find which new bucket it belongs to int nUBucket = infoOld.GetNewBucket(nKey); int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket); ClearNew(nUBucket, nUBucketPos); assert(vvNew[nUBucket][nUBucketPos] == -1); // Enter it into the new set again. infoOld.nRefCount = 1; vvNew[nUBucket][nUBucketPos] = nIdEvict; nNew++; } assert(vvTried[nKBucket][nKBucketPos] == -1); vvTried[nKBucket][nKBucketPos] = nId; nTried++; info.fInTried = true; } void CAddrMan::Good_(const CService& addr, int64_t nTime) { int nId; CAddrInfo* pinfo = Find(addr, &nId); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastSuccess = nTime; info.nLastTry = nTime; info.nAttempts = 0; // nTime is not updated here, to avoid leaking information about // currently-connected peers. // if it is already in the tried set, don't do anything else if (info.fInTried) return; // find a bucket it is in now int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucket = -1; for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT; int nBpos = info.GetBucketPosition(nKey, true, nB); if (vvNew[nB][nBpos] == nId) { nUBucket = nB; break; } } // if no bucket is found, something bad happened; // TODO: maybe re-add the node, but for now, just bail out if (nUBucket == -1) return; LogPrint("addrman", "Moving %s to tried\n", addr.ToString()); // move nId to the tried tables MakeTried(info, nId); } bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty) { if (!addr.IsRoutable()) return false; bool fNew = false; int nId; CAddrInfo* pinfo = Find(addr, &nId); if (pinfo) { // periodically update nTime bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60); int64_t nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty)) pinfo->nTime = std::max((int64_t)0, addr.nTime - nTimePenalty); // add services pinfo->nServices |= addr.nServices; // do not update if no new information is present if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime)) return false; // do not update if the entry was already in the "tried" table if (pinfo->fInTried) return false; // do not update if the max reference count is reached if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it int nFactor = 1; for (int n = 0; n < pinfo->nRefCount; n++) nFactor *= 2; if (nFactor > 1 && (RandomInt(nFactor) != 0)) return false; } else { pinfo = Create(addr, source, &nId); pinfo->nTime = std::max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty); nNew++; fNew = true; } int nUBucket = pinfo->GetNewBucket(nKey, source); int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket); if (vvNew[nUBucket][nUBucketPos] != nId) { bool fInsert = vvNew[nUBucket][nUBucketPos] == -1; if (!fInsert) { CAddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]]; if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) { // Overwrite the existing new table entry. fInsert = true; } } if (fInsert) { ClearNew(nUBucket, nUBucketPos); pinfo->nRefCount++; vvNew[nUBucket][nUBucketPos] = nId; } else { if (pinfo->nRefCount == 0) { Delete(nId); } } } return fNew; } void CAddrMan::Attempt_(const CService& addr, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastTry = nTime; info.nAttempts++; } CAddrInfo CAddrMan::Select_(bool newOnly) { if (size() == 0) return CAddrInfo(); if (newOnly && nNew == 0) return CAddrInfo(); // Use a 50% chance for choosing between tried and new table entries. if (!newOnly && (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { // use a tried node double fChanceFactor = 1.0; while (1) { int nKBucket = RandomInt(ADDRMAN_TRIED_BUCKET_COUNT); int nKBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvTried[nKBucket][nKBucketPos] == -1) { nKBucket = (nKBucket + insecure_rand()) % ADDRMAN_TRIED_BUCKET_COUNT; nKBucketPos = (nKBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } else { // use a new node double fChanceFactor = 1.0; while (1) { int nUBucket = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvNew[nUBucket][nUBucketPos] == -1) { nUBucket = (nUBucket + insecure_rand()) % ADDRMAN_NEW_BUCKET_COUNT; nUBucketPos = (nUBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvNew[nUBucket][nUBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } } #ifdef DEBUG_ADDRMAN int CAddrMan::Check_() { std::set<int> setTried; std::map<int, int> mapNew; if (vRandom.size() != nTried + nNew) return -7; for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++) { int n = (*it).first; CAddrInfo& info = (*it).second; if (info.fInTried) { if (!info.nLastSuccess) return -1; if (info.nRefCount) return -2; setTried.insert(n); } else { if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3; if (!info.nRefCount) return -4; mapNew[n] = info.nRefCount; } if (mapAddr[info] != n) return -5; if (info.nRandomPos < 0 || info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n) return -14; if (info.nLastTry < 0) return -6; if (info.nLastSuccess < 0) return -8; } if (setTried.size() != nTried) return -9; if (mapNew.size() != nNew) return -10; for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvTried[n][i] != -1) { if (!setTried.count(vvTried[n][i])) return -11; if (mapInfo[vvTried[n][i]].GetTriedBucket(nKey) != n) return -17; if (mapInfo[vvTried[n][i]].GetBucketPosition(nKey, false, n) != i) return -18; setTried.erase(vvTried[n][i]); } } } for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[n][i] != -1) { if (!mapNew.count(vvNew[n][i])) return -12; if (mapInfo[vvNew[n][i]].GetBucketPosition(nKey, true, n) != i) return -19; if (--mapNew[vvNew[n][i]] == 0) mapNew.erase(vvNew[n][i]); } } } if (setTried.size()) return -13; if (mapNew.size()) return -15; if (nKey.IsNull()) return -16; return 0; } #endif void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr) { unsigned int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.size() / 100; if (nNodes > ADDRMAN_GETADDR_MAX) nNodes = ADDRMAN_GETADDR_MAX; // gather a list of random nodes, skipping those of low quality for (unsigned int n = 0; n < vRandom.size(); n++) { if (vAddr.size() >= nNodes) break; int nRndPos = RandomInt(vRandom.size() - n) + n; SwapRandom(n, nRndPos); assert(mapInfo.count(vRandom[n]) == 1); const CAddrInfo& ai = mapInfo[vRandom[n]]; if (!ai.IsTerrible()) vAddr.push_back(ai); } } void CAddrMan::Connected_(const CService& addr, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info int64_t nUpdateInterval = 20 * 60; if (nTime - info.nTime > nUpdateInterval) info.nTime = nTime; } int CAddrMan::RandomInt(int nMax){ return GetRandInt(nMax); }
Java
import asyncio import discord import datetime import pytz from discord.ext import commands from Cogs import FuzzySearch from Cogs import Settings from Cogs import DisplayName from Cogs import Message from Cogs import Nullify class Time: # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings): self.bot = bot self.settings = settings @commands.command(pass_context=True) async def settz(self, ctx, *, tz : str = None): """Sets your TimeZone - Overrides your UTC offset - and accounts for DST.""" usage = 'Usage: `{}settz [Region/City]`\nYou can get a list of available TimeZones with `{}listtz`'.format(ctx.prefix, ctx.prefix) if not tz: self.settings.setGlobalUserStat(ctx.author, "TimeZone", None) await ctx.channel.send("*{}*, your TimeZone has been removed!".format(DisplayName.name(ctx.author))) return # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match msg = "I couldn't find that TimeZone!\n\nMaybe you meant one of the following?\n```" for tz in tz_list: msg += tz['Item'] + "\n" msg += '```' await ctx.channel.send(msg) return # We got a time zone self.settings.setGlobalUserStat(ctx.author, "TimeZone", tz_list[0]['Item']) await ctx.channel.send("TimeZone set to *{}!*".format(tz_list[0]['Item'])) @commands.command(pass_context=True) async def listtz(self, ctx, *, tz_search = None): """List all the supported TimeZones in PM.""" if not tz_search: msg = "__Available TimeZones:__\n\n" for tz in pytz.all_timezones: msg += tz + "\n" else: tz_list = FuzzySearch.search(tz_search, pytz.all_timezones) msg = "__Top 3 TimeZone Matches:__\n\n" for tz in tz_list: msg += tz['Item'] + "\n" await Message.say(self.bot, msg, ctx.channel, ctx.author, 1) @commands.command(pass_context=True) async def tz(self, ctx, *, member = None): """See a member's TimeZone.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one timezone = self.settings.getGlobalUserStat(member, "TimeZone") if timezone == None: msg = '*{}* hasn\'t set their TimeZone yet - they can do so with the `{}settz [Region/City]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return msg = '*{}\'s* TimeZone is *{}*'.format(DisplayName.name(member), timezone) await ctx.channel.send(msg) @commands.command(pass_context=True) async def setoffset(self, ctx, *, offset : str = None): """Set your UTC offset.""" if offset == None: self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", None) msg = '*{}*, your UTC offset has been removed!'.format(DisplayName.name(ctx.message.author)) await ctx.channel.send(msg) return offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return off = "{}:{}".format(hours, minutes) self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", off) msg = '*{}*, your UTC offset has been set to *{}!*'.format(DisplayName.name(ctx.message.author), off) await ctx.channel.send(msg) @commands.command(pass_context=True) async def offset(self, ctx, *, member = None): """See a member's UTC offset.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their offset yet - they can do so with the `{}setoffset [+-offset]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return msg = 'UTC' # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) elif hours < 0: # Apply negative offset msg += '{}'.format(offset) msg = '*{}\'s* offset is *{}*'.format(DisplayName.name(member), msg) await ctx.channel.send(msg) @commands.command(pass_context=True) async def time(self, ctx, *, offset : str = None): """Get UTC time +- an offset.""" timezone = None if offset == None: member = ctx.message.author else: # Try to get a user first member = DisplayName.memberForName(offset, ctx.message.guild) if member: # We got one # Check for timezone first offset = self.settings.getGlobalUserStat(member, "TimeZone") if offset == None: offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their TimeZone or offset yet - they can do so with the `{}setoffset [+-offset]` or `{}settz [Region/City]` command.\nThe current UTC time is *{}*.'.format(DisplayName.name(member), ctx.prefix, ctx.prefix, datetime.datetime.utcnow().strftime("%I:%M %p")) await ctx.channel.send(msg) return # At this point - we need to determine if we have an offset - or possibly a timezone passed t = self.getTimeFromTZ(offset) if t == None: # We did not get an offset t = self.getTimeFromOffset(offset) if t == None: await ctx.channel.send("I couldn't find that TimeZone or offset!") return if member: msg = '{}; where *{}* is, it\'s currently *{}*'.format(t["zone"], DisplayName.name(member), t["time"]) else: msg = '{} is currently *{}*'.format(t["zone"], t["time"]) # Say message await ctx.channel.send(msg) def getTimeFromOffset(self, offset): offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: return None # await ctx.channel.send('Offset has to be in +-H:M!') # return msg = 'UTC' # Get the time t = datetime.datetime.utcnow() # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) td = datetime.timedelta(hours=hours, minutes=minutes) newTime = t + td elif hours < 0: # Apply negative offset msg += '{}'.format(offset) td = datetime.timedelta(hours=(-1*hours), minutes=(-1*minutes)) newTime = t - td else: # No offset newTime = t return { "zone" : msg, "time" : newTime.strftime("%I:%M %p") } def getTimeFromTZ(self, tz): # Assume sanitized zones - as they're pulled from pytz # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match return None zone = pytz.timezone(tz_list[0]['Item']) zone_now = datetime.datetime.now(zone) return { "zone" : tz_list[0]['Item'], "time" : zone_now.strftime("%I:%M %p") }
Java
<!DOCTYPE html> <?xml version="1.0" encoding="UTF-8"?> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Earth Negotiations Bulletin: COP17</title> <link href="../assets/style/bulletin.css" rel="stylesheet" /> </head> <body> <h1>Earth Negotiations Bulletin: COP17</h1> <p><b>Durban Climate Change Conference - COP17/CMP7</b></p> <p>28-Nov-11 &mdash; <a href="http://www.iisd.ca/vol12/enb12523e.html">original report</a></p> <div id="section_enb12523e_1"> <h2>A BRIEF HISTORY OF THE UNFCCC AND KYOTO PROTOCOL</h2> <small>history</small> <p>The international political response to climate change began with the adoption of the United Nations Framework Convention on Climate Change (UNFCCC) in 1992.</p> <p>The UNFCCC sets out a framework for action aimed at stabilizing atmospheric concentrations of greenhouse gases to avoid dangerous anthropogenic interference with the climate system.</p> <p>The Convention, which entered into force on 21 March 1994, now has 195 parties.</p> <p>In December 1997, delegates to the third session of the Conference of the Parties (COP) in Kyoto, Japan, agreed to a Protocol to the UNFCCC that commits industrialized countries and countries in transition to a market economy to achieve emission reduction targets.</p> <p>These countries, known as Annex I parties under the UNFCCC, agreed to reduce their overall emissions of six greenhouse gases by an average of 5.2% below 1990 levels between 2008-2012 (the first commitment period), with specific targets varying from country to country.</p> <p>The Kyoto Protocol entered into force on 16 February 2005 and now has 193 parties.</p> <p>At the end of 2005, the first steps were taken to consider long-term issues.</p> <p>Convening in Montreal, Canada, the first session of the COP/MOP 1 decided to establish the AWG-KP on the basis of Protocol Article 3.9, which mandates consideration of Annex I parties further commitments at least seven years before the end of the first commitment period.</p> <p>COP 11 agreed to consider long-term cooperation under the Convention through a series of four workshops known as the Convention Dialogue, which continued until COP 13.</p> </div> <div id="section_enb12523e_2"> <h2>BALI ROADMAP:</h2> <p>COP 13 and COP/MOP 3 took place in December 2007 in Bali, Indonesia.</p> <p>Negotiations resulted in the adoption of the Bali Action Plan.</p> <p>Parties established the AWG-LCA with a mandate to focus on key elements of long-term cooperation identified during the Convention Dialogue: mitigation, adaptation, finance, technology and a shared vision for long-term cooperative action.</p> <p>The Bali conference also resulted in agreement on the Bali Roadmap.</p> <p>Based on two negotiating tracks under the Convention and the Protocol, the Roadmap set a deadline for concluding the negotiations in Copenhagen in December 2009.</p> </div> <div id="section_enb12523e_3"> <h2>COPENHAGEN CLIMATE CHANGE CONFERENCE:</h2> <p>The UN Climate Change Conference in Copenhagen, Denmark, took place in December 2009.</p> <p>The event was marked by disputes over transparency and process.</p> <p>During the high-level segment, informal negotiations took place in a group consisting of major economies and representatives of regional and other negotiating groups.</p> <p>Late in the evening of 18 December, these talks resulted in a political agreement: the Copenhagen Accord, which was then presented to the COP plenary for adoption.</p> <p>Over the next 13 hours, delegates debated the Accord.</p> <p>Many supported adopting it as a step towards securing a better future agreement.</p> <p>However, some developing countries opposed the Accord, which they felt had been reached through an untransparent and undemocratic negotiating process.</p> <p>Ultimately, the COP agreed to take note of the Copenhagen Accord.</p> <p>It established a process for parties to indicate their support for the Accord and, during 2010, over 140 countries did so.</p> <p>More than 80 countries also provided information on their national emission reduction targets and other mitigation actions.</p> <p>On the last day of the Copenhagen Climate Change Conference, parties also agreed to extend the mandates of the AWG-LCA and AWG-KP, requesting them to present their respective outcomes to COP 16 and COP/MOP 6.</p> </div> <div id="section_enb12523e_4"> <h2>CANCUN CLIMATE CHANGE CONFERENCE:</h2> <p>Following four preparatory meetings in 2010, the UN Climate Change Conference in Cancun, Mexico, took place from 29 November to 11 December 2010.</p> <p>By the end of the conference, parties had finalized the Cancun Agreements, which include decisions under both negotiating tracks.</p> <p>Under the Convention track, Decision 1/CP.16 recognized the need for deep cuts in global emissions in order to limit global average temperature rise to 2°C.</p> <p>Parties also agreed to consider strengthening the global long-term goal during a review by 2015, including in relation to a proposed 1.5°C target.</p> <p>They took note of emission reduction targets and nationally appropriate mitigation actions (NAMAs) communicated by developed and developing countries respectively (FCCC/SB/2011/INF.1/Rev.1 and FCCC/AWGLCA/2011/INF.1, both issued after Cancun).</p> <p>Decision 1/CP.16 also addressed other aspects of mitigation, such as measuring, reporting and verification (MRV); reducing emissions from deforestation and forest degradation in developing countries; and the role of conservation, sustainable management of forests and enhancement of forest carbon stocks in developing countries (REDD+).</p> <p>Parties also agreed to establish several new institutions and processes, such as the Cancun Adaptation Framework and the Adaptation Committee, as well as the Technology Mechanism, which includes the Technology Executive Committee (TEC) and the Climate Technology Centre and Network (CTCN).</p> <p>On finance, Decision 1/CP.16 created the Green Climate Fund (GCF), which was designated to be the new operating entity of the Convention s financial mechanism and is to be governed by a board of 24 members.</p> <p>Parties agreed to set up a Transitional Committee tasked with the Fund s detailed design, and established a Standing Committee to assist the COP with respect to the financial mechanism.</p> <p>They also recognized the commitment by developed countries to provide US$30 billion of fast-start finance in 2010-2012, and to jointly mobilize US$100 billion per year by 2020.</p> <p>Under the Protocol track, Decision 1/CMP.6 included agreement to complete the work of the AWG-KP and have the results adopted by the COP/MOP as soon as possible and in time to ensure there will be no gap between the first and second commitment periods.</p> <p>The COP/MOP urged Annex I parties to raise the level of ambition of their emission reduction targets with a view to achieving aggregate emission reductions consistent with the range identified in the Fourth Assessment Report of the Intergovernmental Panel on Climate Change (IPCC).</p> <p>Parties also adopted Decision 2/CMP.6 on land use, land-use change and forestry (LULUCF).</p> <p>The mandates of the two AWGs were extended to the UN Climate Change Conference in Durban.</p> </div> <div id="section_enb12523e_5"> <h2>UN CLIMATE CHANGE TALKS IN 2011:</h2> <p>In 2011, three official UNFCCC negotiating sessions were held in the lead-up to Durban.</p> <p>In April, the two AWGs convened in Bangkok, Thailand.</p> <p>The AWG-LCA engaged in procedural discussions on its agenda, finally agreeing on an agenda for its subsequent work.</p> <p>Under the AWG-KP, parties focused on key policy issues hindering progress.</p> <p>Two months later, negotiators gathered in Bonn, Germany, for sessions of the SBI, SBSTA, AWG-LCA and AWG-KP.</p> <p>SBSTA agreed to a new agenda item on impacts of climate change on water and integrated water resources management under the Nairobi Work Programme.</p> <p>This item will be taken up in Durban.</p> <p>No agreement was reached on other proposed new items, such as blue carbon and rights of nature and the integrity of ecosystems, and a work programme on agriculture.</p> <p>Under the SBI, work was launched on national adaptation plans, and loss and damage, as mandated by the Cancun Agreements.</p> <p>The agenda item relating to MRV remained in abeyance.</p> <p>Proposed new items related to the impacts of the implementation of response measures also featured prominently.</p> <p>The focus of the AWG-KP in Bonn was on outstanding political issues and conditionalities set by various Annex I countries for taking on new commitments during a second commitment period.</p> <p>Despite initial opposition from developing countries, parties also undertook technical work, including on LULUCF, the flexibility mechanisms and methodological issues.</p> <p>Under the AWG-LCA, substantive work began based on Decision 1/CP.16.</p> <p>Parties worked on adaptation, finance, technology, capacity building, shared vision, review of the global long-term goal, legal options, and diverse issues related to mitigation.</p> <p>Parties agreed that notes prepared by the facilitators of the AWG-LCA informal groups be carried forward to the third part of AWG-LCA 14 in Panama.</p> <p>While progress was reported on some issues, many felt that the outcomes were relatively modest.</p> <p>The AWG-LCA and AWG-KP reconvened from 1-7 October 2011 in Panama City, Panama.</p> <p>The AWG-KP concentrated on outstanding issues and further clarifying options concerning mitigation targets, the possible nature and content of rules for a second commitment period, and the role of a possible second commitment period within a balanced outcome in Durban.</p> <p>Under the AWG-LCA, negotiators engaged in extended procedural discussions based on Decision 1/CP.16 and the Bali Action Plan.</p> <p>Parties worked on adaptation, finance, technology, capacity building, shared vision, review of the global long-term goal, legal options, and diverse issues related to mitigation.</p> <p>The outcome for most of the informal group discussions was some form of text forwarded to Durban as a basis for further discussions.</p> </div> <div id="section_enb12523e_6"> <h2>INTERSESSIONAL HIGHLIGHTS</h2> <small>agenda</small> <p>Since the negotiations in Panama, a number of meetings have been held that are relevant to Durban.</p> <p>The 4th meeting of the Transitional Committee for the design of the GCF was held from 16-18 October 2011 in Cape Town, South Africa.</p> <p>Delegates sought to conclude discussions for the design of the GCF ahead of COP 17.</p> <p>However, the Committee could not reach an agreement to adopt the recommendations and the instrument, and so decided to forward them to the COP for its consideration and approval.</p> <p>For further information, visit: http://www.iisd.ca/crs/climate/gcftd4/brief_gcftd4.html There were also a number of other formal and informal regional and group meetings designed to help parties prepare their negotiating positions.</p> <p>For more information on many of these events, visit IISD Reporting Services Climate Change Policy and Practice knowledgebase: http://climate-l.iisd.org</p> </div> <script type="text/javascript" src="../assets/src/bulletin.js"></script> </body> </html>
Java
/* * @param parseObject [ParseObject] * @return [Object] * */ export const convertBrand = (parseObject) => { const ret = {}; const object = parseObject.toJSON(); ret.id = object.objectId; ret.name = object.name; ret.description = object.description; ret.images = (object.images || []).map(image => ({ id: image.objectId, url: image.file.url })); return ret; }; /* * @param parseObject [ParseObject] * @return [Object] * */ export const convertProduct = (parseObject) => { const ret = {}; const object = parseObject.toJSON(); ret.id = object.objectId; ret.brand_id = object.brand.objectId; ret.name = object.name; ret.description = object.description; ret.images = object.images.map(image => ({ id: image.objectId, url: image.file.url })); ret.size = object.size; ret.color = object.color; ret.cost = object.cost; ret.price = object.price; ret.quantity = object.quantity; return ret; };
Java
<a alt="joel 1" href="#/web/joel/1"><div class="chapter-btn">1</div></a><a alt="joel 2" href="#/web/joel/2"><div class="chapter-btn">2</div></a><a alt="joel 3" href="#/web/joel/3"><div class="chapter-btn">3</div></a>
Java
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目&nbsp;</b></th><td class="std2">疑行無名,疑事無功</td></tr> <tr><th class="std1"><b>注音&nbsp;</b></th><td class="std2">|<sup class="subfont">ˊ</sup> ㄒ|ㄥ<sup class="subfont">ˊ</sup> ㄨ<sup class="subfont">ˊ</sup> ㄇ|ㄥ<sup class="subfont">ˊ</sup> |<sup class="subfont">ˊ</sup> ㄕ<sup class="subfont">ˋ</sup> ㄨ<sup class="subfont">ˊ</sup> ㄍㄨㄥ</td></tr> <tr><th class="std1"><b>漢語拼音&nbsp;</b></th><td class="std2"><font class="english_word">yí xíng wú míng yí shì wú gōng</font></td></tr> <tr><th class="std1"><b>釋義&nbsp;</b></th><td class="std2">做事猶豫不決,是無法成功的。史記˙卷六十八˙商君傳:<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>疑行無名,疑事無功。且夫有高人之行者,固見非於世。<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>亦作<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>疑行無成,疑事無功<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>、<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>疑事無功,疑行無名<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>。</td></tr> <tr><th class="std1"><b><font class="fltypefont">附錄</font>&nbsp;</b></th><td class="std2">修訂本參考資料</td></tr> </td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
Java
#include <iostream> using namespace std; int main() { int a,b,c,d; int sum=1080; while(cin>>a>>b>>c>>d) { if(a==0&&b==0&&c==0&&d==0) break; if(a>b) { sum=(a-b)*9+sum; } else if(a<b) { sum=((40-b)+a)*9+sum; } if(c>b) { sum=(c-b)*9+sum; } else if(c<b) { sum=((40-b)+c)*9+sum; } if(c>d) { sum=(c-d)*9+sum; } else if(c<d) { sum=((40-d)+c)*9+sum; } cout<<sum<<endl; sum=1080; } return 0; }
Java
--- layout: page title: Donald Singh's 31st Birthday date: 2016-05-24 author: Teresa Mcdaniel tags: weekly links, java status: published summary: Nam finibus mollis massa eget venenatis. Maecenas suscipit cursus. banner: images/banner/leisure-01.jpg booking: startDate: 10/08/2018 endDate: 10/13/2018 ctyhocn: TCCHHHX groupCode: DS3B published: true --- Pellentesque lacinia, tellus id ornare luctus, nunc libero pellentesque mi, lobortis tincidunt lectus libero vel tellus. Quisque tincidunt erat eget odio viverra congue. Sed eu ipsum nec tortor aliquet dapibus id id eros. Aliquam non cursus justo. Suspendisse faucibus arcu in sapien ullamcorper, eget sollicitudin quam euismod. Nulla venenatis purus sit amet volutpat volutpat. Sed felis ante, placerat id congue vel, suscipit volutpat enim. Curabitur fermentum scelerisque luctus. Morbi convallis risus vel ornare ullamcorper. Nulla facilisi. Sed malesuada faucibus varius. Nulla scelerisque eros at nisi imperdiet elementum. Vivamus fringilla ligula non pulvinar sollicitudin. Praesent sit amet hendrerit metus. Proin vel tristique erat. Integer neque sem, gravida posuere lacus et, commodo ullamcorper eros. Pellentesque at euismod libero. In hac habitasse platea dictumst. 1 Pellentesque accumsan risus ut nisi convallis rutrum 1 Pellentesque vel eros at nisi tempus vehicula 1 Nam eget tellus eu est mattis iaculis vel quis leo 1 Mauris et nisl non orci consectetur feugiat 1 Donec eget massa ac justo malesuada pellentesque ut egestas tortor. Donec velit urna, lacinia nec laoreet sed, semper a lacus. In fermentum congue turpis vitae faucibus. Nulla semper felis id ultricies cursus. Nulla vel nulla tincidunt, blandit eros ultrices, eleifend risus. Integer maximus neque at magna finibus varius. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus quis velit eu odio sagittis commodo ut sollicitudin dui. Praesent id libero ac eros consectetur faucibus. Fusce mattis id sem vitae ornare. Quisque a ipsum vel elit interdum auctor sit amet ut ante.
Java
--- layout: page title: Spring International Conference date: 2016-05-24 author: Helen Kline tags: weekly links, java status: published summary: Vivamus euismod, ipsum at eleifend porttitor, ligula neque accumsan. banner: images/banner/office-01.jpg booking: startDate: 10/10/2019 endDate: 10/15/2019 ctyhocn: RICMDHX groupCode: SIC published: true --- Donec pulvinar massa vel leo aliquet condimentum. Nullam tempor, erat nec varius posuere, nulla nisi bibendum ligula, nec accumsan sapien massa ac tortor. Fusce eleifend commodo velit sit amet mollis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pretium, velit in commodo mattis, risus odio convallis massa, in ultricies elit libero ut lectus. Nunc vel malesuada arcu. Mauris molestie justo a magna volutpat, eget auctor metus pellentesque. Vivamus venenatis nibh nec eleifend ullamcorper. Proin efficitur a ex eu bibendum. * In non nibh pulvinar urna elementum scelerisque * Aenean vel nulla eget purus dignissim condimentum vitae sollicitudin arcu * Integer varius lectus a risus ultrices, nec mollis tortor faucibus. Vestibulum ultricies auctor porttitor. Ut aliquam lacus ut rutrum condimentum. Proin finibus placerat dui id suscipit. Proin ligula arcu, egestas eu leo eu, fringilla maximus libero. Proin ut odio tempor, aliquam orci ac, laoreet sapien. In congue ipsum at purus imperdiet, eget ultricies diam congue. Morbi accumsan velit velit, sit amet aliquet magna luctus sed. Aliquam cursus diam mauris, sed condimentum enim ultricies ac. Nulla ut ligula sagittis, vulputate libero ut, placerat massa. Donec eget mauris vel justo ornare euismod nec a ligula. Etiam at dolor posuere, elementum enim eget, lacinia purus. Sed id tellus dui. Curabitur dictum tincidunt massa, vitae pharetra ligula ullamcorper in. Sed sit amet quam dignissim, tempus nibh at, euismod libero. Mauris placerat urna egestas molestie suscipit. Nullam non sem ipsum. Duis sapien risus, consectetur ac justo non, ultricies suscipit libero. Mauris felis felis, ultricies vel finibus eu, rhoncus accumsan erat. Morbi hendrerit eros venenatis tortor varius, nec mattis mauris malesuada. Curabitur a lacus sed dui cursus viverra quis vitae sapien.
Java
--- layout: page title: Webb Basic Financial Party date: 2016-05-24 author: Kenneth Schroeder tags: weekly links, java status: published summary: Aliquam erat volutpat. Pellentesque tincidunt luctus neque, ac. banner: images/banner/leisure-02.jpg booking: startDate: 01/03/2017 endDate: 01/07/2017 ctyhocn: MGMDNHX groupCode: WBFP published: true --- Maecenas semper augue vel velit volutpat, eu tempor mi volutpat. Curabitur sed lobortis justo. Ut diam turpis, efficitur eu est in, malesuada faucibus orci. Suspendisse eget lacinia tellus. In malesuada enim mi, ac convallis mi placerat ac. Nunc laoreet, leo ut vestibulum mollis, nisi leo volutpat lorem, lacinia condimentum tortor nisl vitae ligula. Mauris vitae leo porttitor, porta nunc nec, rutrum nulla. Proin maximus ullamcorper risus, non sodales eros viverra eu. Nam tempus consequat sem, eu porttitor nisl egestas at. In eget efficitur felis. Duis eu vulputate ligula. Phasellus vel augue eget urna imperdiet cursus et sed risus. Integer dignissim imperdiet diam, id feugiat leo. Mauris id leo nunc. Suspendisse potenti. Sed vel dolor diam. Ut eget ornare mauris. Phasellus porta tortor vel sapien dignissim feugiat. Pellentesque vel imperdiet tellus. * Praesent eu nibh vel eros convallis eleifend eget eu tortor * Aenean nec neque eu felis efficitur interdum nec nec arcu. Integer ac eleifend risus, eget finibus erat. Ut sollicitudin pellentesque ipsum id pellentesque. Phasellus condimentum congue porttitor. Vestibulum neque nisl, ultricies at aliquet a, efficitur non felis. Quisque ut rutrum magna. Integer semper pretium nibh, in suscipit tortor ornare vel. Integer egestas feugiat blandit. Sed non consequat magna. Cras scelerisque tristique neque nec hendrerit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras gravida ligula non aliquet lacinia. Maecenas eu ipsum sapien. Suspendisse quis ornare tortor. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam ac vulputate ipsum. Etiam scelerisque lacinia lacus id pretium. Phasellus ultrices condimentum ex.
Java
#ifndef COLLISIONALGORITHMB #define COLLISIONALGORITHMB #include "CollisionAlgorithm.h" class CollisionAlgorithmB : public CollisionAlgorithm { public: CollisionAlgorithmB(); ~CollisionAlgorithmB(); public: Tuple4f computeRayTriangleIntersection(Ray3D *ray, const Tuple3f &p0, const Tuple3f &p1, const Tuple3f &p2); }; #endif
Java
/* */ "format cjs"; /*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-342ee53 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.toast * @description * Toast */ MdToastDirective['$inject'] = ["$mdToast"]; MdToastProvider['$inject'] = ["$$interimElementProvider"]; angular.module('material.components.toast', [ 'material.core', 'material.components.button' ]) .directive('mdToast', MdToastDirective) .provider('$mdToast', MdToastProvider); /* ngInject */ function MdToastDirective($mdToast) { return { restrict: 'E', link: function postLink(scope, element) { element.addClass('_md'); // private md component indicator for styling // When navigation force destroys an interimElement, then // listen and $destroy() that interim instance... scope.$on('$destroy', function() { $mdToast.destroy(); }); } }; } /** * @ngdoc service * @name $mdToast * @module material.components.toast * * @description * `$mdToast` is a service to build a toast notification on any position * on the screen with an optional duration, and provides a simple promise API. * * The toast will be always positioned at the `bottom`, when the screen size is * between `600px` and `959px` (`sm` breakpoint) * * ## Restrictions on custom toasts * - The toast's template must have an outer `<md-toast>` element. * - For a toast action, use element with class `md-action`. * - Add the class `md-capsule` for curved corners. * * ### Custom Presets * Developers are also able to create their own preset, which can be easily used without repeating * their options each time. * * <hljs lang="js"> * $mdToastProvider.addPreset('testPreset', { * options: function() { * return { * template: * '<md-toast>' + * '<div class="md-toast-content">' + * 'This is a custom preset' + * '</div>' + * '</md-toast>', * controllerAs: 'toast', * bindToController: true * }; * } * }); * </hljs> * * After you created your preset at config phase, you can easily access it. * * <hljs lang="js"> * $mdToast.show( * $mdToast.testPreset() * ); * </hljs> * * ## Parent container notes * * The toast is positioned using absolute positioning relative to its first non-static parent * container. Thus, if the requested parent container uses static positioning, we will temporarily * set its positioning to `relative` while the toast is visible and reset it when the toast is * hidden. * * Because of this, it is usually best to ensure that the parent container has a fixed height and * prevents scrolling by setting the `overflow: hidden;` style. Since the position is based off of * the parent's height, the toast may be mispositioned if you allow the parent to scroll. * * You can, however, have a scrollable element inside of the container; just make sure the * container itself does not scroll. * * <hljs lang="html"> * <div layout-fill id="toast-container"> * <md-content> * I can have lots of content and scroll! * </md-content> * </div> * </hljs> * * @usage * <hljs lang="html"> * <div ng-controller="MyController"> * <md-button ng-click="openToast()"> * Open a Toast! * </md-button> * </div> * </hljs> * * <hljs lang="js"> * var app = angular.module('app', ['ngMaterial']); * app.controller('MyController', function($scope, $mdToast) { * $scope.openToast = function($event) { * $mdToast.show($mdToast.simple().textContent('Hello!')); * // Could also do $mdToast.showSimple('Hello'); * }; * }); * </hljs> */ /** * @ngdoc method * @name $mdToast#showSimple * * @param {string} message The message to display inside the toast * @description * Convenience method which builds and shows a simple toast. * * @returns {promise} A promise that can be resolved with `$mdToast.hide()` or * rejected with `$mdToast.cancel()`. * */ /** * @ngdoc method * @name $mdToast#simple * * @description * Builds a preconfigured toast. * * @returns {obj} a `$mdToastPreset` with the following chainable configuration methods. * * _**Note:** These configuration methods are provided in addition to the methods provided by * the `build()` and `show()` methods below._ * * <table class="md-api-table methods"> * <thead> * <tr> * <th>Method</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td>`.textContent(string)`</td> * <td>Sets the toast content to the specified string</td> * </tr> * <tr> * <td>`.action(string)`</td> * <td> * Adds an action button. <br/> * If clicked, the promise (returned from `show()`) * will resolve with the value `'ok'`; otherwise, it is resolved with `true` after a `hideDelay` * timeout * </td> * </tr> * <tr> * <td>`.highlightAction(boolean)`</td> * <td> * Whether or not the action button will have an additional highlight class.<br/> * By default the `accent` color will be applied to the action button. * </td> * </tr> * <tr> * <td>`.highlightClass(string)`</td> * <td> * If set, the given class will be applied to the highlighted action button.<br/> * This allows you to specify the highlight color easily. Highlight classes are `md-primary`, `md-warn` * and `md-accent` * </td> * </tr> * <tr> * <td>`.capsule(boolean)`</td> * <td>Whether or not to add the `md-capsule` class to the toast to provide rounded corners</td> * </tr> * <tr> * <td>`.theme(string)`</td> * <td>Sets the theme on the toast to the requested theme. Default is `$mdThemingProvider`'s default.</td> * </tr> * <tr> * <td>`.toastClass(string)`</td> * <td>Sets a class on the toast element</td> * </tr> * </tbody> * </table> * */ /** * @ngdoc method * @name $mdToast#updateTextContent * * @description * Updates the content of an existing toast. Useful for updating things like counts, etc. * */ /** * @ngdoc method * @name $mdToast#build * * @description * Creates a custom `$mdToastPreset` that you can configure. * * @returns {obj} a `$mdToastPreset` with the chainable configuration methods for shows' options (see below). */ /** * @ngdoc method * @name $mdToast#show * * @description Shows the toast. * * @param {object} optionsOrPreset Either provide an `$mdToastPreset` returned from `simple()` * and `build()`, or an options object with the following properties: * * - `templateUrl` - `{string=}`: The url of an html template file that will * be used as the content of the toast. Restrictions: the template must * have an outer `md-toast` element. * - `template` - `{string=}`: Same as templateUrl, except this is an actual * template string. * - `autoWrap` - `{boolean=}`: Whether or not to automatically wrap the template content with a * `<div class="md-toast-content">` if one is not provided. Defaults to true. Can be disabled if you provide a * custom toast directive. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope. * This scope will be destroyed when the toast is removed unless `preserveScope` is set to true. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false * - `hideDelay` - `{number=}`: How many milliseconds the toast should stay * active before automatically closing. Set to 0 or false to have the toast stay open until * closed manually. Default: 3000. * - `position` - `{string=}`: Sets the position of the toast. <br/> * Available: any combination of `'bottom'`, `'left'`, `'top'`, `'right'`, `'end'` and `'start'`. * The properties `'end'` and `'start'` are dynamic and can be used for RTL support.<br/> * Default combination: `'bottom left'`. * - `toastClass` - `{string=}`: A class to set on the toast element. * - `controller` - `{string=}`: The controller to associate with this toast. * The controller will be injected the local `$mdToast.hide( )`, which is a function * used to hide the toast. * - `locals` - `{string=}`: An object containing key/value pairs. The keys will * be used as names of values to inject into the controller. For example, * `locals: {three: 3}` would inject `three` into the controller with the value * of 3. * - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values * and the toast will not open until the promises resolve. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope. * - `parent` - `{element=}`: The element to append the toast to. Defaults to appending * to the root element of the application. * * @returns {promise} A promise that can be resolved with `$mdToast.hide()` or * rejected with `$mdToast.cancel()`. `$mdToast.hide()` will resolve either with a Boolean * value == 'true' or the value passed as an argument to `$mdToast.hide()`. * And `$mdToast.cancel()` will resolve the promise with a Boolean value == 'false' */ /** * @ngdoc method * @name $mdToast#hide * * @description * Hide an existing toast and resolve the promise returned from `$mdToast.show()`. * * @param {*=} response An argument for the resolved promise. * * @returns {promise} a promise that is called when the existing element is removed from the DOM. * The promise is resolved with either a Boolean value == 'true' or the value passed as the * argument to `.hide()`. * */ /** * @ngdoc method * @name $mdToast#cancel * * @description * `DEPRECATED` - The promise returned from opening a toast is used only to notify about the closing of the toast. * As such, there isn't any reason to also allow that promise to be rejected, * since it's not clear what the difference between resolve and reject would be. * * Hide the existing toast and reject the promise returned from * `$mdToast.show()`. * * @param {*=} response An argument for the rejected promise. * * @returns {promise} a promise that is called when the existing element is removed from the DOM * The promise is resolved with a Boolean value == 'false'. * */ function MdToastProvider($$interimElementProvider) { // Differentiate promise resolves: hide timeout (value == true) and hide action clicks (value == ok). toastDefaultOptions['$inject'] = ["$animate", "$mdToast", "$mdUtil", "$mdMedia"]; var ACTION_RESOLVE = 'ok'; var activeToastContent; var $mdToast = $$interimElementProvider('$mdToast') .setDefaults({ methods: ['position', 'hideDelay', 'capsule', 'parent', 'position', 'toastClass'], options: toastDefaultOptions }) .addPreset('simple', { argOption: 'textContent', methods: ['textContent', 'content', 'action', 'highlightAction', 'highlightClass', 'theme', 'parent' ], options: /* ngInject */ ["$mdToast", "$mdTheming", function($mdToast, $mdTheming) { return { template: '<md-toast md-theme="{{ toast.theme }}" ng-class="{\'md-capsule\': toast.capsule}">' + ' <div class="md-toast-content">' + ' <span class="md-toast-text" role="alert" aria-relevant="all" aria-atomic="true">' + ' {{ toast.content }}' + ' </span>' + ' <md-button class="md-action" ng-if="toast.action" ng-click="toast.resolve()" ' + ' ng-class="highlightClasses">' + ' {{ toast.action }}' + ' </md-button>' + ' </div>' + '</md-toast>', controller: /* ngInject */ ["$scope", function mdToastCtrl($scope) { var self = this; if (self.highlightAction) { $scope.highlightClasses = [ 'md-highlight', self.highlightClass ] } $scope.$watch(function() { return activeToastContent; }, function() { self.content = activeToastContent; }); this.resolve = function() { $mdToast.hide( ACTION_RESOLVE ); }; }], theme: $mdTheming.defaultTheme(), controllerAs: 'toast', bindToController: true }; }] }) .addMethod('updateTextContent', updateTextContent) .addMethod('updateContent', updateTextContent); function updateTextContent(newContent) { activeToastContent = newContent; } return $mdToast; /* ngInject */ function toastDefaultOptions($animate, $mdToast, $mdUtil, $mdMedia) { var SWIPE_EVENTS = '$md.swipeleft $md.swiperight $md.swipeup $md.swipedown'; return { onShow: onShow, onRemove: onRemove, toastClass: '', position: 'bottom left', themable: true, hideDelay: 3000, autoWrap: true, transformTemplate: function(template, options) { var shouldAddWrapper = options.autoWrap && template && !/md-toast-content/g.test(template); if (shouldAddWrapper) { // Root element of template will be <md-toast>. We need to wrap all of its content inside of // of <div class="md-toast-content">. All templates provided here should be static, developer-controlled // content (meaning we're not attempting to guard against XSS). var templateRoot = document.createElement('md-template'); templateRoot.innerHTML = template; // Iterate through all root children, to detect possible md-toast directives. for (var i = 0; i < templateRoot.children.length; i++) { if (templateRoot.children[i].nodeName === 'MD-TOAST') { var wrapper = angular.element('<div class="md-toast-content">'); // Wrap the children of the `md-toast` directive in jqLite, to be able to append multiple // nodes with the same execution. wrapper.append(angular.element(templateRoot.children[i].childNodes)); // Append the new wrapped element to the `md-toast` directive. templateRoot.children[i].appendChild(wrapper[0]); } } // We have to return the innerHTMl, because we do not want to have the `md-template` element to be // the root element of our interimElement. return templateRoot.innerHTML; } return template || ''; } }; function onShow(scope, element, options) { activeToastContent = options.textContent || options.content; // support deprecated #content method var isSmScreen = !$mdMedia('gt-sm'); element = $mdUtil.extractElementByName(element, 'md-toast', true); options.element = element; options.onSwipe = function(ev, gesture) { //Add the relevant swipe class to the element so it can animate correctly var swipe = ev.type.replace('$md.',''); var direction = swipe.replace('swipe', ''); // If the swipe direction is down/up but the toast came from top/bottom don't fade away // Unless the screen is small, then the toast always on bottom if ((direction === 'down' && options.position.indexOf('top') != -1 && !isSmScreen) || (direction === 'up' && (options.position.indexOf('bottom') != -1 || isSmScreen))) { return; } if ((direction === 'left' || direction === 'right') && isSmScreen) { return; } element.addClass('md-' + swipe); $mdUtil.nextTick($mdToast.cancel); }; options.openClass = toastOpenClass(options.position); element.addClass(options.toastClass); // 'top left' -> 'md-top md-left' options.parent.addClass(options.openClass); // static is the default position if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) { options.parent.css('position', 'relative'); } element.on(SWIPE_EVENTS, options.onSwipe); element.addClass(isSmScreen ? 'md-bottom' : options.position.split(' ').map(function(pos) { return 'md-' + pos; }).join(' ')); if (options.parent) options.parent.addClass('md-toast-animating'); return $animate.enter(element, options.parent).then(function() { if (options.parent) options.parent.removeClass('md-toast-animating'); }); } function onRemove(scope, element, options) { element.off(SWIPE_EVENTS, options.onSwipe); if (options.parent) options.parent.addClass('md-toast-animating'); if (options.openClass) options.parent.removeClass(options.openClass); return ((options.$destroy == true) ? element.remove() : $animate.leave(element)) .then(function () { if (options.parent) options.parent.removeClass('md-toast-animating'); if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) { options.parent.css('position', ''); } }); } function toastOpenClass(position) { // For mobile, always open full-width on bottom if (!$mdMedia('gt-xs')) { return 'md-toast-open-bottom'; } return 'md-toast-open-' + (position.indexOf('top') > -1 ? 'top' : 'bottom'); } } } })(window, window.angular);
Java
<?php namespace Dvsa\Mot\Frontend\SecurityCardModule\CardOrder\Controller; use Core\Controller\AbstractDvsaActionController; use Dvsa\Mot\Frontend\AuthenticationModule\Model\Identity; use Dvsa\Mot\Frontend\SecurityCardModule\CardOrder\Service\OrderNewSecurityCardSessionService; use DvsaCommon\Constants\FeatureToggle; use DvsaFeature\FeatureToggles; use Zend\Http\Response; use Zend\View\Model\ViewModel; class CardOrderConfirmationController extends AbstractDvsaActionController { /** @var OrderNewSecurityCardSessionService $session */ protected $session; /** @var Identity $identity */ private $identity; /** @var FeatureToggles */ private $featureToggles; public function __construct( OrderNewSecurityCardSessionService $securityCardSessionService, Identity $identity, FeatureToggles $featureToggles ) { $this->session = $securityCardSessionService; $this->identity = $identity; $this->featureToggles = $featureToggles; } /** * @return ViewModel */ public function indexAction(): ViewModel { $userId = $this->params()->fromRoute('userId', $this->identity->getUserId()); if (false === $this->checkValidSession()) { $this->redirectToStart($userId); } if ($this->featureToggles->isEnabled(FeatureToggle::TWO_FA_GRACE_PERIOD) && $this->identity->isAuthenticatedWithSecurityQAndAs()) { $this->identity->setAuthenticatedWith2FA(true); } if (!$this->identity->isAuthenticatedWithSecurityQAndAs()) { $this->buildBreadcrumbs(); } // As this is the last page of the journey clear the session $this->session->clearByGuid($userId); return (new ViewModel())->setTemplate('2fa/card-order/confirmation'); } /** * If there is no valid session, we should go to the journey start. * * @return bool */ protected function checkValidSession(): bool { $values = $this->session->toArray(); return !(is_array($values) && count($values) === 0); } /** * @param int $userId * * @return Response */ protected function redirectToStart($userId): Response { return $this->redirect()->toRoute('security-card-order/new', ['userId' => $userId]); } protected function buildBreadcrumbs() { $this->getBreadcrumbBuilder() ->simple('Your profile', 'newProfile') ->simple('Order a security card') ->build(); } }
Java
/* SaveFileController * * Version 1.0 * * November 13, 2017 * * Copyright (c) 2017 Cup Of Java. All rights reserved. */ package com.cmput301f17t11.cupofjava.Controllers; import android.content.Context; import com.cmput301f17t11.cupofjava.Models.Habit; import com.cmput301f17t11.cupofjava.Models.HabitEvent; import com.cmput301f17t11.cupofjava.Models.HabitList; import com.cmput301f17t11.cupofjava.Models.User; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import java.util.ArrayList; /** * Implements the file to save data to. * * @version 1.0 */ public class SaveFileController { private ArrayList<User> allUsers; //private String username; private String saveFile = "test_save_file4.sav"; public SaveFileController(){ this.allUsers = new ArrayList<User>(); } /** * Loads data from file. * * @param context instance of Context */ private void loadFromFile(Context context){ try{ FileInputStream ifStream = context.openFileInput(saveFile); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ifStream)); Gson gson = new Gson(); Type userArrayListType = new TypeToken<ArrayList<User>>(){}.getType(); this.allUsers = gson.fromJson(bufferedReader, userArrayListType); ifStream.close(); } //create a new array list if a file does not already exist catch (FileNotFoundException e){ this.allUsers = new ArrayList<User>(); saveToFile(context); } catch (IOException e){ throw new RuntimeException(); } } /** * Saves current ArrayList contents in file. * * @param context instance of Context */ private void saveToFile(Context context){ try{ FileOutputStream ofStream = context.openFileOutput(saveFile, Context.MODE_PRIVATE); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(ofStream)); Gson gson = new Gson(); gson.toJson(this.allUsers, bufferedWriter); bufferedWriter.flush(); ofStream.close(); } catch (FileNotFoundException e){ //shouldn't really happen, since a file not found would create a new file. throw new RuntimeException("Laws of nature defied!"); } catch (IOException e){ throw new RuntimeException(); } } /** * Adds new user and saves to file. * * @param context instance of Context * @param user instance of User * @see User */ public void addNewUser(Context context, User user){ loadFromFile(context); this.allUsers.add(user); saveToFile(context); } /** * Deletes all user from file. * * @param context instance of Context */ public void deleteAllUsers(Context context){ this.allUsers = new ArrayList<>(); saveToFile(context); } /** * Gets user index. * * @param context instance of Context * @param username string username * @return integer user index if username matches, -1 otherwise */ public int getUserIndex(Context context, String username){ loadFromFile(context); for (int i = 0; i < this.allUsers.size(); i++){ if (this.allUsers.get(i).getUsername().equals(username)){ return i; } } return -1; } /** * Gets HabitList instance. * * @param context instance of Context * @param userIndex integer user index * @return HabitList * @see HabitList */ public HabitList getHabitList(Context context, int userIndex){ loadFromFile(context); return this.allUsers.get(userIndex).getHabitList(); } /** * Gets ArrayList of type Habit. * * @param context instance of Context * @param userIndex integer user index * @return list */ public ArrayList<Habit> getHabitListAsArray(Context context, int userIndex){ loadFromFile(context); ArrayList<Habit> list = this.allUsers.get(userIndex).getHabitListAsArray(); return list; } /** * Adds a habit to a particular user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habit instance of Habit * @see Habit */ public void addHabit(Context context, int userIndex, Habit habit){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().addHabit(habit); saveToFile(context); } /** * Gets habit from a particular user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @return instance of Habit * @see Habit */ public Habit getHabit(Context context, int userIndex, int habitIndex){ loadFromFile(context); return this.allUsers.get(userIndex).getHabitListAsArray().get(habitIndex); } /** * Deletes habit from a certain user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit */ public void deleteHabit(Context context, int userIndex, int habitIndex){ loadFromFile(context); this.allUsers.get(userIndex).getHabitListAsArray().remove(habitIndex); saveToFile(context); } /** * Adds habit event to a particular user's habit event list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @param habitEvent instance of HabitEvent * @see HabitEvent */ public void addHabitEvent(Context context, int userIndex, int habitIndex, HabitEvent habitEvent){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex).addHabitEvent(habitEvent); saveToFile(context); } /** * Removes a habit event from a particular user's habit event list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @param habitEventIndex integer index of habit event */ public void removeHabitEvent(Context context, int userIndex, int habitIndex, int habitEventIndex){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex) .getHabitEventHistory().getHabitEvents().remove(habitEventIndex); saveToFile(context); } /** * For use in timeline view. * * @param context instance of Context * @param userIndex integer user index * @return ArrayList of HabitEvent type * @see HabitEvent */ public ArrayList<HabitEvent> getAllHabitEvents(Context context, int userIndex){ loadFromFile(context); ArrayList<HabitEvent> habitEvents = new ArrayList<>(); User user = this.allUsers.get(userIndex); ArrayList<Habit> habitList = user.getHabitListAsArray(); Habit currentHabit; ArrayList<HabitEvent> currentHabitEvents; for (int i = 0; i < habitList.size(); i++){ currentHabit = habitList.get(i); currentHabitEvents = currentHabit.getHabitEventHistory().getHabitEvents(); for (int j = 0; j < currentHabitEvents.size() ; j++){ habitEvents.add(user.getHabitListAsArray().get(i) .getHabitEventHistory().getHabitEvents().get(j)); } } return habitEvents; } }
Java
import unittest from katas.beta.what_color_is_your_name import string_color class StringColorTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(string_color('Jack'), '79CAE5') def test_equal_2(self): self.assertEqual(string_color('Joshua'), '6A10D6') def test_equal_3(self): self.assertEqual(string_color('Joshua Smith'), '8F00FB') def test_equal_4(self): self.assertEqual(string_color('Hayden Smith'), '7E00EE') def test_equal_5(self): self.assertEqual(string_color('Mathew Smith'), '8B00F1') def test_is_none_1(self): self.assertIsNone(string_color('a'))
Java
<?php namespace BoomCMS\Settings; use BoomCMS\Support\Facades\Settings; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Lang; abstract class Manager { public static function options() { $options = []; foreach (Config::get('boomcms.settingsManagerOptions') as $name => $type) { $langPrefix = "boomcms::settings-manager.$name."; $options[] = [ 'name' => $name, 'label' => Lang::get("{$langPrefix}_label"), 'type' => $type, 'value' => Settings::get($name), 'info' => Lang::has("{$langPrefix}_info") ? Lang::get("{$langPrefix}_info") : '', ]; } usort($options, function ($a, $b) { return ($a['label'] < $b['label']) ? -1 : 1; }); return $options; } }
Java
package endpoints.algebra.circe import io.circe.{Decoder => CirceDecoder, Encoder => CirceEncoder} /** * Combines both an [[io.circe.Encoder]] and a [[io.circe.Decoder]] into a single type class. * * You don’t need to define instances by yourself as they can be derived from an existing pair * of an [[io.circe.Encoder]] and a [[io.circe.Decoder]]. * * @see https://github.com/travisbrown/circe/issues/301 */ trait CirceCodec[A] { def encoder: CirceEncoder[A] def decoder: CirceDecoder[A] } object CirceCodec { @inline def apply[A](implicit codec: CirceCodec[A]): CirceCodec[A] = codec implicit def fromEncoderAndDecoder[A](implicit enc: CirceEncoder[A], dec: CirceDecoder[A]): CirceCodec[A] = new CirceCodec[A] { val decoder = dec val encoder = enc } }
Java
# go-miner # Data Mining Algorithms in GoLang. ## Installation $ go get github.com/ozzie80/go-miner ## Algorithms ### k-means Description From [Wikipedia](https://en.wikipedia.org/wiki/K-means_clustering): > k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells. The k-means implementation of go-miner uses the [k-means++](https://en.wikipedia.org/wiki/K-means%2B%2B "k-means++") algorithm for choosing the initial cluster centroids. The implementation provides internal quality indexes, [Dunn Index](https://en.wikipedia.org/wiki/Dunn_index) and [Davies-Bouldin Index](https://en.wikipedia.org/wiki/Davies%E2%80%93Bouldin_index), for evaluating clustering results. Usage Example // Create points or read from a .csv file points := []dt.Vector{{1.0, 2.0, 3.0}, {5.1, 6.2, 7.3}, {2.0, 3.5, 5.0}} // Specify Parameters: K, Points, MaxIter (optional) params := kmeans.Params{2, points, math.MaxInt64} // Run k-means clusters, err := kmeans.Run(params) // Get quality index score index := kmeans.DunnIndex{} // DaviesBouldinIndex{} score := index.GetScore(clusters) To Do - Concurrent version - Cuda/GPU version ### To Be Added - Apriori - *K*NN - Naive Bayes - PageRank - SVM - ... ## License go-miner is MIT License.
Java
namespace UCloudSDK.Models { /// <summary> /// 获取流量信息 /// <para> /// http://docs.ucloud.cn/api/ucdn/get_ucdn_traffic.html /// </para> /// </summary> public partial class GetUcdnTrafficRequest { /// <summary> /// 默认Action名称 /// </summary> private string _action = "GetUcdnTraffic"; /// <summary> /// API名称 /// <para> /// GetUcdnTraffic /// </para> /// </summary> public string Action { get { return _action; } set { _action = value; } } /// <summary> /// None /// </summary> public string 不需要提供参数 { get; set; } } }
Java
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Progress extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ function __construct() { parent::__construct(); date_default_timezone_set("Asia/Jakarta"); $this->load->model('M_progress'); if (empty($this->session->userdata('session'))) { redirect('login'); } } public function index() { $result['data'] = $this->M_progress->getAll(); $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/list_progress',$result); $this->load->view('backend/footer'); } public function tambah() { $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/add_progress'); $this->load->view('backend/footer'); } public function add() { $tanggal1 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); if (empty($this->input->post('tanggal2')) || empty($this->input->post('jam2'))) { $tanggal2 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); }else{ $tanggal2 = substr($this->input->post('tanggal2'), 6,4)."-".substr($this->input->post('tanggal2'), 0,2)."-".substr($this->input->post('tanggal2'), 3,2); } //die(); switch ($this->input->post('deputi')) { case 'asdep1': $created_by = 2; $url_back ='asdep1'; break; case 'asdep2': $created_by = 3; $url_back ='asdep2'; break; case 'asdep3': $created_by = 4; $url_back ='asdep3'; break; case 'asdep4': $created_by = 5; $url_back ='asdep4'; break; default: # code... break; } $dokumentasi1 = $this->uploadImage($_FILES['foto1'],'foto1'); $dokumentasi2 = $this->uploadImage($_FILES['foto2'],'foto2'); $data = array('narasiKebijakan'=>$this->input->post('narasiKebijakan'),'uraian'=>$this->input->post('uraian'), 'tanggal1'=>$tanggal1,'tanggal2'=>$tanggal2,'lokasi'=>$this->input->post('lokasi'),'hasil'=>$this->input->post('hasil'), 'tindak_ljt'=>$this->input->post('tindak_ljt'),'arahan'=>$this->input->post('arahan'),'masalah'=>$this->input->post('masalah'), 'dokumentasi1'=>$dokumentasi1,'dokumentasi2'=>$dokumentasi2,'created_by'=>$created_by, 'updated_by'=>$this->session->userdata('session')[0]->no); //print_r($data);die(); $this->M_progress->insert($data); redirect('Beranda/view/'.$url_back); } public function uploadImage($image,$name) { //print_r($image);die(); if ($image) { $file_name = 'file_'.time(); $config['upload_path'] = './assets/images/uploads/'; $config['allowed_types'] = 'jpg|png|JPG|PNG|JPEG|jpeg'; $config['max_size'] = 20480; $config['max_width'] = 5120; $config['max_height'] = 3840; $config['file_name'] = $file_name; $this->upload->initialize($config); if ($this->upload->do_upload($name)) { $img = $this->upload->data(); return $img['file_name']; }else{ return ""; //echo $this->upload->display_errors('<p>', '</p>'); } //redirect('Foto'); } } public function config() { $result['data'] = $this->M_progress->getAll(); $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/list_progress',$result); $this->load->view('backend/footer'); } public function update($value) { $result = $this->M_progress->getId($value); $doc1 = $_FILES['foto1']; $doc2 = $_FILES['foto2']; $tanggal1 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); if (empty($this->input->post('tanggal2')) || empty($this->input->post('jam2'))) { $tanggal2 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); }else{ $tanggal2 = substr($this->input->post('tanggal2'), 6,4)."-".substr($this->input->post('tanggal2'), 0,2)."-".substr($this->input->post('tanggal2'), 3,2); } if ($doc1['size'] != 0) { $dokumentasi1 = $this->uploadImage($_FILES['foto1'],'foto1'); }else{ $dokumentasi1 = $result[0]->dokumentasi1; } if ($doc2['size'] != 0) { $dokumentasi2 = $this->uploadImage($_FILES['foto2'],'foto2'); }else{ $dokumentasi2 = $result[0]->dokumentasi2; } $data = array('narasiKebijakan'=>$this->input->post('narasiKebijakan'),'uraian'=>$this->input->post('uraian'),'tanggal1'=>$tanggal1,'tanggal2'=>$tanggal2,'lokasi'=>$this->input->post('lokasi'),'hasil'=>$this->input->post('hasil'),'arahan'=>$this->input->post('arahan'),'tindak_ljt'=>$this->input->post('tindak_ljt'),'masalah'=>$this->input->post('masalah'),'dokumentasi1'=>$dokumentasi1,'dokumentasi2'=>$dokumentasi2,'updated_by'=>$this->session->userdata('session')[0]->no,'updated_at'=>date("Y-m-d H:i:s")); //print_r($data);die(); $this->M_progress->updateId($data,$value); $data = $this->M_progress->getId($value); redirect('Beranda/view/'.$data[0]->role); } public function delete($value) { $this->M_progress->deleteId($value); $data = $this->M_kebijakan->getId($value); redirect('Beranda/view/'.$data[0]->role); } public function edit($value) { $result['data'] = $this->M_progress->getId($value); $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/edit_progress',$result); $this->load->view('backend/footer'); } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Andersc.CodeLib.Tester.Helpers { public class Book { public string Title { get; set; } public string Publisher { get; set; } public int Year { get; set; } } }
Java
## XII. Admin processes ### รันงานของผู้ดูแลระบบ/การจัดการให้เป็นกระบวนการแบบครั้งเดียว [process formation](./concurrency) เป็นอาร์เรย์ของ process ที่ใช้ในการทำธุรกิจปรกติของ app (เช่นการจัดการ reqeust ของเว็บ) ขณะทำงาน developer มักต้องการทำการดูแลหรือบำรุงรักษาเพียงคนเดียวสำหรับ app เช่น: * รันการย้ายข้อมูลฐานข้อมูล (เช่น `manage.py migrate` ใน Django, `rake db:migrate` ใน Rails) * รันคอนโซล (เป็นที่รู้จักในชื่อ [REPL](http://en.wikipedia.org/wiki/Read-eval-print_loop) shell) เพื่อรัน code แบบทันทีทันใดหรือตรวจสอบโมเดลของ app ที่ติดต่อกับฐานข้อมูลทันที ภาษาคอมพิวเตอร์ส่วนใหญ่มี REPL โดยการรัน interpreter โดยไม่ต้องมี argument ใดๆ (เช่น `python` หรือ `perl`) หรือในบางกรณีมีการแยกคำสั่ง (เช่น `irb` สำหรับ Ruby, `rails console` สำหรับ Rails) * รันสคริปต์ครั้งเดียวที่ commit ไปที่ repo ของ app (เช่น `php scripts/fix_bad_records.php`) การดูแล process ครั้งเดียวควรจะทำงานในสภาพแวดล้อมที่เหมือนกับทั้วไป [long-running processes](./processes) สำหรับ app ซึ่งทำงานกับ [release](./build-release-run) ใช้ [codebase](./codebase) and [การตั้งค่า](./config) เดียวกันกับ process ใดๆที่ทำงานกับ release ผู้ดูแลระบบของ code จำเป็นต้อง ship ด้วย application code เพื่อหลีกเลี่ยงปัญหาการประสาน (synchronization) เทคนิค [dependency isolation](./dependencies) เดียวกันควรจะใช้กับชนิดของ process ทั้งหมด ตัวอย่างเช่น ถ้า Ruby web process ใช้คำสั่ง `bundle exec thin start` ดังนั้นการย้ายข้อมูลฐานข้อมูลควรจะใช้คำสั่ง `bundle exec rake db:migrate` ในทำนองเดียวกันกับ Python program ใช้ Virtualenv ควรจะใช้คำสั่ง `bin/python` สำหรับทำงานทั้ง Tornado webserver และการดูแลระบบ process `manage.py` ใดๆ Twelve-factor ชื่นชอบภาษาคอมพิวเตอร์ที่มี PERL shell out of the box เป็นอย่างมาก และซึ่งทำให้ง่ายสำหรับรันสคริปต์ครั้งเดียว ใน local deploy, developer ใช้กระบวนการดูแลระบบครั้งเดียวโดยใช้คำสั่ง shell ข้างใน app ใน production deploy, developer สามารถใช้ ssh หรือคำสั่งรีโมทอื่นที่กลไกกำทำงานโดยสภาพแวดล้อมการดำเนินงานของ deploy เพื่อรัน process
Java
import test from 'ava'; import { spawn } from 'child_process'; test.cb('app should boot without exiting', (t) => { const cli = spawn('node', [ './cli' ]); cli.stderr.on('data', (param) => { console.log(param.toString()); }); cli.on('close', (code) => { t.fail(`app failed to boot ${code}`); }); setTimeout(() => { t.pass(); t.end(); cli.kill(); }, 500); });
Java