code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
(function () { $(function () { var _userService = abp.services.app.user; var _$modal = $('#UserCreateModal'); var _$form = _$modal.find('form'); _$form.validate({ rules: { Password: "required", ConfirmPassword: { equalTo: "#Password" } } }); $('#RefreshButton').click(function () { refreshUserList(); }); $('.delete-user').click(function () { var userId = $(this).attr("data-user-id"); var userName = $(this).attr('data-user-name'); deleteUser(userId, userName); }); $('.edit-user').click(function (e) { var userId = $(this).attr("data-user-id"); e.preventDefault(); $.ajax({ url: abp.appPath + 'Users/EditUserModal?userId=' + userId, type: 'POST', contentType: 'application/html', success: function (content) { $('#UserEditModal div.modal-content').html(content); }, error: function (e) { } }); }); _$form.find('button[type="submit"]').click(function (e) { e.preventDefault(); if (!_$form.valid()) { return; } var user = _$form.serializeFormToObject(); //serializeFormToObject is defined in main.js user.roleNames = []; var _$roleCheckboxes = $("input[name='role']:checked"); if (_$roleCheckboxes) { for (var roleIndex = 0; roleIndex < _$roleCheckboxes.length; roleIndex++) { var _$roleCheckbox = $(_$roleCheckboxes[roleIndex]); user.roleNames.push(_$roleCheckbox.attr('data-role-name')); } } abp.ui.setBusy(_$modal); _userService.create(user).done(function () { _$modal.modal('hide'); location.reload(true); //reload page to see new user! }).always(function () { abp.ui.clearBusy(_$modal); }); }); _$modal.on('shown.bs.modal', function () { _$modal.find('input:not([type=hidden]):first').focus(); }); function refreshUserList() { location.reload(true); //reload page to see new user! } function deleteUser(userId, userName) { abp.message.confirm( "Delete user '" + userName + "'?", function (isConfirmed) { if (isConfirmed) { _userService.delete({ id: userId }).done(function () { refreshUserList(); }); } } ); } }); })();
zchhaenngg/IWI
src/ImproveX.Web/Views/Users/Index.js
JavaScript
mit
2,949
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import camera import time class Display(object): # Inheritrance convinience functions def init(self): pass def close(self): pass def mouse(self, mouseButton, buttonState, x, y): pass def mouseMotion(self, x, y, dx, dy): pass def passiveMouseMotion(self, x, y, dx, dy): pass def keyboard(self, key, x, y): pass def specialKeys(self, key, x, y): pass def timerFired(self, value): pass def draw(self): pass # Initialization function def __init__(self, width = 1280, height = 720, frameName = "OpenGL"): self.frameSize = (self.width, self.height) = (width, height) self.frameName = frameName self.timerDelay = 20 self.clearColor = (135.0/255, 206.0/255, 250.0/255, 1) self.defaultColor = (1, 1, 1) # Camera positioning self.pos = (0, 0, 0) self.ypr = (0, 0, 0) self.init() # Set up graphics self.initGL() self.initGLUT() self.camera = camera.Camera(self.width, self.height) # For mouse motion self._mouseX = None self._mouseY = None # One-time GL commands def initGL(self): glClearColor(*self.clearColor) # Initialize the window manager (GLUT) def initGLUT(self): glutInit() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(*self.frameSize) glutCreateWindow(self.frameName) # Register all the convenience functions glutDisplayFunc(self.drawWrapper) glutIdleFunc(self.drawWrapper) glutTimerFunc(self.timerDelay, self.timerFired, 0) glutMouseFunc(self.mouse) glutMotionFunc(self.mouseMotionWrapper) glutPassiveMotionFunc(self.passiveMouseMotionWrapper) glutKeyboardFunc(self.keyboard) glutSpecialFunc(self.specialKeys) glutReshapeFunc(self.reshape) # Try to register a close function (fall back to a different one) try: glutCloseFunc(self.close) except: glutWMCloseFunc(self.close) # GL commands executed before drawing def preGL(self): glShadeModel(GL_FLAT) glEnable(GL_DEPTH_TEST) # Set up colors and clear buffers glClearColor(*self.clearColor) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(*self.defaultColor) glLoadIdentity() # Commands after GL is done def postGL(self): glutSwapBuffers() time.sleep(1/60.0) # Wrapper to re-register timer event def timerFiredWrapper(self, value): self.timerFired(value) glutTimerFunc(self.timerDelay, self.timerFired, value + 1) # Wrapper to handle as much GL as possible def drawWrapper(self): self.preGL() # Let the camera draw the view self.camera.draw(self.draw, self.pos, self.ypr) self.postGL() # Wrapper to pass change in position as well as position # Only called when mouse motion and button pressed def mouseMotionWrapper(self, x, y): if(self._mouseX == None or self._mouseY == None): (self._mouseX, self._mouseY) = (x, y) (dx, dy) = (x - self._mouseX, y - self._mouseY) self.mouseMotion(x, y, dx, dy) (self._mouseX, self._mouseY) = (x, y) # Wrapper to pass change in position as well as position # Called when mouse motion and not button pressed def passiveMouseMotionWrapper(self, x, y): if(self._mouseX == None or self._mouseY == None): (self._mouseX, self._mouseY) = (x, y) (dx, dy) = (x - self._mouseX, y - self._mouseY) self.passiveMouseMotion(x, y, dx, dy) (self._mouseX, self._mouseY) = (x, y) # Update when resizing the window def reshape(self, width, height): if(self.width != width or self.height != height): glutReshapeWindow(width, height) self.camera.width = width self.camera.height = height # Run the GL def run(self): glutMainLoop()
Alex4913/PyOpenGL-Boilerplate
src/display.py
Python
mit
3,803
package automortar.sample.rest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import javax.inject.Inject; import autodagger.AutoExpose; import automortar.sample.app.App; import automortar.sample.app.DaggerScope; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; /** * Created by lukasz on 19/02/15. */ @DaggerScope(App.class) public class RestClient { private Service service; @Inject public RestClient() { Gson gson = new GsonBuilder().create(); RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.BASIC) .setEndpoint("http://jsonplaceholder.typicode.com/") .setConverter(new GsonConverter(gson)) .build(); service = restAdapter.create(Service.class); } public Service getService() { return service; } }
lukaspili/Auto-Mortar
sample/src/main/java/automortar/sample/rest/RestClient.java
Java
mit
909
using NetTelebot.Type.Payment; using Newtonsoft.Json.Linq; namespace NetTelebot.Tests.TypeTestObject.PaymentObject { internal static class InvoiceInfoObject { /// <summary> /// This object contains basic information about an invoice. /// See <see href="https://core.telegram.org/bots/api#invoice">API</see> /// </summary> /// <param name="title">Product name</param> /// <param name="description">Product description</param> /// <param name="startParameter">Unique bot deep-linking parameter that can be used to generate this invoice</param> /// <param name="currency">Three-letter ISO 4217 currency code</param> /// <param name="totalAmount">Total price in the smallest units of the currency (integer, not float/double). /// For example, for a price of US$ 1.45 pass amount = 145. </param> /// <returns><see cref="InvoceInfo"/></returns> internal static JObject GetObject(string title, string description, string startParameter, string currency, int totalAmount) { dynamic audioInfo = new JObject(); audioInfo.title = title; audioInfo.description = description; audioInfo.start_parameter = startParameter; audioInfo.currency = currency; audioInfo.total_amount = totalAmount; return audioInfo; } } }
vertigra/NetTelebot-2.0
NetTelebot.Tests/TypeTestObject/PaymentObject/InvoiceInfoObject.cs
C#
mit
1,426
//>>built define({nomatchMessage:"Die Kennw\u00f6rter stimmen nicht \u00fcberein.",badPasswordMessage:"Ung\u00fcltiges Kennwort."});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/dojox/form/nls/de/PasswordValidator.js
JavaScript
mit
132
#include "platform/i_platform.h" #include "core/map/map_element.h" namespace map { MapElement::~MapElement() { } MapElement::MapElement( int32_t Id ) : mIdentifier( 0 ) , mId( Id ) , mSpawnedActorGUID( -1 ) { SetNextUID(); } void MapElement::SetNextUID() { static int32_t NextUID = 0; mUID = ++NextUID; } int32_t MapElement::GetIdentifier() { return mIdentifier; } void MapElement::Load( Json::Value& setters ) { std::string identifier; if ( Json::GetStr( setters["identifier"], identifier ) ) { mIdentifier = AutoId( identifier ); } } void MapElement::Save( Json::Value& Element ) { std::string elementName; if ( IdStorage::Get().GetName( mId, elementName ) ) { Element["name"] = Json::Value( elementName ); } std::string identifierName; if ( IdStorage::Get().GetName( mIdentifier, identifierName ) ) { Element["identifier"] = Json::Value( identifierName ); } } void MapElement::SetIdentifier( int32_t uId ) { mIdentifier = uId; } void MapElement::SetSpawnedActorGUID( int32_t spawnedActorGUID ) { mSpawnedActorGUID = spawnedActorGUID; } int32_t MapElement::GetSpawnedActorGUID() const { return mSpawnedActorGUID; } int32_t MapElement::GetUID() const { return mUID; } MapElement& MapElement::operator=( MapElement const& other ) { mIdentifier = other.mIdentifier; mId = other.mId; mSpawnedActorGUID = other.mSpawnedActorGUID; // mUID should be unique SetNextUID(); return *this; } DefaultMapElement::DefaultMapElement( int32_t Id ) : MapElement( Id ) { } } // namespace map
ishtoo/Reaping2
src/core/map/map_element.cpp
C++
mit
1,638
/* * Copyright 2005 Joe Walker * * 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 org.directwebremoting.export; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.directwebremoting.Browser; import org.directwebremoting.datasync.Directory; import org.directwebremoting.datasync.StoreProvider; import org.directwebremoting.io.DwrConvertedException; import org.directwebremoting.io.Item; import org.directwebremoting.io.ItemUpdate; import org.directwebremoting.io.MatchedItems; import org.directwebremoting.io.StoreChangeListener; import org.directwebremoting.io.StoreRegion; /** * External interface to the set of {@link StoreProvider}s that have been * registered. * @author Joe Walker [joe at getahead dot ltd dot uk] */ public class Data { /** * Provide access to a single item of data given its ID. * @param storeId The ID of the store into which we look for the item * @param itemId The ID of the item to retrieve from the store * @param listener The client side interface to pass async updates to. * Will be <code>null</code> if no async updates are required * @return The found item, or null if one was not found. */ public Item viewItem(String storeId, String itemId, StoreChangeListener<Object> listener) { StoreProvider<Object> provider = Directory.getRegistration(storeId, Object.class); if (provider == null) { throw new DwrConvertedException("clientId not found"); } if (listener != null) { return provider.viewItem(itemId, listener); } else { return provider.viewItem(itemId); } } /** * Notes that there is a region of a page that wishes to subscribe to server * side data, and registers a callback function to receive the data. * @param storeId The ID of a store as registered on the server using * {@link Directory#register}. If no store has been registered * on the server using this passed <code>storeId</code>, then this call will * act as if there was a store registered, but that it was empty. This may * make it harder to scan the server for exposed stores. Internally however * the call will be ignored. This behavior may change in the future and * should <strong>not</strong> be relied upon. * @param region For field documentation see {@link StoreRegion}. * @param listener The client side interface to pass async updates to. * Will be <code>null</code> if no async updates are required */ public MatchedItems viewRegion(String storeId, StoreRegion region, StoreChangeListener<Object> listener) { StoreProvider<Object> provider = Directory.getRegistration(storeId, Object.class); if (provider == null) { throw new DwrConvertedException("clientId not found"); } if (region == null) { region = new StoreRegion(); } if (listener != null) { provider.unsubscribe(listener); return provider.viewRegion(region, listener); } else { return provider.viewRegion(region); } } /** * Remove a subscription from the list of people that we are remembering * to keep updated * @param receiver The client side interface to pass async updates to. * Will be <code>null</code> if no async updates are required */ public void unsubscribe(String storeId, StoreChangeListener<Object> receiver) { StoreProvider<Object> provider = Directory.getRegistration(storeId, Object.class); provider.unsubscribe(receiver); Browser.close(receiver); } /** * Update server side data. * @param storeId The store into which data is to be altered/inserted. If * a store by the given name has not been registered then this method is * a no-op, however a message will be written to the log detailing the error * @param changes A list of changes to make to the objects in the store */ public <T> void update(String storeId, List<ItemUpdate> changes) { StoreProvider<Object> store = Directory.getRegistration(storeId, Object.class); if (store == null) { log.error("update() can't find any stores with storeId=" + storeId); throw new NullPointerException("Invalid store"); } store.update(changes); } /** * The log stream */ private static final Log log = LogFactory.getLog(Data.class); }
TheOpenCloudEngine/metaworks
metaworks-dwr/core/impl/main/java/org/directwebremoting/export/Data.java
Java
mit
5,172
require "heroku/command/base" require "heroku/helpers/log_displayer" # run one-off commands (console, rake) # class Heroku::Command::Run < Heroku::Command::Base # run:detached COMMAND # # run a detached dyno, where output is sent to your logs # # -s, --size SIZE # specify dyno size # -t, --tail # stream logs for the dyno # #Example: # # $ heroku run:detached ls # Running `ls` detached... up, run.1 # Use `heroku logs -p run.1` to view the output. # def detached command = args.join(" ") error("Usage: heroku run COMMAND") if command.empty? opts = { :attach => false, :command => command } opts[:size] = options[:size] if options[:size] app_name = app process_data = action("Running `#{command}` detached", :success => "up") do process_data = api.post_ps(app_name, command, opts).body status(process_data['process']) process_data end if options[:tail] opts = [] opts << "tail=1" opts << "ps=#{process_data['process']}" log_displayer = ::Heroku::Helpers::LogDisplayer.new(heroku, app, opts) log_displayer.display_logs else display("Use `heroku logs -p #{process_data['process']} -a #{app_name}` to view the output.") end end # run:rake COMMAND # # WARNING: `heroku run:rake` has been deprecated. Please use `heroku run rake` instead." # # remotely execute a rake command # #Example: # # $ heroku run:rake -T # Running `rake -T` attached to terminal... up, run.1 # (in /app) # rake test # run tests # def rake deprecate("`heroku #{current_command}` has been deprecated. Please use `heroku run rake` instead.") command = "rake #{args.join(' ')}" run_attached(command) end alias_command "rake", "run:rake" # HIDDEN: run:console [COMMAND] # # open a remote console session # # if COMMAND is specified, run the command and exit # # NOTE: For Cedar apps, use `heroku run console` # #Examples: # # $ heroku console # Ruby console for example.heroku.com # >> # def console puts "`heroku #{current_command}` has been removed. Please use: `heroku run` instead." puts "For more information, please see:" puts " * https://devcenter.heroku.com/articles/one-off-dynos" puts " * https://devcenter.heroku.com/articles/rails3#console" puts " * https://devcenter.heroku.com/articles/console-bamboo" end alias_command "console", "run:console" protected def run_attached(command) app_name = app opts = { :attach => true, :ps_env => get_terminal_environment } opts[:size] = options[:size] if options[:size] process_data = action("Running `#{command}` attached to terminal", :success => "up") do process_data = api.post_ps(app_name, command, opts).body status(process_data["process"]) process_data end rendezvous_session(process_data["rendezvous_url"]) end def rendezvous_session(rendezvous_url, &on_connect) begin set_buffer(false) rendezvous = Heroku::Client::Rendezvous.new( :rendezvous_url => rendezvous_url, :connect_timeout => (ENV["HEROKU_CONNECT_TIMEOUT"] || 120).to_i, :activity_timeout => nil, :input => $stdin, :output => $stdout) rendezvous.on_connect(&on_connect) rendezvous.start rescue Timeout::Error, Errno::ETIMEDOUT error "\nTimeout awaiting dyno, see https://devcenter.heroku.com/articles/one-off-dynos#timeout-awaiting-process" rescue OpenSSL::SSL::SSLError error "\nSSL error connecting to dyno." rescue Errno::ECONNREFUSED, Errno::ECONNRESET error "\nError connecting to dyno, see https://devcenter.heroku.com/articles/one-off-dynos#timeout-awaiting-process" rescue Interrupt ensure set_buffer(true) end end end
heroku/heroku
lib/heroku/command/run.rb
Ruby
mit
3,828
(function(){ if(!window.Prism) { return; } function $$(expr, con) { return Array.prototype.slice.call((con || document).querySelectorAll(expr)); } var CRLF = crlf = /\r?\n|\r/g; function highlightLines(pre, lines, classes) { var ranges = lines.replace(/\s+/g, '').split(','), offset = +pre.getAttribute('data-line-offset') || 0; var lineHeight = parseFloat(getComputedStyle(pre).lineHeight); for (var i=0, range; range = ranges[i++];) { range = range.split('-'); var start = +range[0], end = +range[1] || start; var line = document.createElement('div'); line.textContent = Array(end - start + 2).join(' \r\n'); line.className = (classes || '') + ' line-highlight'; line.setAttribute('data-start', start); if(end > start) { line.setAttribute('data-end', end); } line.style.top = (start - offset - 1) * lineHeight + 'px'; (pre.querySelector('code') || pre).appendChild(line); } } function applyHash() { var hash = location.hash.slice(1); // Remove pre-existing temporary lines $$('.temporary.line-highlight').forEach(function (line) { line.parentNode.removeChild(line); }); var range = (hash.match(/\.([\d,-]+)$/) || [,''])[1]; if (!range || document.getElementById(hash)) { return; } var id = hash.slice(0, hash.lastIndexOf('.')), pre = document.getElementById(id); if (!pre) { return; } if (!pre.hasAttribute('data-line')) { pre.setAttribute('data-line', ''); } highlightLines(pre, range, 'temporary '); document.querySelector('.temporary.line-highlight').scrollIntoView(); } var fakeTimer = 0; // Hack to limit the number of times applyHash() runs Prism.hooks.add('after-highlight', function(env) { var pre = env.element.parentNode; var lines = pre && pre.getAttribute('data-line'); if (!pre || !lines || !/pre/i.test(pre.nodeName)) { return; } clearTimeout(fakeTimer); $$('.line-highlight', pre).forEach(function (line) { line.parentNode.removeChild(line); }); highlightLines(pre, lines); fakeTimer = setTimeout(applyHash, 1); }); addEventListener('hashchange', applyHash); })();
inergex/meetups
2014Q2/bower_components/prismjs/plugins/line-highlight/prism-line-highlight.js
JavaScript
mit
2,089
module Shoulda module Matchers module ActiveRecord module AssociationMatchers # @private class OptionVerifier delegate :reflection, to: :reflector DEFAULT_VALUE_OF_OPTIONS = { has_many: { validate: true, }, }.freeze RELATION_OPTIONS = [:conditions, :order].freeze def initialize(reflector) @reflector = reflector end def correct_for_string?(name, expected_value) correct_for?(:string, name, expected_value) end def correct_for_boolean?(name, expected_value) correct_for?(:boolean, name, expected_value) end def correct_for_hash?(name, expected_value) correct_for?(:hash, name, expected_value) end def correct_for_constant?(name, expected_unresolved_value) correct_for?(:constant, name, expected_unresolved_value) end def correct_for_relation_clause?(name, expected_value) correct_for?(:relation_clause, name, expected_value) end def correct_for?(*args) expected_value, name, type = args.reverse if expected_value.nil? true else type_cast_expected_value = type_cast( type, expected_value_for(type, name, expected_value), ) actual_value = type_cast(type, actual_value_for(name)) type_cast_expected_value == actual_value end end def actual_value_for(name) if RELATION_OPTIONS.include?(name) actual_value_for_relation_clause(name) else method_name = "actual_value_for_#{name}" if respond_to?(method_name, true) __send__(method_name) else actual_value_for_option(name) end end end protected attr_reader :reflector def type_cast(type, value) case type when :string, :relation_clause value.to_s when :boolean !!value when :hash Hash(value).stringify_keys else value end end def expected_value_for(type, name, value) if RELATION_OPTIONS.include?(name) expected_value_for_relation_clause(name, value) elsif type == :constant expected_value_for_constant(value) else value end end def expected_value_for_relation_clause(name, value) relation = reflector.build_relation_with_clause(name, value) reflector.extract_relation_clause_from(relation, name) end def expected_value_for_constant(name) namespace = Shoulda::Matchers::Util.deconstantize( reflector.model_class.to_s, ) ["#{namespace}::#{name}", name].each do |path| constant = Shoulda::Matchers::Util.safe_constantize(path) if constant return constant end end end def actual_value_for_relation_clause(name) reflector.extract_relation_clause_from( reflector.association_relation, name, ) end def actual_value_for_class_name reflector.associated_class end def actual_value_for_option(name) option_value = reflection.options[name] if option_value.nil? DEFAULT_VALUE_OF_OPTIONS.dig(reflection.macro, name) else option_value end end end end end end end
thoughtbot/shoulda-matchers
lib/shoulda/matchers/active_record/association_matchers/option_verifier.rb
Ruby
mit
3,920
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var path = require("path"); var fs = require("fs"); var minify = require("jsonminify"); var js_beautify = require("js-beautify").js_beautify; var css_beautify = require("js-beautify").css; var html_beautify = require("js-beautify").html; // Older versions of node have `existsSync` in the `path` module, not `fs`. Meh. fs.existsSync = fs.existsSync || path.existsSync; path.sep = path.sep || "/"; // The source file to be prettified, original source's path and some options. var tempPath = process.argv[2] || ""; var filePath = process.argv[3] || ""; var pluginFolder = path.dirname(__dirname); var sourceFolder = path.dirname(filePath); var options = { html: {}, css: {}, js: {} }; var jsbeautifyrcPath; // Try and get some persistent options from the plugin folder. if (fs.existsSync(jsbeautifyrcPath = pluginFolder + path.sep + ".jsbeautifyrc")) { setOptions(jsbeautifyrcPath, options); } // When a JSBeautify config file exists in the same directory as the source // file, any directory above, or the user's home folder, then use that // configuration to overwrite the default prefs. var sourceFolderParts = path.resolve(sourceFolder).split(path.sep); var pathsToLook = sourceFolderParts.map(function(value, key) { return sourceFolderParts.slice(0, key + 1).join(path.sep); }); // Start with the current directory first, end with the user's home folder. pathsToLook.reverse(); pathsToLook.push(getUserHome()); pathsToLook.some(function(pathToLook) { if (fs.existsSync(jsbeautifyrcPath = path.join(pathToLook, ".jsbeautifyrc"))) { setOptions(jsbeautifyrcPath, options); return true; } }); // Dump some diagnostics messages, parsed out by the plugin. console.log("Using prettify options: " + JSON.stringify(options, null, 2)); // Read the source file and, when complete, beautify the code. fs.readFile(tempPath, "utf8", function(err, data) { if (err) { return; } // Mark the output as being from this plugin. console.log("*** HTMLPrettify output ***"); if (isCSS(filePath, data)) { console.log(css_beautify(data, options["css"])); } else if (isHTML(filePath, data)) { console.log(html_beautify(data, options["html"])); } else if (isJS(filePath, data)) { console.log(js_beautify(data, options["js"])); } }); // Some handy utility functions. function isTrue(value) { return value == "true" || value == true; } function getUserHome() { return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE; } function parseJSON(file) { try { return JSON.parse(minify(fs.readFileSync(file, "utf8"))); } catch (e) { console.log("Could not parse JSON at: " + file); return {}; } } function setOptions(file, optionsStore) { var obj = parseJSON(file); for (var key in obj) { var value = obj[key]; // Options are defined as an object for each format, with keys as prefs. if (key != "html" && key != "css" && key != "js") { continue; } for (var pref in value) { // Special case "true" and "false" pref values as actually booleans. // This avoids common accidents in .jsbeautifyrc json files. if (value == "true" || value == "false") { optionsStore[key][pref] = isTrue(value[pref]); } else { optionsStore[key][pref] = value[pref]; } } } } // Checks if a file type is allowed by regexing the file name and expecting a // certain extension loaded from the settings file. function isTypeAllowed(type, path) { var allowedFileExtensions = options[type]["allowed_file_extensions"] || { "html": ["htm", "html", "xhtml", "shtml", "xml", "svg"], "css": ["css", "scss", "sass", "less"], "js": ["js", "json", "jshintrc", "jsbeautifyrc"] }[type]; for (var i = 0, len = allowedFileExtensions.length; i < len; i++) { if (path.match(new RegExp("\\." + allowedFileExtensions[i] + "$"))) { return true; } } return false; } function isCSS(path, data) { // If file unsaved, there's no good way to determine whether or not it's // CSS based on the file contents. if (path == "?") { return false; } return isTypeAllowed("css", path); } function isHTML(path, data) { // If file unsaved, check if first non-whitespace character is &lt; if (path == "?") { return data.match(/^\s*</); } return isTypeAllowed("html", path); } function isJS(path, data) { // If file unsaved, check if first non-whitespace character is NOT &lt; if (path == "?") { return !data.match(/^\s*</); } return isTypeAllowed("js", path); }
micahwood/linux-dotfiles
sublime/Packages/HTML-CSS-JS Prettify/scripts/run.js
JavaScript
mit
4,755
<?php $env = new Twig_Environment(new Twig_Loader_Array([])); $env->addFilter(new Twig_SimpleFilter('anonymous', function () {})); return $env;
frisbeesport/frisbeesport.nl
vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/FilterInclude.php
PHP
mit
146
package saberapplications.pawpads.service; import android.app.IntentService; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.webkit.MimeTypeMap; import android.widget.Toast; import com.quickblox.chat.model.QBAttachment; import com.quickblox.content.QBContent; import com.quickblox.content.model.QBFile; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import saberapplications.pawpads.R; public class FileDownloadService extends IntentService { private static Handler handler; public FileDownloadService() { super("FileDownloadService"); } public static final String ATTACHMENT_NAME="attachement_name"; public static final String ATTACHMENT_ID="attachement_id"; public static void startService(Context context, QBAttachment attachment) { Intent intent = new Intent(context, FileDownloadService.class); intent.putExtra(ATTACHMENT_ID,attachment.getId()); //attachment.getName() + attachment.getType() intent.putExtra(ATTACHMENT_NAME,attachment.getName()); context.startService(intent); handler=new Handler(); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { try { String fileId=intent.getStringExtra(ATTACHMENT_ID); final String fileName=intent.getStringExtra(ATTACHMENT_NAME); if (fileId==null) return; File targetFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName); if (!targetFile.exists()) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(FileDownloadService.this, R.string.download_started,Toast.LENGTH_LONG).show(); } }); QBFile file = QBContent.getFile(Integer.parseInt(fileId)); URL u = new URL(file.getPrivateUrl()); InputStream inputStream = u.openStream(); OutputStream outStream = new FileOutputStream(targetFile); byte[] buffer = new byte[1024 * 100]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } } MimeTypeMap myMime = MimeTypeMap.getSingleton(); Intent newIntent = new Intent(Intent.ACTION_VIEW); String mimeType = myMime.getMimeTypeFromExtension(fileExt(fileName)); newIntent.setDataAndType(Uri.fromFile(targetFile),mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(newIntent); } catch (ActivityNotFoundException e) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(FileDownloadService.this, R.string.file_downloaded, Toast.LENGTH_LONG).show(); } }); } } catch (final IOException e) { e.printStackTrace(); handler.post(new Runnable() { @Override public void run() { Toast.makeText(FileDownloadService.this,e.getLocalizedMessage(),Toast.LENGTH_LONG).show(); } }); } } } private String fileExt(String url) { if (url.indexOf("?") > -1) { url = url.substring(0, url.indexOf("?")); } if (url.lastIndexOf(".") == -1) { return null; } else { String ext = url.substring(url.lastIndexOf(".") + 1); if (ext.indexOf("%") > -1) { ext = ext.substring(0, ext.indexOf("%")); } if (ext.indexOf("/") > -1) { ext = ext.substring(0, ext.indexOf("/")); } return ext.toLowerCase(); } } }
castaway2000/Pawpads
app/src/main/java/saberapplications/pawpads/service/FileDownloadService.java
Java
mit
4,649
<?php /** phpSec - A PHP security library @author Audun Larsen <larsen@xqus.com> @copyright Copyright (c) Audun Larsen, 2011, 2012 @link https://github.com/phpsec/phpSec @license http://opensource.org/licenses/mit-license.php The MIT License @package phpSec */ namespace phpSec\Auth; /** * Provides one time password functionality. * @package phpSec */ class Otp { public $_charset = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** * phpSec core Pimple container. */ private $psl = null; /** * Constructor. * * @param \phpSec\Core $psl * phpSec core Pimple container. */ public function __construct(\phpSec\Core $psl) { $this->psl = $psl; } /** * Generate a one-time-password (OTP). The password is only valid for a given time, * and must be delivered to the user instantly. The password is also only valid * for the current session. * * @param string $action * The action to generate a OTP for. This should be as specific as possible. * Used to ensure that the OTP is used for the intended action. * * @param string $uid * User identifier. Default is a session identifier. Can be set to a username or user id * if you want the OTP to be valid outside the session active when creating it. * * @param array $data * Optional array of data that belongs to $action. Used to ensure that the action * is performed with the same data as when the OTP was generated. * * @param integer $length * OTP length. * * @param integer $ttl * Time to live for the OTP. In seconds. * * @return string * One time password that should be delivered to the user by for example email or SMS. * */ public function generate($action, $uid = null, $data = null, $length = 6, $ttl = 480) { $rand = $this->psl['crypt/rand']; $hash = $this->psl['crypt/hash']; $store = $this->psl['store']; if($uid === null) { $uid = $this->psl->getUid(); } $pw = $rand->str($length, $this->_charset); $otp['pw'] = $hash->create($pw); $otp['data'] = $hash->create(serialize($data)); $otp['ttl'] = time() + $ttl; if($store->write('otp', $this->storeId($uid, $action), $otp)) { return $pw; } return false; } /** * Validate a one-time-password. * * @param strgin $otp * OTP supplied by user. * * @param string $action * See phpsecOtp::generate(). * * @param string $uid * See phpsecOtp::generate(). * * @param array $data * See phpsecOtp::generate(). * */ public function validate($otp, $action, $uid = null, $data = null) { $hash = $this->psl['crypt/hash']; $store = $this->psl['store']; if($uid === null) { $uid = $this->psl->getUid(); } $storeData = $store->read('otp', $this->storeId($uid, $action)); if($storeData !== false) { if($storeData['ttl'] < time()) { $store->delete('otp', $this->storeId($uid, $action)); return false; } if($hash->check($otp, $storeData['pw']) && $hash->check(serialize($data), $storeData['data'])) { $store->delete('otp', $this->storeId($uid, $action)); return true; } } return false; } private function storeId($uid, $action) { return hash('sha512', $uid.$action); } }
phpsec/phpSec
lib/phpSec/Auth/Otp.php
PHP
mit
3,380
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include <map> #include <boost/version.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <leveldb/env.h> #include <leveldb/cache.h> #include <leveldb/filter_policy.h> #include <memenv/memenv.h> #include "kernel.h" #include "checkpoints.h" #include "txdb.h" #include "util.h" #include "main.h" #include "chainparams.h" using namespace std; using namespace boost; leveldb::DB *txdb; // global pointer for LevelDB object instance static leveldb::Options GetOptions() { leveldb::Options options; int nCacheSizeMB = GetArg("-dbcache", 25); options.block_cache = leveldb::NewLRUCache(nCacheSizeMB * 1048576); options.filter_policy = leveldb::NewBloomFilterPolicy(10); return options; } void init_blockindex(leveldb::Options& options, bool fRemoveOld = false) { // First time init. filesystem::path directory = GetDataDir() / "txleveldb"; if (fRemoveOld) { filesystem::remove_all(directory); // remove directory unsigned int nFile = 1; while (true) { filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile); // Break if no such file if( !filesystem::exists( strBlockFile ) ) break; filesystem::remove(strBlockFile); nFile++; } } filesystem::create_directory(directory); LogPrintf("Opening LevelDB in %s\n", directory.string()); leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb); if (!status.ok()) { throw runtime_error(strprintf("init_blockindex(): error opening database environment %s", status.ToString())); } } // CDB subclasses are created and destroyed VERY OFTEN. That's why // we shouldn't treat this as a free operations. CTxDB::CTxDB(const char* pszMode) { assert(pszMode); activeBatch = NULL; fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w')); if (txdb) { pdb = txdb; return; } bool fCreate = strchr(pszMode, 'c'); options = GetOptions(); options.create_if_missing = fCreate; options.filter_policy = leveldb::NewBloomFilterPolicy(10); init_blockindex(options); // Init directory pdb = txdb; if (Exists(string("version"))) { ReadVersion(nVersion); LogPrintf("Transaction index version is %d\n", nVersion); if (nVersion < DATABASE_VERSION) { LogPrintf("Required index version is %d, removing old database\n", DATABASE_VERSION); // Leveldb instance destruction delete txdb; txdb = pdb = NULL; delete activeBatch; activeBatch = NULL; init_blockindex(options, true); // Remove directory and create new database pdb = txdb; bool fTmp = fReadOnly; fReadOnly = false; WriteVersion(DATABASE_VERSION); // Save transaction index version fReadOnly = fTmp; } } else if (fCreate) { bool fTmp = fReadOnly; fReadOnly = false; WriteVersion(DATABASE_VERSION); fReadOnly = fTmp; } LogPrintf("Opened LevelDB successfully\n"); } void CTxDB::Close() { delete txdb; txdb = pdb = NULL; delete options.filter_policy; options.filter_policy = NULL; delete options.block_cache; options.block_cache = NULL; delete activeBatch; activeBatch = NULL; } bool CTxDB::TxnBegin() { assert(!activeBatch); activeBatch = new leveldb::WriteBatch(); return true; } bool CTxDB::TxnCommit() { assert(activeBatch); leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch); delete activeBatch; activeBatch = NULL; if (!status.ok()) { LogPrintf("LevelDB batch commit failure: %s\n", status.ToString()); return false; } return true; } class CBatchScanner : public leveldb::WriteBatch::Handler { public: std::string needle; bool *deleted; std::string *foundValue; bool foundEntry; CBatchScanner() : foundEntry(false) {} virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) { if (key.ToString() == needle) { foundEntry = true; *deleted = false; *foundValue = value.ToString(); } } virtual void Delete(const leveldb::Slice& key) { if (key.ToString() == needle) { foundEntry = true; *deleted = true; } } }; // When performing a read, if we have an active batch we need to check it first // before reading from the database, as the rest of the code assumes that once // a database transaction begins reads are consistent with it. It would be good // to change that assumption in future and avoid the performance hit, though in // practice it does not appear to be large. bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const { assert(activeBatch); *deleted = false; CBatchScanner scanner; scanner.needle = key.str(); scanner.deleted = deleted; scanner.foundValue = value; leveldb::Status status = activeBatch->Iterate(&scanner); if (!status.ok()) { throw runtime_error(status.ToString()); } return scanner.foundEntry; } bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex) { txindex.SetNull(); return Read(make_pair(string("tx"), hash), txindex); } bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex) { return Write(make_pair(string("tx"), hash), txindex); } bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight) { // Add to tx index uint256 hash = tx.GetHash(); CTxIndex txindex(pos, tx.vout.size()); return Write(make_pair(string("tx"), hash), txindex); } bool CTxDB::EraseTxIndex(const CTransaction& tx) { uint256 hash = tx.GetHash(); return Erase(make_pair(string("tx"), hash)); } bool CTxDB::ContainsTx(uint256 hash) { return Exists(make_pair(string("tx"), hash)); } bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex) { tx.SetNull(); if (!ReadTxIndex(hash, txindex)) return false; return (tx.ReadFromDisk(txindex.pos)); } bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx) { CTxIndex txindex; return ReadDiskTx(hash, tx, txindex); } bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex) { return ReadDiskTx(outpoint.hash, tx, txindex); } bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx) { CTxIndex txindex; return ReadDiskTx(outpoint.hash, tx, txindex); } bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex) { return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex); } bool CTxDB::ReadHashBestChain(uint256& hashBestChain) { return Read(string("hashBestChain"), hashBestChain); } bool CTxDB::WriteHashBestChain(uint256 hashBestChain) { return Write(string("hashBestChain"), hashBestChain); } bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust) { return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust); } bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust) { return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust); } bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint) { return Read(string("hashSyncCheckpoint"), hashCheckpoint); } bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint) { return Write(string("hashSyncCheckpoint"), hashCheckpoint); } bool CTxDB::ReadCheckpointPubKey(string& strPubKey) { return Read(string("strCheckpointPubKey"), strPubKey); } bool CTxDB::WriteCheckpointPubKey(const string& strPubKey) { return Write(string("strCheckpointPubKey"), strPubKey); } static CBlockIndex *InsertBlockIndex(uint256 hash) { if (hash == 0) return NULL; // Return existing map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) return (*mi).second; // Create new CBlockIndex* pindexNew = new CBlockIndex(); if (!pindexNew) throw runtime_error("LoadBlockIndex() : new CBlockIndex failed"); mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); return pindexNew; } bool CTxDB::LoadBlockIndex() { if (mapBlockIndex.size() > 0) { // Already loaded once in this session. It can happen during migration // from BDB. return true; } // The block index is an in-memory structure that maps hashes to on-disk // locations where the contents of the block can be found. Here, we scan it // out of the DB and into mapBlockIndex. leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions()); // Seek to start key. CDataStream ssStartKey(SER_DISK, CLIENT_VERSION); ssStartKey << make_pair(string("blockindex"), uint256(0)); iterator->Seek(ssStartKey.str()); // Now read each entry. while (iterator->Valid()) { boost::this_thread::interruption_point(); // Unpack keys and values. CDataStream ssKey(SER_DISK, CLIENT_VERSION); ssKey.write(iterator->key().data(), iterator->key().size()); CDataStream ssValue(SER_DISK, CLIENT_VERSION); ssValue.write(iterator->value().data(), iterator->value().size()); string strType; ssKey >> strType; // Did we reach the end of the data to read? if (strType != "blockindex") break; CDiskBlockIndex diskindex; ssValue >> diskindex; uint256 blockHash = diskindex.GetBlockHash(); // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(blockHash); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); pindexNew->pnext = InsertBlockIndex(diskindex.hashNext); pindexNew->nFile = diskindex.nFile; pindexNew->nBlockPos = diskindex.nBlockPos; pindexNew->nHeight = diskindex.nHeight; pindexNew->nMint = diskindex.nMint; pindexNew->nMoneySupply = diskindex.nMoneySupply; pindexNew->nFlags = diskindex.nFlags; pindexNew->nStakeModifier = diskindex.nStakeModifier; pindexNew->prevoutStake = diskindex.prevoutStake; pindexNew->nStakeTime = diskindex.nStakeTime; pindexNew->hashProof = diskindex.hashProof; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; // Watch for genesis block if (pindexGenesisBlock == NULL && blockHash == Params().HashGenesisBlock()) pindexGenesisBlock = pindexNew; if (!pindexNew->CheckIndex()) { delete iterator; return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight); } // xRadon: build setStakeSeen if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); iterator->Next(); } delete iterator; boost::this_thread::interruption_point(); // Calculate nChainTrust vector<pair<int, CBlockIndex*> > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) { CBlockIndex* pindex = item.second; pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust(); } // Load hashBestChain pointer to end of best chain if (!ReadHashBestChain(hashBestChain)) { if (pindexGenesisBlock == NULL) return true; return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded"); } if (!mapBlockIndex.count(hashBestChain)) return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index"); pindexBest = mapBlockIndex[hashBestChain]; nBestHeight = pindexBest->nHeight; nBestChainTrust = pindexBest->nChainTrust; LogPrintf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n", hashBestChain.ToString(), nBestHeight, CBigNum(nBestChainTrust).ToString(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime())); // xRadon: load hashSyncCheckpoint if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint)) return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded"); LogPrintf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString()); // Load bnBestInvalidTrust, OK if it doesn't exist CBigNum bnBestInvalidTrust; ReadBestInvalidTrust(bnBestInvalidTrust); nBestInvalidTrust = bnBestInvalidTrust.getuint256(); // Verify blocks in the best chain int nCheckLevel = GetArg("-checklevel", 1); int nCheckDepth = GetArg( "-checkblocks", 500); if (nCheckDepth == 0) nCheckDepth = 1000000000; // suffices until the year 19000 if (nCheckDepth > nBestHeight) nCheckDepth = nBestHeight; LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); CBlockIndex* pindexFork = NULL; map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos; for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); if (pindex->nHeight < nBestHeight-nCheckDepth) break; CBlock block; if (!block.ReadFromDisk(pindex)) return error("LoadBlockIndex() : block.ReadFromDisk failed"); // check level 1: verify block validity // check level 7: verify block signature too if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6))) { LogPrintf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); pindexFork = pindex->pprev; } // check level 2: verify transaction index validity if (nCheckLevel>1) { pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos); mapBlockPos[pos] = pindex; BOOST_FOREACH(const CTransaction &tx, block.vtx) { uint256 hashTx = tx.GetHash(); CTxIndex txindex; if (ReadTxIndex(hashTx, txindex)) { // check level 3: checker transaction hashes if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos) { // either an error or a duplicate transaction CTransaction txFound; if (!txFound.ReadFromDisk(txindex.pos)) { LogPrintf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString()); pindexFork = pindex->pprev; } else if (txFound.GetHash() != hashTx) // not a duplicate tx { LogPrintf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString()); pindexFork = pindex->pprev; } } // check level 4: check whether spent txouts were spent within the main chain unsigned int nOutput = 0; if (nCheckLevel>3) { BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent) { if (!txpos.IsNull()) { pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos); if (!mapBlockPos.count(posFind)) { LogPrintf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString(), hashTx.ToString()); pindexFork = pindex->pprev; } // check level 6: check whether spent txouts were spent by a valid transaction that consume them if (nCheckLevel>5) { CTransaction txSpend; if (!txSpend.ReadFromDisk(txpos)) { LogPrintf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString(), nOutput); pindexFork = pindex->pprev; } else if (!txSpend.CheckTransaction()) { LogPrintf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString(), nOutput); pindexFork = pindex->pprev; } else { bool fFound = false; BOOST_FOREACH(const CTxIn &txin, txSpend.vin) if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput) fFound = true; if (!fFound) { LogPrintf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString(), nOutput); pindexFork = pindex->pprev; } } } } nOutput++; } } } // check level 5: check whether all prevouts are marked spent if (nCheckLevel>4) { BOOST_FOREACH(const CTxIn &txin, tx.vin) { CTxIndex txindex; if (ReadTxIndex(txin.prevout.hash, txindex)) if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull()) { LogPrintf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString(), txin.prevout.n, hashTx.ToString()); pindexFork = pindex->pprev; } } } } } } if (pindexFork) { boost::this_thread::interruption_point(); // Reorg back to the fork LogPrintf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight); CBlock block; if (!block.ReadFromDisk(pindexFork)) return error("LoadBlockIndex() : block.ReadFromDisk failed"); CTxDB txdb; block.SetBestChain(txdb, pindexFork); } return true; }
Bitspender/h10
src/txdb-leveldb.cpp
C++
mit
20,331
package com.yunstudio.struts.listener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.yunstudio.service.AdminService; public class SessionListener implements HttpSessionAttributeListener,HttpSessionListener{ private AdminService adminService; public void attributeAdded(HttpSessionBindingEvent se) { // TODO Auto-generated method stub } public void attributeRemoved(HttpSessionBindingEvent se) { // TODO Auto-generated method stub // WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(se.getSession().getServletContext()); // adminService=(AdminService) wac.getBean("adminService"); } public void attributeReplaced(HttpSessionBindingEvent se) { // TODO Auto-generated method stub } public void sessionCreated(HttpSessionEvent se) { // TODO Auto-generated method stub } public void sessionDestroyed(HttpSessionEvent se) { // WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(se.getSession().getServletContext()); // adminService=(AdminService) wac.getBean("adminService"); } }
binghuo365/csustRepo
trunk/src/com/yunstudio/struts/listener/SessionListener.java
Java
mit
1,268
import copy from collections import OrderedDict from collections import defaultdict from conans.model.env_info import EnvValues from conans.model.options import OptionsValues from conans.model.values import Values class Profile(object): """A profile contains a set of setting (with values), environment variables """ def __init__(self): # Sections self.settings = OrderedDict() self.package_settings = defaultdict(OrderedDict) self.env_values = EnvValues() self.options = OptionsValues() self.build_requires = OrderedDict() # conan_ref Pattern: list of conan_ref @property def settings_values(self): return Values.from_list(list(self.settings.items())) @property def package_settings_values(self): result = {} for pkg, settings in self.package_settings.items(): result[pkg] = list(settings.items()) return result def dumps(self): result = ["[settings]"] for name, value in self.settings.items(): result.append("%s=%s" % (name, value)) for package, values in self.package_settings.items(): for name, value in values.items(): result.append("%s:%s=%s" % (package, name, value)) result.append("[options]") result.append(self.options.dumps()) result.append("[build_requires]") for pattern, req_list in self.build_requires.items(): result.append("%s: %s" % (pattern, ", ".join(str(r) for r in req_list))) result.append("[env]") result.append(self.env_values.dumps()) return "\n".join(result).replace("\n\n", "\n") def update(self, other): self.update_settings(other.settings) self.update_package_settings(other.package_settings) # this is the opposite other.env_values.update(self.env_values) self.env_values = other.env_values self.options.update(other.options) for pattern, req_list in other.build_requires.items(): self.build_requires.setdefault(pattern, []).extend(req_list) def update_settings(self, new_settings): """Mix the specified settings with the current profile. Specified settings are prioritized to profile""" assert(isinstance(new_settings, OrderedDict)) # apply the current profile res = copy.copy(self.settings) if new_settings: # Invalidate the current subsettings if the parent setting changes # Example: new_settings declare a different "compiler", so invalidate the current "compiler.XXX" for name, value in new_settings.items(): if "." not in name: if name in self.settings and self.settings[name] != value: for cur_name, _ in self.settings.items(): if cur_name.startswith("%s." % name): del res[cur_name] # Now merge the new values res.update(new_settings) self.settings = res def update_package_settings(self, package_settings): """Mix the specified package settings with the specified profile. Specified package settings are prioritized to profile""" for package_name, settings in package_settings.items(): self.package_settings[package_name].update(settings)
birsoyo/conan
conans/model/profile.py
Python
mit
3,409
namespace AngleSharp.Network { using AngleSharp.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Net; /// <summary> /// The virtual response class. /// </summary> public class VirtualResponse : IResponse { #region Fields private Url _address; private HttpStatusCode _status; private Dictionary<String, String> _headers; private Stream _content; private Boolean _dispose; #endregion #region ctor private VirtualResponse() { _address = Url.Create("http://localhost/"); _status = HttpStatusCode.OK; _headers = new Dictionary<String, String>(); _content = MemoryStream.Null; _dispose = false; } /// <summary> /// Creates a new virtual response. /// </summary> /// <param name="request">The request callback.</param> /// <returns>The resulted response.</returns> public static IResponse Create(Action<VirtualResponse> request) { var vr = new VirtualResponse(); request(vr); return vr; } #endregion #region Properties Url IResponse.Address { get { return _address; } } Stream IResponse.Content { get { return _content; } } IDictionary<String, String> IResponse.Headers { get { return _headers; } } HttpStatusCode IResponse.StatusCode { get { return _status; } } #endregion #region Methods /// <summary> /// Sets the location of the response to the given url. /// </summary> /// <param name="url">The imaginary url of the response.</param> /// <returns>The current instance.</returns> public VirtualResponse Address(Url url) { _address = url; return this; } /// <summary> /// Sets the location of the response to the provided address. /// </summary> /// <param name="address">The string to use as an url.</param> /// <returns>The current instance.</returns> public VirtualResponse Address(String address) { return Address(Url.Create(address ?? String.Empty)); } /// <summary> /// Sets the location of the response to the uri's value. /// </summary> /// <param name="url">The Uri instance to convert.</param> /// <returns>The current instance.</returns> public VirtualResponse Address(Uri url) { return Address(Url.Convert(url)); } /// <summary> /// Sets the status code. /// </summary> /// <param name="code">The status code to set.</param> /// <returns>The current instance.</returns> public VirtualResponse Status(HttpStatusCode code) { _status = code; return this; } /// <summary> /// Sets the status code by providing the integer value. /// </summary> /// <param name="code">The integer representing the code.</param> /// <returns>The current instance.</returns> public VirtualResponse Status(Int32 code) { return Status((HttpStatusCode)code); } /// <summary> /// Sets the header with the given name and value. /// </summary> /// <param name="name">The header name to set.</param> /// <param name="value">The value for the key.</param> /// <returns>The current instance.</returns> public VirtualResponse Header(String name, String value) { _headers[name] = value; return this; } /// <summary> /// Sets the headers with the name of the properties and their /// assigned values. /// </summary> /// <param name="obj">The object to decompose.</param> /// <returns>The current instance.</returns> public VirtualResponse Headers(Object obj) { var headers = obj.ToDictionary(); return Headers(headers); } /// <summary> /// Sets the headers with the name of the keys and their assigned /// values. /// </summary> /// <param name="headers">The dictionary to use.</param> /// <returns>The current instance.</returns> public VirtualResponse Headers(IDictionary<String, String> headers) { foreach (var header in headers) { Header(header.Key, header.Value); } return this; } /// <summary> /// Sets the response's content from the provided string. /// </summary> /// <param name="text">The text to use as content.</param> /// <returns>The current instance.</returns> public VirtualResponse Content(String text) { Release(); var raw = TextEncoding.Utf8.GetBytes(text); _content = new MemoryStream(raw); _dispose = true; return this; } /// <summary> /// Sets the response's content from the provided stream. /// </summary> /// <param name="stream">The response's content stream.</param> /// <param name="shouldDispose">True to dispose afterwards.</param> /// <returns>The current instance.</returns> public VirtualResponse Content(Stream stream, Boolean shouldDispose = false) { Release(); _content = stream; _dispose = shouldDispose; return this; } #endregion #region Helpers private void Release() { if (_dispose) { _content?.Dispose(); } _dispose = false; _content = null; } void IDisposable.Dispose() { Release(); } #endregion } }
FlorianRappl/AngleSharp
src/AngleSharp/Network/VirtualResponse.cs
C#
mit
6,196
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { deepmerge } from '@material-ui/utils'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import Modal from '../Modal'; import Slide from '../Slide'; import Paper from '../Paper'; import capitalize from '../utils/capitalize'; import { duration } from '../styles/transitions'; import useTheme from '../styles/useTheme'; import useThemeProps from '../styles/useThemeProps'; import experimentalStyled from '../styles/experimentalStyled'; import drawerClasses, { getDrawerUtilityClass } from './drawerClasses'; const overridesResolver = (props, styles) => { const { styleProps } = props; return deepmerge(_extends({}, (styleProps.variant === 'permanent' || styleProps.variant === 'persistent') && styles.docked, styles.modal, { [`& .${drawerClasses.paper}`]: _extends({}, styles.paper, styles[`paperAnchor${capitalize(styleProps.anchor)}`], styleProps.variant !== 'temporary' && styles[`paperAnchorDocked${capitalize(styleProps.anchor)}`]) }), styles.root || {}); }; const useUtilityClasses = styleProps => { const { classes, anchor, variant } = styleProps; const slots = { root: ['root'], docked: [(variant === 'permanent' || variant === 'persistent') && 'docked'], modal: ['modal'], paper: ['paper', `paperAnchor${capitalize(anchor)}`, variant !== 'temporary' && `paperAnchorDocked${capitalize(anchor)}`] }; return composeClasses(slots, getDrawerUtilityClass, classes); }; const DrawerRoot = experimentalStyled(Modal, {}, { name: 'MuiDrawer', slot: 'Root', overridesResolver })({}); const DrawerDockedRoot = experimentalStyled('div', {}, { name: 'MuiDrawer', slot: 'Docked', overridesResolver })({ /* Styles applied to the root element if `variant="permanent or persistent"`. */ flex: '0 0 auto' }); const DrawerPaper = experimentalStyled(Paper, {}, { name: 'MuiDrawer', slot: 'Paper' })(({ theme, styleProps }) => _extends({ /* Styles applied to the Paper component. */ overflowY: 'auto', display: 'flex', flexDirection: 'column', height: '100%', flex: '1 0 auto', zIndex: theme.zIndex.drawer, WebkitOverflowScrolling: 'touch', // Add iOS momentum scrolling. // temporary style position: 'fixed', top: 0, // We disable the focus ring for mouse, touch and keyboard users. // At some point, it would be better to keep it for keyboard users. // :focus-ring CSS pseudo-class will help. outline: 0 }, styleProps.anchor === 'left' && { /* Styles applied to the Paper component if `anchor="left"`. */ left: 0, right: 'auto' }, styleProps.anchor === 'top' && { /* Styles applied to the Paper component if `anchor="top"`. */ top: 0, left: 0, bottom: 'auto', right: 0, height: 'auto', maxHeight: '100%' }, styleProps.anchor === 'right' && { /* Styles applied to the Paper component if `anchor="right"`. */ left: 'auto', right: 0 }, styleProps.anchor === 'bottom' && { /* Styles applied to the Paper component if `anchor="bottom"`. */ top: 'auto', left: 0, bottom: 0, right: 0, height: 'auto', maxHeight: '100%' }, styleProps.anchor === 'left' && styleProps.variant !== 'temporary' && { /* Styles applied to the Paper component if `anchor="left"` and `variant` is not "temporary". */ borderRight: `1px solid ${theme.palette.divider}` }, styleProps.anchor === 'top' && styleProps.variant !== 'temporary' && { /* Styles applied to the Paper component if `anchor="top"` and `variant` is not "temporary". */ borderBottom: `1px solid ${theme.palette.divider}` }, styleProps.anchor === 'right' && styleProps.variant !== 'temporary' && { /* Styles applied to the Paper component if `anchor="right"` and `variant` is not "temporary". */ borderLeft: `1px solid ${theme.palette.divider}` }, styleProps.anchor === 'bottom' && styleProps.variant !== 'temporary' && { /* Styles applied to the Paper component if `anchor="bottom"` and `variant` is not "temporary". */ borderTop: `1px solid ${theme.palette.divider}` })); const oppositeDirection = { left: 'right', right: 'left', top: 'down', bottom: 'up' }; export function isHorizontal(anchor) { return ['left', 'right'].indexOf(anchor) !== -1; } export function getAnchor(theme, anchor) { return theme.direction === 'rtl' && isHorizontal(anchor) ? oppositeDirection[anchor] : anchor; } const defaultTransitionDuration = { enter: duration.enteringScreen, exit: duration.leavingScreen }; /** * The props of the [Modal](/api/modal/) component are available * when `variant="temporary"` is set. */ const Drawer = /*#__PURE__*/React.forwardRef(function Drawer(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiDrawer' }); const { anchor: anchorProp = 'left', BackdropProps, children, className, elevation = 16, ModalProps: { BackdropProps: BackdropPropsProp } = {}, onClose, open = false, PaperProps = {}, SlideProps, // eslint-disable-next-line react/prop-types TransitionComponent = Slide, transitionDuration = defaultTransitionDuration, variant = 'temporary' } = props, ModalProps = _objectWithoutPropertiesLoose(props.ModalProps, ["BackdropProps"]), other = _objectWithoutPropertiesLoose(props, ["anchor", "BackdropProps", "children", "className", "elevation", "ModalProps", "onClose", "open", "PaperProps", "SlideProps", "TransitionComponent", "transitionDuration", "variant"]); const theme = useTheme(); // Let's assume that the Drawer will always be rendered on user space. // We use this state is order to skip the appear transition during the // initial mount of the component. const mounted = React.useRef(false); React.useEffect(() => { mounted.current = true; }, []); const anchor = getAnchor(theme, anchorProp); const styleProps = _extends({}, props, { anchor, elevation, open, variant }, other); const classes = useUtilityClasses(styleProps); const drawer = /*#__PURE__*/React.createElement(DrawerPaper, _extends({ elevation: variant === 'temporary' ? elevation : 0, square: true }, PaperProps, { className: clsx(classes.paper, PaperProps.className), styleProps: styleProps }), children); if (variant === 'permanent') { return /*#__PURE__*/React.createElement(DrawerDockedRoot, _extends({ className: clsx(classes.root, classes.docked, className), styleProps: styleProps, ref: ref }, other), drawer); } const slidingDrawer = /*#__PURE__*/React.createElement(TransitionComponent, _extends({ in: open, direction: oppositeDirection[anchor], timeout: transitionDuration, appear: mounted.current }, SlideProps), drawer); if (variant === 'persistent') { return /*#__PURE__*/React.createElement(DrawerDockedRoot, _extends({ className: clsx(classes.root, classes.docked, className), styleProps: styleProps, ref: ref }, other), slidingDrawer); } // variant === temporary return /*#__PURE__*/React.createElement(DrawerRoot, _extends({ BackdropProps: _extends({}, BackdropProps, BackdropPropsProp, { transitionDuration }), className: clsx(classes.root, classes.modal, className), open: open, styleProps: styleProps, onClose: onClose, ref: ref }, other, ModalProps), slidingDrawer); }); process.env.NODE_ENV !== "production" ? Drawer.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Side from which the drawer will appear. * @default 'left' */ anchor: PropTypes.oneOf(['bottom', 'left', 'right', 'top']), /** * @ignore */ BackdropProps: PropTypes.object, /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The elevation of the drawer. * @default 16 */ elevation: PropTypes.number, /** * Props applied to the [`Modal`](/api/modal/) element. * @default {} */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. */ onClose: PropTypes.func, /** * If `true`, the component is shown. * @default false */ open: PropTypes.bool, /** * Props applied to the [`Paper`](/api/paper/) element. * @default {} */ PaperProps: PropTypes.object, /** * Props applied to the [`Slide`](/api/slide/) element. */ SlideProps: PropTypes.object, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. * @default { enter: duration.enteringScreen, exit: duration.leavingScreen } */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number })]), /** * The variant to use. * @default 'temporary' */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']) } : void 0; export default Drawer;
cdnjs/cdnjs
ajax/libs/material-ui/5.0.0-alpha.27/modern/Drawer/Drawer.js
JavaScript
mit
9,817
/*++ Copyright (c) 2014 Microsoft Corporation Module Name: hitting_sets.h Abstract: Hitting set approximations. Author: Nikolaj Bjorner (nbjorner) 2014-06-06 Notes: --*/ #include "vector.h" #include "util.h" #include "hitting_sets.h" #include "simplex.h" #include "sparse_matrix_def.h" #include "simplex_def.h" typedef simplex::simplex<simplex::mpz_ext> Simplex; typedef simplex::sparse_matrix<simplex::mpz_ext> sparse_matrix; namespace opt { struct hitting_sets::imp { class justification { public: enum kind_t { AXIOM, DECISION, CLAUSE }; private: kind_t m_kind; unsigned m_value; bool m_pos; public: explicit justification(kind_t k):m_kind(k), m_value(0), m_pos(false) {} explicit justification(unsigned v, bool pos):m_kind(CLAUSE), m_value(v), m_pos(pos) {} justification(justification const& other): m_kind(other.m_kind), m_value(other.m_value), m_pos(other.m_pos) {} justification& operator=(justification const& other) { m_kind = other.m_kind; m_value = other.m_value; m_pos = other.m_pos; return *this; } unsigned clause() const { return m_value; } bool is_axiom() const { return m_kind == AXIOM; } bool is_decision() const { return m_kind == DECISION; } bool is_clause() const { return m_kind == CLAUSE; } kind_t kind() const { return m_kind; } bool pos() const { return m_pos; } }; class set { unsigned m_num_elems; unsigned m_elems[0]; set(): m_num_elems(0) {} public: static set* mk(small_object_allocator& alloc, unsigned sz, unsigned const* elems) { unsigned size = (sz+1)*sizeof(unsigned); void * mem = alloc.allocate(size); set* result = new (mem) set(); result->m_num_elems = sz; memcpy(result->m_elems, elems, sizeof(unsigned)*sz); return result; } inline unsigned operator[](unsigned idx) const { SASSERT(idx < m_num_elems); return m_elems[idx]; } inline unsigned& operator[](unsigned idx) { SASSERT(idx < m_num_elems); return m_elems[idx]; } unsigned size() const { return m_num_elems; } unsigned alloc_size() const { return (m_num_elems + 1)*sizeof(unsigned); } bool empty() const { return 0 == size(); } }; reslimit& m_limit; rational m_lower; rational m_upper; vector<rational> m_weights; vector<rational> m_weights_inv; rational m_max_weight; rational m_denominator; small_object_allocator m_alloc; ptr_vector<set> m_T; ptr_vector<set> m_F; svector<lbool> m_value; svector<lbool> m_model; vector<unsigned_vector> m_tuse_list; vector<unsigned_vector> m_fuse_list; // Custom CDCL solver. svector<justification> m_justification; vector<unsigned_vector> m_twatch; vector<unsigned_vector> m_fwatch; unsigned_vector m_level; unsigned_vector m_trail; // trail of assigned literals unsigned m_qhead; // queue head justification m_conflict_j; // conflict justification unsigned m_conflict_l; // conflict literal bool m_inconsistent; unsigned m_scope_lvl; rational m_weight; // current weight of assignment. unsigned_vector m_indices; unsigned_vector m_scores; vector<rational> m_scored_weights; svector<bool> m_score_updated; bool m_enable_simplex; struct compare_scores { imp* m_imp; compare_scores():m_imp(0) {} bool operator()(int v1, int v2) const { return m_imp->m_scored_weights[v1] > m_imp->m_scored_weights[v2]; } }; compare_scores m_compare_scores; heap<compare_scores> m_heap; svector<bool> m_mark; struct scope { unsigned m_trail_lim; }; vector<scope> m_scopes; unsigned_vector m_lemma; unsigned m_conflict_lvl; // simplex unsynch_mpz_manager m; Simplex m_simplex; unsigned m_weights_var; static unsigned const null_idx = UINT_MAX; imp(reslimit& lim): m_limit(lim), m_max_weight(0), m_denominator(1), m_alloc("hitting-sets"), m_qhead(0), m_conflict_j(justification(justification::AXIOM)), m_inconsistent(false), m_scope_lvl(0), m_compare_scores(), m_heap(0, m_compare_scores), m_simplex(lim), m_weights_var(0) { m_enable_simplex = true; m_compare_scores.m_imp = this; } ~imp() { for (unsigned i = 0; i < m_T.size(); ++i) { m_alloc.deallocate(m_T[i]->alloc_size(), m_T[i]); } for (unsigned i = 0; i < m_F.size(); ++i) { m_alloc.deallocate(m_F[i]->alloc_size(), m_F[i]); } } void add_weight(rational const& w) { SASSERT(w.is_pos()); unsigned var = m_weights.size(); m_simplex.ensure_var(var); m_simplex.set_lower(var, mpq_inf(mpq(0),mpq(0))); m_simplex.set_upper(var, mpq_inf(mpq(1),mpq(0))); m_weights.push_back(w); m_weights_inv.push_back(rational::one()); m_value.push_back(l_undef); m_justification.push_back(justification(justification::DECISION)); m_tuse_list.push_back(unsigned_vector()); m_fuse_list.push_back(unsigned_vector()); m_twatch.push_back(unsigned_vector()); m_fwatch.push_back(unsigned_vector()); m_level.push_back(0); m_indices.push_back(var); m_model.push_back(l_undef); m_mark.push_back(false); m_scores.push_back(0); m_scored_weights.push_back(rational(0)); m_score_updated.push_back(true); m_max_weight += w; } justification add_exists_false(unsigned sz, unsigned const* S) { return add_exists(sz, S, true); } justification add_exists_true(unsigned sz, unsigned const* S) { return add_exists(sz, S, false); } justification add_exists(unsigned sz, unsigned const* S, bool sign) { vector<unsigned_vector>& use_list = sign?m_fuse_list:m_tuse_list; lbool val = sign?l_false:l_true; justification j(justification::AXIOM); ptr_vector<set>& Sets = sign?m_F:m_T; vector<unsigned_vector>& watch = sign?m_fwatch:m_twatch; init_weights(); if (sz == 0) { set_conflict(0, justification(justification::AXIOM)); } else if (sz == 1) { IF_VERBOSE(2, verbose_stream() << "unit literal : " << S[0] << " " << val << "\n";); assign(S[0], val, justification(justification::AXIOM)); } else { unsigned clause_id = Sets.size(); for (unsigned i = 0; i < sz; ++i) { use_list[S[i]].push_back(clause_id); } j = justification(clause_id, !sign); watch[S[0]].push_back(clause_id); watch[S[1]].push_back(clause_id); Sets.push_back(set::mk(m_alloc, sz, S)); if (!sign) { pop(scope_lvl()); inc_score(clause_id); } TRACE("opt", display(tout, j);); IF_VERBOSE(2, if (!sign) display(verbose_stream(), j);); if (!sign && m_enable_simplex) { add_simplex_row(!sign, sz, S); } } return j; } lbool compute_lower() { m_lower.reset(); rational w1 = L1(); rational w2 = L2(); rational w3 = L3(); if (w1 > m_lower) m_lower = w1; if (w2 > m_lower) m_lower = w2; if (w3 > m_lower) m_lower = w3; return l_true; } lbool compute_upper() { m_upper = m_max_weight; unsigned fsz = m_F.size(); lbool r = search(); pop(scope_lvl()); IF_VERBOSE(1, verbose_stream() << "(hsmax.negated-size: " << fsz << ")\n";); #if 0 // garbage collect agressively on exit. // all learned clases for negative branches are // pruned. for (unsigned i = fsz; i < m_F.size(); ++i) { m_alloc.deallocate(m_F[i]->alloc_size(), m_F[i]); } m_F.resize(fsz); for (unsigned i = 0; i < m_fuse_list.size(); ++i) { unsigned_vector & uses = m_fuse_list[i]; while (!uses.empty() && uses.back() >= fsz) uses.pop_back(); unsigned_vector & watch = m_fwatch[i]; unsigned j = 0, k = 0; for (; j < watch.size(); ++j) { if (watch[j] < fsz) { watch[k] = watch[j]; ++k; } } watch.resize(k); } #endif return r; } rational get_lower() { return m_lower/m_denominator; } rational get_upper() { return m_upper/m_denominator; } void set_upper(rational const& r) { m_max_weight = r*m_denominator; } bool get_value(unsigned idx) { return idx < m_model.size() && m_model[idx] == l_true; } void collect_statistics(::statistics& st) const { m_simplex.collect_statistics(st); } void reset() { m_lower.reset(); m_upper = m_max_weight; } void init_weights() { if (m_weights_var != 0) { return; } m_weights_var = m_weights.size(); unsigned_vector vars; scoped_mpz_vector coeffs(m); // normalize weights to integral. rational d(1); for (unsigned i = 0; i < m_weights.size(); ++i) { d = lcm(d, denominator(m_weights[i])); } m_denominator = d; if (!d.is_one()) { for (unsigned i = 0; i < m_weights.size(); ++i) { m_weights[i] *= d; } } rational lc(1); for (unsigned i = 0; i < m_weights.size(); ++i) { lc = lcm(lc, m_weights[i]); } for (unsigned i = 0; i < m_weights.size(); ++i) { m_weights_inv[i] = lc/m_weights[i]; } m_heap.set_bounds(m_weights.size()); for (unsigned i = 0; i < m_weights.size(); ++i) { m_heap.insert(i); } update_heap(); // set up Simplex objective function. for (unsigned i = 0; i < m_weights.size(); ++i) { vars.push_back(i); coeffs.push_back(m_weights[i].to_mpq().numerator()); } m_simplex.ensure_var(m_weights_var); vars.push_back(m_weights_var); coeffs.push_back(mpz(-1)); m_simplex.add_row(m_weights_var, coeffs.size(), vars.c_ptr(), coeffs.c_ptr()); } void display(std::ostream& out) const { out << "inconsistent: " << m_inconsistent << "\n"; out << "weight: " << m_weight << "\n"; for (unsigned i = 0; i < m_weights.size(); ++i) { out << i << ": " << value(i) << " w: " << m_weights[i] << " s: " << m_scores[i] << "\n"; } for (unsigned i = 0; i < m_T.size(); ++i) { display(out << "+" << i << ": ", *m_T[i]); } for (unsigned i = 0; i < m_F.size(); ++i) { display(out << "-" << i << ": ", *m_F[i]); } out << "watch lists:\n"; for (unsigned i = 0; i < m_fwatch.size(); ++i) { out << i << ": "; for (unsigned j = 0; j < m_twatch[i].size(); ++j) { out << "+" << m_twatch[i][j] << " "; } for (unsigned j = 0; j < m_fwatch[i].size(); ++j) { out << "-" << m_fwatch[i][j] << " "; } out << "\n"; } out << "trail\n"; for (unsigned i = 0; i < m_trail.size(); ++i) { unsigned idx = m_trail[i]; out << (m_justification[idx].is_decision()?"d":"") << idx << " "; } out << "\n"; } void display(std::ostream& out, set const& S) const { for (unsigned i = 0; i < S.size(); ++i) { out << S[i] << " "; } out << "\n"; } void display(std::ostream& out, justification const& j) const { switch(j.kind()) { case justification::AXIOM: out << "axiom\n"; break; case justification::DECISION: out << "decision\n"; break; case justification::CLAUSE: { out << "clause: "; set const& S = j.pos()?(*m_T[j.clause()]):(*m_F[j.clause()]); for (unsigned i = 0; i < S.size(); ++i) { out << S[i] << " "; } out << "\n"; } } } void display_lemma(std::ostream& out) { out << "lemma: "; for (unsigned i = 0; i < m_lemma.size(); ++i) { out << m_lemma[i] << " "; } out << "\n"; } struct scoped_push { imp& s; scoped_push(imp& s):s(s) { s.push(); } ~scoped_push() { s.pop(1); } }; struct value_lt { vector<rational> const& weights; value_lt(vector<rational> const& weights): weights(weights) {} bool operator()(int v1, int v2) const { return weights[v1] > weights[v2]; } }; void inc_score(unsigned clause_id) { set const& S = *m_T[clause_id]; if (!has_selected(S)) { for (unsigned j = 0; j < S.size(); ++j) { ++m_scores[S[j]]; m_score_updated[S[j]] = true; } } } void dec_score(unsigned clause_id) { set const& S = *m_T[clause_id]; if (!has_selected(S)) { for (unsigned j = 0; j < S.size(); ++j) { SASSERT(m_scores[S[j]] > 0); --m_scores[S[j]]; m_score_updated[S[j]] = true; } } } void update_score(unsigned idx, bool inc) { unsigned_vector const& uses = m_tuse_list[idx]; for (unsigned i = 0; i < uses.size(); ++i) { if (inc) { inc_score(uses[i]); } else { dec_score(uses[i]); } } } rational L1() { rational w(m_weight); scoped_push _sc(*this); for (unsigned i = 0; !canceled() && i < m_T.size(); ++i) { set const& S = *m_T[i]; SASSERT(!S.empty()); if (!has_selected(S)) { w += m_weights[select_min(S)]; for (unsigned j = 0; j < S.size(); ++j) { assign(S[j], l_true, justification(justification::DECISION)); } } } return w; } void update_heap() { for (unsigned i = 0; i < m_scored_weights.size(); ++i) { if (m_score_updated[i]) { rational const& old_w = m_scored_weights[i]; rational new_w = rational(m_scores[i])*m_weights_inv[i]; if (new_w > old_w) { m_scored_weights[i] = new_w; //m_heap.decreased(i); } else if (new_w < old_w) { m_scored_weights[i] = new_w; //m_heap.increased(i); } m_score_updated[i] = false; } } } rational L2() { rational w(m_weight); scoped_push _sc(*this); int n = 0; for (unsigned i = 0; i < m_T.size(); ++i) { if (!has_selected(*m_T[i])) ++n; } update_heap(); value_lt lt(m_scored_weights); std::sort(m_indices.begin(), m_indices.end(), lt); for(unsigned i = 0; i < m_indices.size() && n > 0; ++i) { // deg(c) = score(c) // wt(c) = m_weights[c] unsigned idx = m_indices[i]; if (m_scores[idx] == 0) { break; } if (m_scores[idx] < static_cast<unsigned>(n) || m_weights[idx].is_one()) { w += m_weights[idx]; } else { w += div((rational(n)*m_weights[idx]), rational(m_scores[idx])); } n -= m_scores[idx]; } return w; } rational L3() { TRACE("simplex", m_simplex.display(tout);); VERIFY(l_true == m_simplex.make_feasible()); TRACE("simplex", m_simplex.display(tout);); VERIFY(l_true == m_simplex.minimize(m_weights_var)); mpq_inf const& val = m_simplex.get_value(m_weights_var); unsynch_mpq_inf_manager mg; unsynch_mpq_manager& mq = mg.get_mpq_manager(); scoped_mpq c(mq); mg.ceil(val, c); rational w(c); CTRACE("simplex", w >= m_weight, tout << w << " " << m_weight << " !!!!\n"; display(tout);); SASSERT(w >= m_weight); return w; } void add_simplex_row(bool is_some_true, unsigned sz, unsigned const* S) { unsigned_vector vars; scoped_mpz_vector coeffs(m); for (unsigned i = 0; i < sz; ++i) { vars.push_back(S[i]); coeffs.push_back(mpz(1)); } unsigned base_var = m_F.size() + m_T.size() + m_weights.size(); m_simplex.ensure_var(base_var); vars.push_back(base_var); coeffs.push_back(mpz(-1)); // S - base_var = 0 if (is_some_true) { // base_var >= 1 m_simplex.set_lower(base_var, mpq_inf(mpq(1),mpq(0))); } else { // base_var <= sz-1 m_simplex.set_upper(base_var, mpq_inf(mpq(sz-1),mpq(0))); } m_simplex.add_row(base_var, coeffs.size(), vars.c_ptr(), coeffs.c_ptr()); } unsigned select_min(set const& S) { unsigned result = S[0]; for (unsigned i = 1; i < S.size(); ++i) { if (m_weights[result] > m_weights[S[i]]) { result = S[i]; } } return result; } bool have_selected(lbool val, ptr_vector<set> const& Sets, unsigned& i) { for (i = 0; i < Sets.size(); ++i) { if (!has_selected(val, *Sets[i])) return false; } return true; } void set_undef_to_false() { for (unsigned i = 0; i < m_model.size(); ++i) { if (m_model[i] == l_undef) { m_model[i] = l_false; } } } bool values_satisfy_Fs(unsigned& i) { unsigned j = 0; for (i = 0; i < m_F.size(); ++i) { set const& F = *m_F[i]; for (j = 0; j < F.size(); ++j) { if (m_model[F[j]] == l_false) { break; } } if (F.size() == j) { break; } } return i == m_F.size(); } bool has_selected(set const& S) { return has_selected(l_true, S); } bool has_unselected(set const& S) { return has_selected(l_false, S); } bool has_unset(set const& S) { return has_selected(l_undef, S); } bool has_selected(lbool val, set const& S) { for (unsigned i = 0; i < S.size(); ++i) { if (val == value(S[i])) { return true; } } return false; } // (greedy) CDCL learner for hitting sets. inline unsigned scope_lvl() const { return m_scope_lvl; } inline bool inconsistent() const { return m_inconsistent; } inline bool canceled() const { return !m_limit.inc(); } inline unsigned lvl(unsigned idx) const { return m_level[idx]; } inline lbool value(unsigned idx) const { return m_value[idx]; } inline bool is_marked(unsigned v) const { return m_mark[v] != 0; } inline void mark(unsigned v) { SASSERT(!is_marked(v)); m_mark[v] = true; } inline void reset_mark(unsigned v) { SASSERT(is_marked(v)); m_mark[v] = false; } void push() { SASSERT(!inconsistent()); ++m_scope_lvl; m_scopes.push_back(scope()); scope& s = m_scopes.back(); s.m_trail_lim = m_trail.size(); } void pop(unsigned n) { if (n > 0) { m_inconsistent = false; m_scope_lvl = scope_lvl() - n; unassign(m_scopes[scope_lvl()].m_trail_lim); m_scopes.shrink(scope_lvl()); } } void assign(unsigned idx, lbool val, justification const& justification) { if (val == l_true) { m_weight += m_weights[idx]; update_score(idx, false); if (m_enable_simplex) { m_simplex.set_lower(idx, mpq_inf(mpq(1),mpq(0))); } } SASSERT(val != l_true || m_scores[idx] == 0); m_value[idx] = val; m_justification[idx] = justification; m_trail.push_back(idx); m_level[idx] = scope_lvl(); TRACE("opt", tout << idx << " := " << val << " scope: " << scope_lvl() << " w: " << m_weight << "\n";); } svector<unsigned> m_replay_idx; svector<lbool> m_replay_val; void unassign(unsigned sz) { for (unsigned j = sz; j < m_trail.size(); ++j) { unsigned idx = m_trail[j]; lbool val = value(idx); m_value[idx] = l_undef; if (val == l_true) { m_weight -= m_weights[idx]; update_score(idx, true); if (m_enable_simplex) { m_simplex.set_lower(idx, mpq_inf(mpq(0),mpq(0))); } } if (m_justification[idx].is_axiom()) { m_replay_idx.push_back(idx); m_replay_val.push_back(val); } } TRACE("opt", tout << m_weight << "\n";); m_trail.shrink(sz); m_qhead = sz; for (unsigned i = m_replay_idx.size(); i > 0; ) { --i; unsigned idx = m_replay_idx[i]; lbool val = m_replay_val[i]; assign(idx, val, justification(justification::AXIOM)); } m_replay_idx.reset(); m_replay_val.reset(); } lbool search() { TRACE("opt", display(tout);); pop(scope_lvl()); while (true) { while (true) { propagate(); if (canceled()) return l_undef; if (!inconsistent()) break; if (!resolve_conflict()) return l_false; SASSERT(!inconsistent()); } if (!decide()) { SASSERT(validate_model()); m_model.reset(); m_model.append(m_value); m_upper = m_weight; // SASSERT(m_weight < m_max_weight); return l_true; } } } bool validate_model() { for (unsigned i = 0; i < m_T.size(); ++i) { set const& S = *m_T[i]; bool found = false; for (unsigned j = 0; !found && j < S.size(); ++j) { found = value(S[j]) == l_true; } CTRACE("opt", !found, display(tout << "not found: " << i << "\n", S); display(tout);); SASSERT(found); } for (unsigned i = 0; i < m_F.size(); ++i) { set const& S = *m_F[i]; bool found = false; for (unsigned j = 0; !found && j < S.size(); ++j) { found = value(S[j]) != l_true; } CTRACE("opt", !found, display(tout << "not found: " << i << "\n", S); display(tout);); SASSERT(found); } return true; } bool invariant() { for (unsigned i = 0; i < m_fwatch.size(); ++i) { for (unsigned j = 0; j < m_fwatch[i].size(); ++j) { set const& S = *m_F[m_fwatch[i][j]]; SASSERT(S[0] == i || S[1] == i); } } for (unsigned i = 0; i < m_twatch.size(); ++i) { for (unsigned j = 0; j < m_twatch[i].size(); ++j) { set const& S = *m_T[m_twatch[i][j]]; SASSERT(S[0] == i || S[1] == i); } } return true; } bool resolve_conflict() { while (true) { if (!resolve_conflict_core()) return false; if (!inconsistent()) return true; } } unsigned get_max_lvl(unsigned conflict_l, justification const& conflict_j) { if (scope_lvl() == 0) return 0; unsigned r = lvl(conflict_l); if (conflict_j.is_clause()) { unsigned clause = conflict_j.clause(); ptr_vector<set> const& S = conflict_j.pos()?m_T:m_F; r = std::max(r, lvl((*S[clause])[0])); r = std::max(r, lvl((*S[clause])[1])); } return r; } bool resolve_conflict_core() { SASSERT(inconsistent()); TRACE("opt", display(tout);); unsigned conflict_l = m_conflict_l; justification conflict_j(m_conflict_j); if (conflict_j.is_axiom()) { return false; } m_conflict_lvl = get_max_lvl(conflict_l, conflict_j); if (m_conflict_lvl == 0) { return false; } unsigned idx = skip_above_conflict_level(); unsigned num_marks = 0; m_lemma.reset(); m_lemma.push_back(0); process_antecedent(conflict_l, num_marks); do { TRACE("opt", tout << "conflict literal: " << conflict_l << "\n"; display(tout, conflict_j);); if (conflict_j.is_clause()) { unsigned cl = conflict_j.clause(); unsigned i = 0; SASSERT(value(conflict_l) != l_undef); set const& T = conflict_j.pos()?(*m_T[cl]):(*m_F[cl]); if (T[0] == conflict_l) { i = 1; } else { SASSERT(T[1] == conflict_l); process_antecedent(T[0], num_marks); i = 2; } unsigned sz = T.size(); for (; i < sz; ++i) { process_antecedent(T[i], num_marks); } } else if (conflict_j.is_decision()) { --num_marks; SASSERT(num_marks == 0); break; } else if (conflict_j.is_axiom()) { IF_VERBOSE(0, verbose_stream() << "axiom " << conflict_l << " " << value(conflict_l) << " " << num_marks << "\n";); --num_marks; SASSERT(num_marks == 0); break; } while (true) { unsigned l = m_trail[idx]; if (is_marked(l)) break; SASSERT(idx > 0); --idx; } conflict_l = m_trail[idx]; conflict_j = m_justification[conflict_l]; --idx; --num_marks; if (num_marks == 0 && value(conflict_l) == l_false) { ++num_marks; } reset_mark(conflict_l); } while (num_marks > 0); m_lemma[0] = conflict_l; TRACE("opt", display_lemma(tout);); SASSERT(value(conflict_l) == l_true); unsigned new_scope_lvl = 0; for (unsigned i = 1; i < m_lemma.size(); ++i) { SASSERT(l_true == value(m_lemma[i])); new_scope_lvl = std::max(new_scope_lvl, lvl(m_lemma[i])); reset_mark(m_lemma[i]); } pop(scope_lvl() - new_scope_lvl); SASSERT(l_undef == value(conflict_l)); justification j = add_exists_false(m_lemma.size(), m_lemma.c_ptr()); if (!j.is_axiom()) assign(conflict_l, l_false, j); return true; } void process_antecedent(unsigned antecedent, unsigned& num_marks) { unsigned alvl = lvl(antecedent); SASSERT(alvl <= m_conflict_lvl); if (!is_marked(antecedent) && alvl > 0 && !m_justification[antecedent].is_axiom()) { mark(antecedent); if (alvl == m_conflict_lvl || value(antecedent) == l_false) { ++num_marks; } else { m_lemma.push_back(antecedent); } } } unsigned skip_above_conflict_level() { unsigned idx = m_trail.size(); if (idx == 0) { return idx; } idx--; // skip literals from levels above the conflict level while (lvl(m_trail[idx]) > m_conflict_lvl) { SASSERT(idx > 0); idx--; } return idx; } void set_conflict(unsigned idx, justification const& justification) { if (!inconsistent()) { TRACE("opt", tout << "conflict: " << idx << "\n";); m_inconsistent = true; m_conflict_j = justification; m_conflict_l = idx; } } unsigned next_var() { update_heap(); value_lt lt(m_scored_weights); std::sort(m_indices.begin(), m_indices.end(), lt); unsigned idx = m_indices[0]; if (m_scores[idx] == 0) return UINT_MAX; return idx; #if 0 int min_val = m_heap.min_value(); if (min_val == -1) { return UINT_MAX; } SASSERT(0 <= min_val && static_cast<unsigned>(min_val) < m_weights.size()); if (m_scores[min_val] == 0) { return UINT_MAX; } return static_cast<unsigned>(min_val); #endif } bool decide() { unsigned idx = next_var(); if (idx == UINT_MAX) { return false; } else { push(); TRACE("opt", tout << "decide " << idx << "\n";); assign(idx, l_true, justification(justification::DECISION)); return true; } } void propagate() { TRACE("opt", display(tout);); SASSERT(invariant()); while (m_qhead < m_trail.size() && !inconsistent() && !canceled()) { unsigned idx = m_trail[m_qhead]; ++m_qhead; switch (value(idx)) { case l_undef: UNREACHABLE(); break; case l_true: propagate(idx, l_false, m_fwatch, m_F); break; case l_false: propagate(idx, l_true, m_twatch, m_T); break; } } prune_branch(); } void propagate(unsigned idx, lbool good_val, vector<unsigned_vector>& watch, ptr_vector<set>& Fs) { TRACE("opt", tout << idx << " " << value(idx) << "\n";); unsigned_vector& w = watch[idx]; unsigned sz = w.size(); lbool bad_val = ~good_val; SASSERT(value(idx) == bad_val); unsigned l = 0; for (unsigned i = 0; i < sz && !canceled(); ++i, ++l) { unsigned clause_id = w[i]; set& F = *Fs[clause_id]; SASSERT(F.size() >= 2); bool k1 = (F[0] != idx); bool k2 = !k1; SASSERT(F[k1] == idx); SASSERT(value(F[k1]) == bad_val); if (value(F[k2]) == good_val) { w[l] = w[i]; continue; } bool found = false; unsigned sz2 = F.size(); for (unsigned j = 2; !found && j < sz2; ++j) { unsigned idx2 = F[j]; if (value(idx2) != bad_val) { found = true; std::swap(F[k1], F[j]); --l; watch[idx2].push_back(clause_id); } } if (!found) { if (value(F[k2]) == bad_val) { set_conflict(F[k2], justification(clause_id, good_val == l_true)); if (i == l) { l = sz; } else { for (; i < sz; ++i, ++l) { w[l] = w[i]; } } break; } else { SASSERT(value(F[k2]) == l_undef); assign(F[k2], good_val, justification(clause_id, good_val == l_true)); w[l] = w[i]; } } } watch[idx].shrink(l); SASSERT(invariant()); TRACE("opt", tout << idx << " " << value(idx) << "\n";); SASSERT(value(idx) == bad_val); } bool infeasible_lookahead() { if (m_enable_simplex && L3() >= m_max_weight) { return true; } return (L1() >= m_max_weight) || (L2() >= m_max_weight); } void prune_branch() { if (inconsistent() || !infeasible_lookahead()) { return; } IF_VERBOSE(4, verbose_stream() << "(hs.prune-branch " << m_weight << ")\n";); m_lemma.reset(); unsigned i = 0; rational w(0); for (; i < m_trail.size() && w < m_max_weight; ++i) { unsigned idx = m_trail[i]; if (m_justification[idx].is_decision()) { SASSERT(value(idx) == l_true); m_lemma.push_back(idx); w += m_weights[idx]; } } // undo the lower bounds. TRACE("opt", tout << "prune branch: " << m_weight << " "; display_lemma(tout); display(tout); ); justification j = add_exists_false(m_lemma.size(), m_lemma.c_ptr()); unsigned idx = m_lemma.empty()?0:m_lemma[0]; set_conflict(idx, j); } // TBD: derive strong inequalities and add them to Simplex. // x_i1 + .. + x_ik >= k-1 for each subset k from set n: x_1 + .. + x_n >= k }; hitting_sets::hitting_sets(reslimit& lim) { m_imp = alloc(imp, lim); } hitting_sets::~hitting_sets() { dealloc(m_imp); } void hitting_sets::add_weight(rational const& w) { m_imp->add_weight(w); } void hitting_sets::add_exists_true(unsigned sz, unsigned const* elems) { m_imp->add_exists_true(sz, elems); } void hitting_sets::add_exists_false(unsigned sz, unsigned const* elems) { m_imp->add_exists_false(sz, elems); } lbool hitting_sets::compute_lower() { return m_imp->compute_lower(); } lbool hitting_sets::compute_upper() { return m_imp->compute_upper(); } rational hitting_sets::get_lower() { return m_imp->get_lower(); } rational hitting_sets::get_upper() { return m_imp->get_upper(); } void hitting_sets::set_upper(rational const& r) { return m_imp->set_upper(r); } bool hitting_sets::get_value(unsigned idx) { return m_imp->get_value(idx); } void hitting_sets::collect_statistics(::statistics& st) const { m_imp->collect_statistics(st); } void hitting_sets::reset() { m_imp->reset(); } };
seahorn/z3
src/opt/hitting_sets.cpp
C++
mit
39,509
import * as React from 'react'; import Button from '@material-ui/core/Button'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import Grow from '@material-ui/core/Grow'; import Paper from '@material-ui/core/Paper'; import Popper from '@material-ui/core/Popper'; import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import Stack from '@material-ui/core/Stack'; export default function MenuListComposition() { const [open, setOpen] = React.useState(false); const anchorRef = React.useRef<HTMLButtonElement>(null); const handleToggle = () => { setOpen((prevOpen) => !prevOpen); }; const handleClose = (event: Event | React.SyntheticEvent) => { if ( anchorRef.current && anchorRef.current.contains(event.target as HTMLElement) ) { return; } setOpen(false); }; function handleListKeyDown(event: React.KeyboardEvent) { if (event.key === 'Tab') { event.preventDefault(); setOpen(false); } else if (event.key === 'Escape') { setOpen(false); } } // return focus to the button when we transitioned from !open -> open const prevOpen = React.useRef(open); React.useEffect(() => { if (prevOpen.current === true && open === false) { anchorRef.current!.focus(); } prevOpen.current = open; }, [open]); return ( <Stack direction="row" spacing={2}> <Paper> <MenuList> <MenuItem>Profile</MenuItem> <MenuItem>My account</MenuItem> <MenuItem>Logout</MenuItem> </MenuList> </Paper> <div> <Button ref={anchorRef} id="composition-button" aria-controls={open ? 'composition-menu' : undefined} aria-expanded={open ? 'true' : undefined} aria-haspopup="true" onClick={handleToggle} > Dashboard </Button> <Popper open={open} anchorEl={anchorRef.current} role={undefined} placement="bottom-start" transition disablePortal > {({ TransitionProps, placement }) => ( <Grow {...TransitionProps} style={{ transformOrigin: placement === 'bottom-start' ? 'left top' : 'left bottom', }} > <Paper> <ClickAwayListener onClickAway={handleClose}> <MenuList autoFocusItem={open} id="composition-menu" aria-labelledby="composition-button" onKeyDown={handleListKeyDown} > <MenuItem onClick={handleClose}>Profile</MenuItem> <MenuItem onClick={handleClose}>My account</MenuItem> <MenuItem onClick={handleClose}>Logout</MenuItem> </MenuList> </ClickAwayListener> </Paper> </Grow> )} </Popper> </div> </Stack> ); }
callemall/material-ui
docs/src/pages/components/menus/MenuListComposition.tsx
TypeScript
mit
3,099
<?php namespace PHPMad\Tests; use PHPMad\FizzBuzz; class FooTest extends \PHPUnit_Framework_TestCase { protected $object; private $fizzBuzz; protected function setUp() { $this->object = new FizzBuzz(); $this->fizzBuzz = $this->object->run(); } function testLength() { $this->assertCount(100, $this->fizzBuzz); } function testNormalNumbersAreThemselves() { $this->assertEquals(1, $this->fizzBuzz[0]); } function testMultipleOf3HasFizz() { $this->assertEquals('Fizz', $this->fizzBuzz[2]); } function testMultipleOf5HasBuzz() { $this->assertEquals('Buzz', $this->fizzBuzz[4]); } function testMultipleOf15isFizzBuzz() { $this->assertEquals('FizzBuzz', $this->fizzBuzz[14]); } function testContains3HasFizz() { $this->assertEquals('Fizz', $this->fizzBuzz[12]); } function testContains5HasBuzz() { $this->assertEquals('Buzz', $this->fizzBuzz[51]); } function testContains3And5IsFizzBuzz() { $this->assertEquals('FizzBuzz', $this->fizzBuzz[52]); } }
ajgarlag/php-mad-fizzbuzz-2
tests/PHPMad/Tests/FizzBuzzTest.php
PHP
mit
1,153
package leetcode221_230; import java.util.ArrayList; import java.util.List; /**Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. * Created by eugene on 16/4/23. */ public class SummaryRanges { public List<String> summaryRanges(int[] nums) { List<String> list = new ArrayList(); for(int i=0; i<nums.length; i++){ int n = nums[i]; while(i+1<nums.length && nums[i+1]-nums[i]==1) i++; if(n!=nums[i]){ list.add(n+"->"+nums[i]); }else{ list.add(n+""); } } return list; } public List<String> summaryRanges1(int[] nums) { List<String> result = new ArrayList<>(); if (nums.length==0) return result; int start = nums[0]; int count = 1; StringBuilder builder = new StringBuilder(); builder.append(start); for (int i=1; i<nums.length; i++){ if (nums[i]-nums[i-1]==1){ count++; } else { if (count==1) { result.add(builder.toString()); } else { result.add(builder.append("->"+nums[i-1]).toString()); } builder = new StringBuilder(""+nums[i]); count = 1; } } if (count!=1) result.add(builder.append("->"+nums[nums.length-1]).toString()); else result.add(builder.toString()); return result; } }
Ernestyj/JStudy
src/main/java/leetcode221_230/SummaryRanges.java
Java
mit
1,582
/** * 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. */ package com.microsoft.azure.management.sql.v2017_03_01_preview; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for DatabaseStatus. */ public final class DatabaseStatus extends ExpandableStringEnum<DatabaseStatus> { /** Static value Online for DatabaseStatus. */ public static final DatabaseStatus ONLINE = fromString("Online"); /** Static value Restoring for DatabaseStatus. */ public static final DatabaseStatus RESTORING = fromString("Restoring"); /** Static value RecoveryPending for DatabaseStatus. */ public static final DatabaseStatus RECOVERY_PENDING = fromString("RecoveryPending"); /** Static value Recovering for DatabaseStatus. */ public static final DatabaseStatus RECOVERING = fromString("Recovering"); /** Static value Suspect for DatabaseStatus. */ public static final DatabaseStatus SUSPECT = fromString("Suspect"); /** Static value Offline for DatabaseStatus. */ public static final DatabaseStatus OFFLINE = fromString("Offline"); /** Static value Standby for DatabaseStatus. */ public static final DatabaseStatus STANDBY = fromString("Standby"); /** Static value Shutdown for DatabaseStatus. */ public static final DatabaseStatus SHUTDOWN = fromString("Shutdown"); /** Static value EmergencyMode for DatabaseStatus. */ public static final DatabaseStatus EMERGENCY_MODE = fromString("EmergencyMode"); /** Static value AutoClosed for DatabaseStatus. */ public static final DatabaseStatus AUTO_CLOSED = fromString("AutoClosed"); /** Static value Copying for DatabaseStatus. */ public static final DatabaseStatus COPYING = fromString("Copying"); /** Static value Creating for DatabaseStatus. */ public static final DatabaseStatus CREATING = fromString("Creating"); /** Static value Inaccessible for DatabaseStatus. */ public static final DatabaseStatus INACCESSIBLE = fromString("Inaccessible"); /** Static value OfflineSecondary for DatabaseStatus. */ public static final DatabaseStatus OFFLINE_SECONDARY = fromString("OfflineSecondary"); /** Static value Pausing for DatabaseStatus. */ public static final DatabaseStatus PAUSING = fromString("Pausing"); /** Static value Paused for DatabaseStatus. */ public static final DatabaseStatus PAUSED = fromString("Paused"); /** Static value Resuming for DatabaseStatus. */ public static final DatabaseStatus RESUMING = fromString("Resuming"); /** Static value Scaling for DatabaseStatus. */ public static final DatabaseStatus SCALING = fromString("Scaling"); /** * Creates or finds a DatabaseStatus from its string representation. * @param name a name to look for * @return the corresponding DatabaseStatus */ @JsonCreator public static DatabaseStatus fromString(String name) { return fromString(name, DatabaseStatus.class); } /** * @return known DatabaseStatus values */ public static Collection<DatabaseStatus> values() { return values(DatabaseStatus.class); } }
selvasingh/azure-sdk-for-java
sdk/sql/mgmt-v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/DatabaseStatus.java
Java
mit
3,401
module Nanoc::Int # Module that contains all outdatedness reasons. # # @api private module OutdatednessReasons # A generic outdatedness reason. An outdatedness reason is basically a # descriptive message that explains why a given object is outdated. class Generic # @return [String] A descriptive message for this outdatedness reason attr_reader :message # @param [String] message The descriptive message for this outdatedness # reason def initialize(message) @message = message end end CodeSnippetsModified = Generic.new( 'The code snippets have been modified since the last time the site was compiled.') ConfigurationModified = Generic.new( 'The site configuration has been modified since the last time the site was compiled.') DependenciesOutdated = Generic.new( 'This item uses content or attributes that have changed since the last time the site was compiled.') NotEnoughData = Generic.new( 'Not enough data is present to correctly determine whether the item is outdated.') NotWritten = Generic.new( 'This item representation has not yet been written to the output directory (but it does have a path).') RulesModified = Generic.new( 'The rules file has been modified since the last time the site was compiled.') SourceModified = Generic.new( 'The source file of this item has been modified since the last time the site was compiled.') end end
gjtorikian/nanoc
lib/nanoc/base/compilation/outdatedness_reasons.rb
Ruby
mit
1,498
import '@phosphor/widgets/style/index.css'; import 'font-awesome/css/font-awesome.css'; import '@jupyter-widgets/controls/css/widgets.css'; import { WidgetManager } from './manager'; /** * Render the inline widgets inside a DOM element. * * @param managerFactory A function that returns a new WidgetManager * @param element (default document.documentElement) The document element in which to process for widget state. */ export declare function renderWidgets(managerFactory: () => WidgetManager, element?: HTMLElement): Promise<void>;
glenngillen/dotfiles
.vscode/extensions/ms-toolsai.jupyter-2021.6.832593372/out/ipywidgets/libembed.d.ts
TypeScript
mit
540
/* * Copyright (c) 2011, Dirk Thomas, TU Darmstadt * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the TU Darmstadt nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <rqt_autopilot/ratio_layouted_frame.h> #include <assert.h> namespace rqt_autopilot { RatioLayoutedFrame::RatioLayoutedFrame(QWidget* parent, Qt::WFlags flags) : QFrame() , aspect_ratio_(4, 3) { } RatioLayoutedFrame::~RatioLayoutedFrame() { } void RatioLayoutedFrame::resizeToFitAspectRatio() { QRect rect = contentsRect(); // reduce longer edge to aspect ration double width = double(rect.width()); double height = double(rect.height()); if (width * aspect_ratio_.height() / height > aspect_ratio_.width()) { // too large width width = height * aspect_ratio_.width() / aspect_ratio_.height(); rect.setWidth(int(width)); } else { // too large height height = width * aspect_ratio_.height() / aspect_ratio_.width(); rect.setHeight(int(height)); } // resize taking the border line into account int border = lineWidth(); resize(rect.width() + 2 * border, rect.height() + 2 * border); } void RatioLayoutedFrame::setInnerFrameMinimumSize(const QSize& size) { int border = lineWidth(); QSize new_size = size; new_size += QSize(2 * border, 2 * border); setMinimumSize(new_size); update(); } void RatioLayoutedFrame::setInnerFrameMaximumSize(const QSize& size) { int border = lineWidth(); QSize new_size = size; new_size += QSize(2 * border, 2 * border); setMaximumSize(new_size); update(); } void RatioLayoutedFrame::setInnerFrameFixedSize(const QSize& size) { setInnerFrameMinimumSize(size); setInnerFrameMaximumSize(size); } void RatioLayoutedFrame::setAspectRatio(unsigned short width, unsigned short height) { int divisor = greatestCommonDivisor(width, height); if (divisor != 0) { aspect_ratio_.setWidth(width / divisor); aspect_ratio_.setHeight(height / divisor); } } int RatioLayoutedFrame::greatestCommonDivisor(int a, int b) { if (b==0) { return a; } return greatestCommonDivisor(b, a % b); } }
gt-ros-pkg/humans
src/syllo_rqt/catkin_ws/src/rqt_autopilot/src/rqt_autopilot/ratio_layouted_frame.cpp
C++
mit
3,531
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @flow strict-local * @format */ // flowlint ambiguous-object-type:error 'use strict'; const useRelayEnvironment = require('./useRelayEnvironment'); const warning = require('warning'); const {getFragmentResourceForEnvironment} = require('./FragmentResource'); const {useEffect, useRef, useState} = require('react'); const {getFragmentIdentifier} = require('relay-runtime'); import type {ReaderFragment} from 'relay-runtime'; type ReturnType<TFragmentData: mixed> = {| data: TFragmentData, disableStoreUpdates: () => void, enableStoreUpdates: () => void, shouldUpdateGeneration: number | null, |}; function useFragmentNode<TFragmentData: mixed>( fragmentNode: ReaderFragment, fragmentRef: mixed, componentDisplayName: string, ): ReturnType<TFragmentData> { const environment = useRelayEnvironment(); const FragmentResource = getFragmentResourceForEnvironment(environment); const isMountedRef = useRef(false); const [, forceUpdate] = useState(0); const fragmentIdentifier = getFragmentIdentifier(fragmentNode, fragmentRef); // The values of these React refs are counters that should be incremented // under their respective conditions. This allows us to use the counters as // memoization values to indicate if computations for useMemo or useEffect // should be re-executed. const mustResubscribeGenerationRef = useRef(0); const shouldUpdateGenerationRef = useRef(0); const environmentChanged = useHasChanged(environment); const fragmentIdentifierChanged = useHasChanged(fragmentIdentifier); // If the fragment identifier changes, it means that the variables on the // fragment owner changed, or the fragment ref points to different records. // In this case, we need to resubscribe to the Relay store. const mustResubscribe = environmentChanged || fragmentIdentifierChanged; // We only want to update the component consuming this fragment under the // following circumstances: // - We receive an update from the Relay store, indicating that the data // the component is directly subscribed to has changed. // - We need to subscribe and render /different/ data (i.e. the fragment refs // now point to different records, or the context changed). // Note that even if identity of the fragment ref objects changes, we // don't consider them as different unless they point to a different data ID. // // This prevents unnecessary updates when a parent re-renders this component // with the same props, which is a common case when the parent updates due // to change in the data /it/ is subscribed to, but which doesn't affect the // child. if (mustResubscribe) { shouldUpdateGenerationRef.current++; mustResubscribeGenerationRef.current++; } // Read fragment data; this might suspend. const fragmentResult = FragmentResource.readWithIdentifier( fragmentNode, fragmentRef, fragmentIdentifier, componentDisplayName, ); const isListeningForUpdatesRef = useRef(true); function enableStoreUpdates() { isListeningForUpdatesRef.current = true; const didMissUpdates = FragmentResource.checkMissedUpdates( fragmentResult, )[0]; if (didMissUpdates) { handleDataUpdate(); } } function disableStoreUpdates() { isListeningForUpdatesRef.current = false; } function handleDataUpdate() { if ( isMountedRef.current === false || isListeningForUpdatesRef.current === false ) { return; } // If we receive an update from the Relay store, we need to make sure the // consuming component updates. shouldUpdateGenerationRef.current++; // React bails out on noop state updates as an optimization. // If we want to force an update via setState, we need to pass an value. // The actual value can be arbitrary though, e.g. an incremented number. forceUpdate(count => count + 1); } // Establish Relay store subscriptions in the commit phase, only if // rendering for the first time, or if we need to subscribe to new data useEffect(() => { isMountedRef.current = true; const disposable = FragmentResource.subscribe( fragmentResult, handleDataUpdate, ); return () => { // When unmounting or resubscribing to new data, clean up current // subscription. This will also make sure fragment data is no longer // cached for the so next time it its read, it will be read fresh from the // Relay store isMountedRef.current = false; disposable.dispose(); }; // NOTE: We disable react-hooks-deps warning because mustResubscribeGenerationRef // is capturing all information about whether the effect should be re-ran. // eslint-disable-next-line react-hooks/exhaustive-deps }, [mustResubscribeGenerationRef.current]); if (__DEV__) { if (fragmentRef != null && fragmentResult.data == null) { warning( false, 'Relay: Expected to have been able to read non-null data for ' + 'fragment `%s` declared in ' + '`%s`, since fragment reference was non-null. ' + "Make sure that that `%s`'s parent isn't " + 'holding on to and/or passing a fragment reference for data that ' + 'has been deleted.', fragmentNode.name, componentDisplayName, componentDisplayName, ); } } return { // $FlowFixMe data: fragmentResult.data, disableStoreUpdates, enableStoreUpdates, shouldUpdateGeneration: shouldUpdateGenerationRef.current, }; } function useHasChanged(value: mixed): boolean { const [mirroredValue, setMirroredValue] = useState(value); const valueChanged = mirroredValue !== value; if (valueChanged) { setMirroredValue(value); } return valueChanged; } module.exports = useFragmentNode;
iamchenxin/relay
packages/relay-experimental/useFragmentNode.js
JavaScript
mit
6,025
/** * This class is generated by jOOQ */ package de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.records; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class BattleParticipantRecord extends org.jooq.impl.TableRecordImpl<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.records.BattleParticipantRecord> implements org.jooq.Record2<java.lang.Integer, java.lang.Integer>, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.interfaces.IBattleParticipant { private static final long serialVersionUID = -1733415471; /** * Setter for <code>battle_participant.id</code>. */ public void setId(java.lang.Integer value) { setValue(0, value); } /** * Getter for <code>battle_participant.id</code>. */ @Override public java.lang.Integer getId() { return (java.lang.Integer) getValue(0); } /** * Setter for <code>battle_participant.issue_id</code>. */ public void setIssueId(java.lang.Integer value) { setValue(1, value); } /** * Getter for <code>battle_participant.issue_id</code>. */ @Override public java.lang.Integer getIssueId() { return (java.lang.Integer) getValue(1); } // ------------------------------------------------------------------------- // Record2 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public org.jooq.Row2<java.lang.Integer, java.lang.Integer> fieldsRow() { return (org.jooq.Row2) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Row2<java.lang.Integer, java.lang.Integer> valuesRow() { return (org.jooq.Row2) super.valuesRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field1() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT.ID; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field2() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT.ISSUE_ID; } /** * {@inheritDoc} */ @Override public java.lang.Integer value1() { return getId(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value2() { return getIssueId(); } /** * {@inheritDoc} */ @Override public BattleParticipantRecord value1(java.lang.Integer value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public BattleParticipantRecord value2(java.lang.Integer value) { setIssueId(value); return this; } /** * {@inheritDoc} */ @Override public BattleParticipantRecord values(java.lang.Integer value1, java.lang.Integer value2) { return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached BattleParticipantRecord */ public BattleParticipantRecord() { super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT); } /** * Create a detached, initialised BattleParticipantRecord */ public BattleParticipantRecord(java.lang.Integer id, java.lang.Integer issueId) { super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT); setValue(0, id); setValue(1, issueId); } }
plattformbrandenburg/ldadmin
src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/tables/records/BattleParticipantRecord.java
Java
mit
3,599
/** * @providesModule Fabric */ 'use strict'; module.exports.Crashlytics = require('./Crashlytics'); module.exports.Answers = require('./Answers');
lrettig/react-native-fabric
index.js
JavaScript
mit
150
namespace AwesomeLogger.Audit.Api.Migrations { using System; using System.Data.Entity.Migrations; public partial class Init : DbMigration { public override void Up() { CreateTable( "dbo.PatternMatches", c => new { Id = c.Int(nullable: false, identity: true), Created = c.DateTime(nullable: false), MachineName = c.String(nullable: false, maxLength: 200), SearchPath = c.String(nullable: false, maxLength: 255), LogPath = c.String(nullable: false, maxLength: 255), Pattern = c.String(nullable: false, maxLength: 200), Line = c.Int(nullable: false), Email = c.String(nullable: false, maxLength: 255), Match = c.String(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropTable("dbo.PatternMatches"); } } }
alexey-ernest/awesome-logger
Package/Source/AwesomeLogger.Audit.Api/Migrations/201506211259170_Init.cs
C#
mit
1,155
require File.dirname(__FILE__) + '/helper' class TestPager < Test::Unit::TestCase should "calculate number of pages" do assert_equal(0, Pager.calculate_pages([], '2')) assert_equal(1, Pager.calculate_pages([1], '2')) assert_equal(1, Pager.calculate_pages([1,2], '2')) assert_equal(2, Pager.calculate_pages([1,2,3], '2')) assert_equal(2, Pager.calculate_pages([1,2,3,4], '2')) assert_equal(3, Pager.calculate_pages([1,2,3,4,5], '2')) end context "pagination disabled" do setup do stub(Jekyll).configuration do Jekyll::DEFAULTS.merge({ 'source' => source_dir, 'destination' => dest_dir }) end @config = Jekyll.configuration end should "report that pagination is disabled" do assert !Pager.pagination_enabled?(@config, 'index.html') end end context "pagination enabled for 2" do setup do stub(Jekyll).configuration do Jekyll::DEFAULTS.merge({ 'source' => source_dir, 'destination' => dest_dir, 'paginate' => 2 }) end @config = Jekyll.configuration @site = Site.new(@config) @site.process @posts = @site.posts end should "report that pagination is enabled" do assert Pager.pagination_enabled?(@config, 'index.html') end context "with 4 posts" do setup do @posts = @site.posts[1..4] # limit to 4 end should "create first pager" do pager = Pager.new(@config, 1, @posts) assert_equal(2, pager.posts.size) assert_equal(2, pager.total_pages) assert_nil(pager.previous_page) assert_equal(2, pager.next_page) end should "create second pager" do pager = Pager.new(@config, 2, @posts) assert_equal(2, pager.posts.size) assert_equal(2, pager.total_pages) assert_equal(1, pager.previous_page) assert_nil(pager.next_page) end should "not create third pager" do assert_raise(RuntimeError) { Pager.new(@config, 3, @posts) } end end context "with 5 posts" do setup do @posts = @site.posts[1..5] # limit to 5 end should "create first pager" do pager = Pager.new(@config, 1, @posts) assert_equal(2, pager.posts.size) assert_equal(3, pager.total_pages) assert_nil(pager.previous_page) assert_equal(2, pager.next_page) end should "create second pager" do pager = Pager.new(@config, 2, @posts) assert_equal(2, pager.posts.size) assert_equal(3, pager.total_pages) assert_equal(1, pager.previous_page) assert_equal(3, pager.next_page) end should "create third pager" do pager = Pager.new(@config, 3, @posts) assert_equal(1, pager.posts.size) assert_equal(3, pager.total_pages) assert_equal(2, pager.previous_page) assert_nil(pager.next_page) end should "not create fourth pager" do assert_raise(RuntimeError) { Pager.new(@config, 4, @posts) } end end end end
stammy/jekyll
test/test_pager.rb
Ruby
mit
3,137
package chihane.jdaddressselector; import java.util.List; import chihane.jdaddressselector.model.City; import chihane.jdaddressselector.model.County; import chihane.jdaddressselector.model.Province; import chihane.jdaddressselector.model.Street; public interface AddressProvider { void provideProvinces(AddressReceiver<Province> addressReceiver); void provideCitiesWith(int provinceId, AddressReceiver<City> addressReceiver); void provideCountiesWith(int cityId, AddressReceiver<County> addressReceiver); void provideStreetsWith(int countyId, AddressReceiver<Street> addressReceiver); interface AddressReceiver<T> { void send(List<T> data); } }
chihane/JDAddressSelector
library/src/main/java/chihane/jdaddressselector/AddressProvider.java
Java
mit
680
def hours_in_year # 1 year is equal to 365 days # 1 day is equal to 24 hours # Therefore we multiply 365 with 24 to get the total # amount of hours in a year. 365 * 24 end puts "There are #{hours_in_year} hours in a year!"
VansPhan/phase-0
week-4/scrap_paper/hours_in_a_year.rb
Ruby
mit
230
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.puntodeventa.global.Entity; import java.io.Serializable; import java.math.BigInteger; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; /** * * @author jehernandez */ @Embeddable public class CredAmortPK implements Serializable { @Basic(optional = false) @Column(name = "CVE_CLIENTE") private BigInteger cveCliente; @Basic(optional = false) @Column(name = "ID_FOLIO") private BigInteger idFolio; public CredAmortPK() { } public CredAmortPK(BigInteger cveCliente, BigInteger idFolio) { this.cveCliente = cveCliente; this.idFolio = idFolio; } public BigInteger getCveCliente() { return cveCliente; } public void setCveCliente(BigInteger cveCliente) { this.cveCliente = cveCliente; } public BigInteger getIdFolio() { return idFolio; } public void setIdFolio(BigInteger idFolio) { this.idFolio = idFolio; } @Override public int hashCode() { int hash = 0; hash += (cveCliente != null ? cveCliente.hashCode() : 0); hash += (idFolio != null ? idFolio.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CredAmortPK)) { return false; } CredAmortPK other = (CredAmortPK) object; if ((this.cveCliente == null && other.cveCliente != null) || (this.cveCliente != null && !this.cveCliente.equals(other.cveCliente))) { return false; } if ((this.idFolio == null && other.idFolio != null) || (this.idFolio != null && !this.idFolio.equals(other.idFolio))) { return false; } return true; } @Override public String toString() { return "com.puntodeventa.persistence.Entity.CredAmortPK[ cveCliente=" + cveCliente + ", idFolio=" + idFolio + " ]"; } }
lalongooo/POSSpring
src/main/java/com/puntodeventa/global/Entity/CredAmortPK.java
Java
mit
2,149
'use strict'; describe('LoginController', function () { // Load the parent app beforeEach(module('demoSite')); var $controller; var $scope, controller, $window; beforeEach(inject(function (_$controller_) { $controller = _$controller_; $scope = {}; $window = { location: {}, open: function () { } }; controller = $controller('LoginController', { $scope: $scope, $window: $window }); })); describe('isTapIn variable', function () { it('is true by default', function () { expect($scope.isTapIn).toBe(true); }); it('is true if that value is passed to initiateLogin', function () { $scope.initiateLogin(true); expect($scope.isTapIn).toBe(true); }); it('is false if that value is passed to initiateLogin', function () { $scope.initiateLogin(false); expect($scope.isTapIn).toBe(false); }); }); describe('popup creation', function () { it('should pop up a new window when a new login is initiated', function () { spyOn($window, 'open'); $scope.initiateLogin(true); expect($window.open).toHaveBeenCalled(); }) }) describe('error message framework', function () { it('should convert error codes to friendly messages', function () { expect($scope.showError).toBe(false); // Loop through each property in the errorMessages object and check that it is displayed properly. for (var property in $scope.errorMessages) { if ($scope.errorMessages.hasOwnProperty(property)) { $scope.showErrorFromCode(property); expect($scope.errorMessage).toBe($scope.errorMessages[property]); expect($scope.showError).toBe(true); } } }); it('should handle lack of connection to the server', function () { expect($scope.showError).toBe(false); $scope.handleGetURLError(); expect($scope.errorMessage).toBe($scope.errorMessages["no_connection"]); expect($scope.showError).toBe(true); }); it('should hide any errors when a new login is initiated', function () { $scope.showError = true; $scope.initiateLogin(true); expect($scope.showError).toBe(false); }) }); describe('polling framework', function () { beforeEach(function () { // Because the framework utilizes a popup, these variables are NOT inside the controller. dataHasReturned = false; returnedData = new Object(); }); it('should handle manually closing of the popup window', function () { $scope.popupWindow = window.open(); $scope.popupWindow.close(); $scope.pollPopupForCompletedAuth(); expect(dataHasReturned).toBe(false); }); it('should present an error if one comes back from the server', function () { dataHasReturned = true; returnedData.error = "access_denied"; expect($scope.showError).toBe(false); $scope.pollPopupForCompletedAuth(); expect($scope.showError).toBe(true); expect(dataHasReturned).toBe(false); }); it('should redirect the user to the auth page when proper data has returned', function () { dataHasReturned = true; returnedData = { subject: "1111-2222-3333-4444", username: "Test User", email: "testemail@privakey.invalid", details: "Tech+Details" }; $scope.pollPopupForCompletedAuth(); expect($window.location.href).toBe('/#/auth'); }); }) });
privakey/privakey-nodejs
sample/assets/js/angular/login/login.module.spec.js
JavaScript
mit
3,904
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ploeh.Samples.AssortedCodeSnippets.Cycle.Lazy { public class B : IB { private readonly IC c; public B(IC c) { if (c == null) { throw new ArgumentNullException("c"); } this.c = c; } #region IB Members public string AugmentHello() { return "InvariantB:" + this.c.Hello(); } #endregion } }
owolp/Telerik-Academy
Module-2/Design-Patterns/Materials/DI.NET/AssortedCodeSnippets/AssortedCodeSnippets/Cycle/Lazy/B.cs
C#
mit
552
/* ConnectionErrorView.java Copyright (c) 2017 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.manager.setting; import android.content.Context; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import org.deviceconnect.android.manager.R; import org.deviceconnect.android.manager.core.plugin.CommunicationHistory; import org.deviceconnect.android.manager.core.plugin.ConnectionError; import org.deviceconnect.android.manager.core.plugin.DevicePlugin; import java.util.List; /** * プラグインとの接続に関するエラーの表示. * * @author NTT DOCOMO, INC. */ public class ConnectionErrorView extends LinearLayout { private static final int DEFAULT_VISIBILITY = View.GONE; private final TextView mErrorView; public ConnectionErrorView(final Context context, final @Nullable AttributeSet attrs) { super(context, attrs); setVisibility(DEFAULT_VISIBILITY); View layout = LayoutInflater.from(context).inflate(R.layout.layout_plugin_connection_error, this); mErrorView = (TextView) layout.findViewById(R.id.plugin_connection_error_message); } public void showErrorMessage(final DevicePlugin plugin) { ConnectionError error = plugin.getCurrentConnectionError(); if (error != null) { showErrorMessage(error); return; } CommunicationHistory history = plugin.getHistory(); List<CommunicationHistory.Info> timeouts = history.getNotRespondedCommunications(); List<CommunicationHistory.Info> responses = history.getRespondedCommunications(); if (timeouts.size() > 0) { CommunicationHistory.Info timeout = timeouts.get(timeouts.size() - 1); boolean showsWarning; if (responses.size() > 0) { CommunicationHistory.Info response = responses.get(responses.size() - 1); showsWarning = response.getStartTime() < timeout.getStartTime(); } else { showsWarning = true; } // NOTE: 最も直近のリクエストについて応答タイムアウトが発生した場合のみ下記のエラーを表示. if (showsWarning) { showErrorMessage(R.string.dconnect_error_response_timeout); } return; } setVisibility(DEFAULT_VISIBILITY); mErrorView.setText(null); } public void showErrorMessage(final ConnectionError error) { if (error != null) { int messageId = -1; switch (error) { case NOT_PERMITTED: messageId = R.string.dconnect_error_connection_not_permitted; break; case NOT_RESPONDED: messageId = R.string.dconnect_error_connection_timeout; break; case TERMINATED: messageId = R.string.dconnect_error_connection_terminated; break; case INTERNAL_ERROR: messageId = R.string.dconnect_error_connection_internal_error; break; default: break; } showErrorMessage(messageId); } } private void showErrorMessage(final int messageId) { if (messageId != -1) { String message = getContext().getString(messageId); mErrorView.setText(message); setVisibility(View.VISIBLE); } } }
TakayukiHoshi1984/DeviceConnect-Android
dConnectManager/dConnectManager/dconnect-manager-app/src/main/java/org/deviceconnect/android/manager/setting/ConnectionErrorView.java
Java
mit
3,763
/* ========================================================= * bootstrap-datepicker.js * http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ (function ($) { var $window = $(window); function UTCDate() { return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday() { var today = new Date(); return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); } // Picker object var Datepicker = function (element, options) { var that = this; this._process_options(options); this.element = $(element); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false; this.hasInput = this.component && this.element.find('input').length; if (this.component && this.component.length === 0) this.component = false; this.picker = $(DPGlobal.template); this._buildEvents(); this._attachEvents(); if (this.isInline) { this.picker.addClass('datepicker-inline').appendTo(this.element); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.o.rtl) { this.picker.addClass('datepicker-rtl'); this.picker.find('.prev i, .next i') .toggleClass('icon-arrow-left icon-arrow-right'); } this.viewMode = this.o.startView; if (this.o.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function (i, val) { return parseInt(val) + 1; }); this._allow_update = false; this.setStartDate(this._o.startDate); this.setEndDate(this._o.endDate); this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled); this.fillDow(); this.fillMonths(); this._allow_update = true; this.update(); this.showMode(); if (this.isInline) { this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _process_options: function (opts) { // Store raw options for reference this._o = $.extend({}, this._o, opts); // Processed options var o = this.o = $.extend({}, this._o); // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" var lang = o.language; if (!dates[lang]) { lang = lang.split('-')[0]; if (!dates[lang]) lang = defaults.language; } o.language = lang; switch (o.startView) { case 2: case 'decade': o.startView = 2; break; case 1: case 'year': o.startView = 1; break; default: o.startView = 0; } switch (o.minViewMode) { case 1: case 'months': o.minViewMode = 1; break; case 2: case 'years': o.minViewMode = 2; break; default: o.minViewMode = 0; } o.startView = Math.max(o.startView, o.minViewMode); o.weekStart %= 7; o.weekEnd = ((o.weekStart + 6) % 7); var format = DPGlobal.parseFormat(o.format); if (o.startDate !== -Infinity) { if (!!o.startDate) { if (o.startDate instanceof Date) o.startDate = this._local_to_utc(this._zero_time(o.startDate)); else o.startDate = DPGlobal.parseDate(o.startDate, format, o.language); } else { o.startDate = -Infinity; } } if (o.endDate !== Infinity) { if (!!o.endDate) { if (o.endDate instanceof Date) o.endDate = this._local_to_utc(this._zero_time(o.endDate)); else o.endDate = DPGlobal.parseDate(o.endDate, format, o.language); } else { o.endDate = Infinity; } } o.daysOfWeekDisabled = o.daysOfWeekDisabled || []; if (!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/); o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) { return parseInt(d, 10); }); var plc = String(o.orientation).toLowerCase().split(/\s+/g), _plc = o.orientation.toLowerCase(); plc = $.grep(plc, function (word) { return (/^auto|left|right|top|bottom$/).test(word); }); o.orientation = { x: 'auto', y: 'auto' }; if (!_plc || _plc === 'auto') ; // no action else if (plc.length === 1) { switch (plc[0]) { case 'top': case 'bottom': o.orientation.y = plc[0]; break; case 'left': case 'right': o.orientation.x = plc[0]; break; } } else { _plc = $.grep(plc, function (word) { return (/^left|right$/).test(word); }); o.orientation.x = _plc[0] || 'auto'; _plc = $.grep(plc, function (word) { return (/^top|bottom$/).test(word); }); o.orientation.y = _plc[0] || 'auto'; } }, _events: [], _secondaryEvents: [], _applyEvents: function (evs) { for (var i = 0, el, ev; i < evs.length; i++) { el = evs[i][0]; ev = evs[i][1]; el.on(ev); } }, _unapplyEvents: function (evs) { for (var i = 0, el, ev; i < evs.length; i++) { el = evs[i][0]; ev = evs[i][1]; el.off(ev); } }, _buildEvents: function () { if (this.isInput) { // single input this._events = [ [this.element, { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }] ]; } else if (this.component && this.hasInput) { // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')) { // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } this._secondaryEvents = [ [this.picker, { click: $.proxy(this.click, this) }], [$(window), { resize: $.proxy(this.place, this) }], [$(document), { mousedown: $.proxy(function (e) { // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || this.element.find(e.target).length || this.picker.is(e.target) || this.picker.find(e.target).length )) { this.hide(); } }, this) }] ]; }, _attachEvents: function () { this._detachEvents(); this._applyEvents(this._events); }, _detachEvents: function () { this._unapplyEvents(this._events); }, _attachSecondaryEvents: function () { this._detachSecondaryEvents(); this._applyEvents(this._secondaryEvents); }, _detachSecondaryEvents: function () { this._unapplyEvents(this._secondaryEvents); }, _trigger: function (event, altdate) { var date = altdate || this.date, local_date = this._utc_to_local(date); this.element.trigger({ type: event, date: local_date, format: $.proxy(function (altformat) { var format = altformat || this.o.format; return DPGlobal.formatDate(date, format, this.o.language); }, this) }); }, show: function (e) { if (!this.isInline) this.picker.appendTo('body'); this.picker.show(); this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); this.place(); this._attachSecondaryEvents(); if (e) { e.preventDefault(); } this._trigger('show'); }, hide: function (e) { if (this.isInline) return; if (!this.picker.is(':visible')) return; this.picker.hide().detach(); this._detachSecondaryEvents(); this.viewMode = this.o.startView; this.showMode(); if ( this.o.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this._trigger('hide'); }, remove: function () { this.hide(); this._detachEvents(); this._detachSecondaryEvents(); this.picker.remove(); delete this.element.data().datepicker; if (!this.isInput) { delete this.element.data().date; } }, _utc_to_local: function (utc) { return new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000)); }, _local_to_utc: function (local) { return new Date(local.getTime() - (local.getTimezoneOffset() * 60000)); }, _zero_time: function (local) { return new Date(local.getFullYear(), local.getMonth(), local.getDate()); }, _zero_utc_time: function (utc) { return new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate())); }, getDate: function () { return this._utc_to_local(this.getUTCDate()); }, getUTCDate: function () { return this.date; }, setDate: function (d) { this.setUTCDate(this._local_to_utc(d)); }, setUTCDate: function (d) { this.date = d; this.setValue(); }, setValue: function () { var formatted = this.getFormattedDate(); if (!this.isInput) { if (this.component) { this.element.find('input').val(formatted).change(); } } else { this.element.val(formatted).change(); } }, getFormattedDate: function (format) { if (format === undefined) format = this.o.format; return DPGlobal.formatDate(this.date, format, this.o.language); }, setStartDate: function (startDate) { this._process_options({ startDate: startDate }); this.update(); this.updateNavArrows(); }, setEndDate: function (endDate) { this._process_options({ endDate: endDate }); this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function (daysOfWeekDisabled) { this._process_options({ daysOfWeekDisabled: daysOfWeekDisabled }); this.update(); this.updateNavArrows(); }, place: function () { if (this.isInline) return; var calendarWidth = this.picker.outerWidth(), calendarHeight = this.picker.outerHeight(), visualPadding = 10, windowWidth = $window.width(), windowHeight = $window.height(), scrollTop = $window.scrollTop(); var zIndex = parseInt(this.element.parents().filter(function () { return $(this).css('z-index') != 'auto'; }).first().css('z-index')) + 10; var offset = this.component ? this.component.parent().offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false); var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false); var left = offset.left, top = offset.top; this.picker.removeClass( 'datepicker-orient-top datepicker-orient-bottom ' + 'datepicker-orient-right datepicker-orient-left' ); if (this.o.orientation.x !== 'auto') { this.picker.addClass('datepicker-orient-' + this.o.orientation.x); if (this.o.orientation.x === 'right') left -= calendarWidth - width; } // auto x orientation is best-placement: if it crosses a window // edge, fudge it sideways else { // Default to left this.picker.addClass('datepicker-orient-left'); if (offset.left < 0) left -= offset.left - visualPadding; else if (offset.left + calendarWidth > windowWidth) left = windowWidth - calendarWidth - visualPadding; } // auto y orientation is best-situation: top or bottom, no fudging, // decision based on which shows more of the calendar var yorient = this.o.orientation.y, top_overflow, bottom_overflow; if (yorient === 'auto') { top_overflow = -scrollTop + offset.top - calendarHeight; bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight); if (Math.max(top_overflow, bottom_overflow) === bottom_overflow) yorient = 'top'; else yorient = 'bottom'; } this.picker.addClass('datepicker-orient-' + yorient); if (yorient === 'top') top += height; else top -= calendarHeight + parseInt(this.picker.css('padding-top')); this.picker.css({ top: top, left: left, zIndex: zIndex }); }, _allow_update: true, update: function () { if (!this._allow_update) return; var oldDate = new Date(this.date), date, fromArgs = false; if (arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) { date = arguments[0]; if (date instanceof Date) date = this._local_to_utc(date); fromArgs = true; } else { date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); delete this.element.data().date; } this.date = DPGlobal.parseDate(date, this.o.format, this.o.language); if (fromArgs) { // setting date by clicking this.setValue(); } else if (date) { // setting date by typing if (oldDate.getTime() !== this.date.getTime()) this._trigger('changeDate'); } else { // clearing date this._trigger('clearDate'); } if (this.date < this.o.startDate) { this.viewDate = new Date(this.o.startDate); this.date = new Date(this.o.startDate); } else if (this.date > this.o.endDate) { this.viewDate = new Date(this.o.endDate); this.date = new Date(this.o.endDate); } else { this.viewDate = new Date(this.date); this.date = new Date(this.date); } this.fill(); }, fillDow: function () { var dowCnt = this.o.weekStart, html = '<tr>'; if (this.o.calendarWeeks) { var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.o.weekStart + 7) { html += '<th class="dow">' + dates[this.o.language].daysMin[(dowCnt++) % 7] + '</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function () { var html = '', i = 0; while (i < 12) { html += '<span class="month">' + dates[this.o.language].monthsShort[i++] + '</span>'; } this.picker.find('.datepicker-months td').html(html); }, setRange: function (range) { if (!range || !range.length) delete this.range; else this.range = $.map(range, function (d) { return d.valueOf(); }); this.fill(); }, getClassNames: function (date) { var cls = [], year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), currentDate = this.date.valueOf(), today = new Date(); if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) { cls.push('old'); } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) { cls.push('new'); } // Compare internal UTC date with local today, not UTC today if (this.o.todayHighlight && date.getUTCFullYear() == today.getFullYear() && date.getUTCMonth() == today.getMonth() && date.getUTCDate() == today.getDate()) { cls.push('today'); } if (currentDate && date.valueOf() == currentDate) { cls.push('active'); } if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate || $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) { cls.push('disabled'); } if (this.range) { if (date > this.range[0] && date < this.range[this.range.length - 1]) { cls.push('range'); } if ($.inArray(date.valueOf(), this.range) != -1) { cls.push('selected'); } } return cls; }, fill: function () { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity, startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity, endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity, endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity, currentDate = this.date && this.date.valueOf(), tooltip; this.picker.find('.datepicker-days thead th.datepicker-switch') .text(dates[this.o.language].months[month] + ' ' + year); this.picker.find('tfoot th.today') .text(dates[this.o.language].today) .toggle(this.o.todayBtn !== false); this.picker.find('tfoot th.clear') .text(dates[this.o.language].clear) .toggle(this.o.clearBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month - 1, 28, 0, 0, 0, 0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7) % 7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while (prevMonth.valueOf() < nextMonth) { if (prevMonth.getUTCDay() == this.o.weekStart) { html.push('<tr>'); if (this.o.calendarWeeks) { // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay()) % 7 * 864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">' + calWeek + '</td>'); } } clsName = this.getClassNames(prevMonth); clsName.push('day'); if (this.o.beforeShowDay !== $.noop) { var before = this.o.beforeShowDay(this._utc_to_local(prevMonth)); if (before === undefined) before = {}; else if (typeof (before) === 'boolean') before = { enabled: before }; else if (typeof (before) === 'string') before = { classes: before }; if (before.enabled === false) clsName.push('disabled'); if (before.classes) clsName = clsName.concat(before.classes.split(/\s+/)); if (before.tooltip) tooltip = before.tooltip; } clsName = $.unique(clsName); html.push('<td class="' + clsName.join(' ') + '"' + (tooltip ? ' title="' + tooltip + '"' : '') + '>' + prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() == this.o.weekEnd) { html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate() + 1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var currentYear = this.date && this.date.getUTCFullYear(); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear && currentYear == year) { months.eq(this.date.getUTCMonth()).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth).addClass('disabled'); } if (year == endYear) { months.slice(endMonth + 1).addClass('disabled'); } html = ''; year = parseInt(year / 10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '<span class="year' + (i == -1 ? ' old' : i == 10 ? ' new' : '') + (currentYear == year ? ' active' : '') + (year < startYear || year > endYear ? ' disabled' : '') + '">' + year + '</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function () { if (!this._allow_update) return; var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode) { case 0: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) { this.picker.find('.prev').css({ visibility: 'hidden' }); } else { this.picker.find('.prev').css({ visibility: 'visible' }); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) { this.picker.find('.next').css({ visibility: 'hidden' }); } else { this.picker.find('.next').css({ visibility: 'visible' }); } break; case 1: case 2: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) { this.picker.find('.prev').css({ visibility: 'hidden' }); } else { this.picker.find('.prev').css({ visibility: 'visible' }); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) { this.picker.find('.next').css({ visibility: 'hidden' }); } else { this.picker.find('.next').css({ visibility: 'visible' }); } break; } }, click: function (e) { e.preventDefault(); var target = $(e.target).closest('span, td, th'); if (target.length == 1) { switch (target[0].nodeName.toLowerCase()) { case 'th': switch (target[0].className) { case 'datepicker-switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); switch (this.viewMode) { case 0: this.viewDate = this.moveMonth(this.viewDate, dir); this._trigger('changeMonth', this.viewDate); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); if (this.viewMode === 1) this._trigger('changeYear', this.viewDate); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.o.todayBtn == 'linked' ? null : 'view'; this._setDate(date, which); break; case 'clear': var element; if (this.isInput) element = this.element; else if (this.component) element = this.element.find('input'); if (element) element.val("").change(); this._trigger('changeDate'); this.update(); if (this.o.autoclose) this.hide(); break; } break; case 'span': if (!target.is('.disabled')) { this.viewDate.setUTCDate(1); if (target.is('.month')) { var day = 1; var month = target.parent().find('span').index(target); var year = this.viewDate.getUTCFullYear(); this.viewDate.setUTCMonth(month); this._trigger('changeMonth', this.viewDate); if (this.o.minViewMode === 1) { this._setDate(UTCDate(year, month, day, 0, 0, 0, 0)); } } else { var year = parseInt(target.text(), 10) || 0; var day = 1; var month = 0; this.viewDate.setUTCFullYear(year); this._trigger('changeYear', this.viewDate); if (this.o.minViewMode === 2) { this._setDate(UTCDate(year, month, day, 0, 0, 0, 0)); } } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')) { var day = parseInt(target.text(), 10) || 1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day, 0, 0, 0, 0)); } break; } } }, _setDate: function (date, which) { if (!which || which == 'date') this.date = new Date(date); if (!which || which == 'view') this.viewDate = new Date(date); this.fill(); this.setValue(); this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component) { element = this.element.find('input'); } if (element) { element.change(); } if (this.o.autoclose && (!which || which == 'date')) { this.hide(); } }, moveMonth: function (date, dir) { if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1) { test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function () { return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function () { return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i = 0; i < mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function () { return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()) { new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function (date, dir) { return this.moveMonth(date, dir * 12); }, dateWithinRange: function (date) { return date >= this.o.startDate && date <= this.o.endDate; }, keydown: function (e) { if (this.picker.is(':not(:visible)')) { if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch (e.keyCode) { case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.o.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; if (e.ctrlKey) { newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); this._trigger('changeYear', this.viewDate); } else if (e.shiftKey) { newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); this._trigger('changeMonth', this.viewDate); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)) { this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.o.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; if (e.ctrlKey) { newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); this._trigger('changeYear', this.viewDate); } else if (e.shiftKey) { newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); this._trigger('changeMonth', this.viewDate); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir * 7); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)) { this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter this.hide(); e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged) { this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component) { element = this.element.find('input'); } if (element) { element.change(); } } }, showMode: function (dir) { if (dir) { this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir)); } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover. Method show() does not set display css correctly and datepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datepicker-' + DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); } }; var DateRangePicker = function (element, options) { this.element = $(element); this.inputs = $.map(options.inputs, function (i) { return i.jquery ? i[0] : i; }); delete options.inputs; $(this.inputs) .datepicker(options) .bind('changeDate', $.proxy(this.dateUpdated, this)); this.pickers = $.map(this.inputs, function (i) { return $(i).data('datepicker'); }); this.updateDates(); }; DateRangePicker.prototype = { updateDates: function () { this.dates = $.map(this.pickers, function (i) { return i.date; }); this.updateRanges(); }, updateRanges: function () { var range = $.map(this.dates, function (d) { return d.valueOf(); }); $.each(this.pickers, function (i, p) { p.setRange(range); }); }, dateUpdated: function (e) { var dp = $(e.target).data('datepicker'), new_date = dp.getUTCDate(), i = $.inArray(e.target, this.inputs), l = this.inputs.length; if (i == -1) return; if (new_date < this.dates[i]) { // Date being moved earlier/left while (i >= 0 && new_date < this.dates[i]) { this.pickers[i--].setUTCDate(new_date); } } else if (new_date > this.dates[i]) { // Date being moved later/right while (i < l && new_date > this.dates[i]) { this.pickers[i++].setUTCDate(new_date); } } this.updateDates(); }, remove: function () { $.map(this.pickers, function (p) { p.remove(); }); delete this.element.data().datepicker; } }; function opts_from_el(el, prefix) { // Derive options from element data-attrs var data = $(el).data(), out = {}, inkey, replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'), prefix = new RegExp('^' + prefix.toLowerCase()); for (var key in data) if (prefix.test(key)) { inkey = key.replace(replace, function (_, a) { return a.toLowerCase(); }); out[inkey] = data[key]; } return out; } function opts_from_locale(lang) { // Derive options from locale plugins var out = {}; // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" if (!dates[lang]) { lang = lang.split('-')[0] if (!dates[lang]) return; } var d = dates[lang]; $.each(locale_opts, function (i, k) { if (k in d) out[k] = d[k]; }); return out; } var old = $.fn.datepicker; $.fn.datepicker = function (option) { var args = Array.apply(null, arguments); args.shift(); var internal_return, this_return; this.each(function () { var $this = $(this), data = $this.data('datepicker'), options = typeof option == 'object' && option; if (!data) { var elopts = opts_from_el(this, 'date'), // Preliminary otions xopts = $.extend({}, defaults, elopts, options), locopts = opts_from_locale(xopts.language), // Options priority: js args, data-attrs, locales, defaults opts = $.extend({}, defaults, locopts, elopts, options); if ($this.is('.input-daterange') || opts.inputs) { var ropts = { inputs: opts.inputs || $this.find('input').toArray() }; $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts)))); } else { $this.data('datepicker', (data = new Datepicker(this, opts))); } } if (typeof option == 'string' && typeof data[option] == 'function') { internal_return = data[option].apply(data, args); if (internal_return !== undefined) return false; } }); if (internal_return !== undefined) return internal_return; else return this; }; var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, orientation: "auto", rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; var locale_opts = $.fn.datepicker.locale_opts = [ 'format', 'rtl', 'weekStart' ]; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today", clear: "Clear" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function (format) { // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0) { throw new Error("Invalid date format."); } return { separators: separators, parts: parts }; }, parseDate: function (date, format, language) { if (date instanceof Date) return date; if (typeof format === 'string') format = DPGlobal.parseFormat(format); if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) { var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i = 0; i < parts.length; i++) { part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch (part[2]) { case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } var parts = date && date.match(this.nonpunctuation) || [], date = new Date(), parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function (d, v) { return d.setUTCFullYear(v); }, yy: function (d, v) { return d.setUTCFullYear(2000 + v); }, m: function (d, v) { if (isNaN(d)) return d; v -= 1; while (v < 0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) d.setUTCDate(d.getUTCDate() - 1); return d; }, d: function (d, v) { return d.setUTCDate(v); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length != fparts.length) { fparts = $(fparts).filter(function (i, p) { return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder if (parts.length == fparts.length) { for (var i = 0, cnt = fparts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)) { switch (part) { case 'MM': filtered = $(dates[language].months).filter(function () { var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function () { var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } for (var i = 0, _date, s; i < setters_order.length; i++) { s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) { _date = new Date(date); setters_map[s](_date, parsed[s]); if (!isNaN(_date)) date = _date; } } } return date; }, formatDate: function (date, format, language) { if (typeof format === 'string') format = DPGlobal.parseFormat(format); var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; var date = [], seps = $.extend([], format.separators); for (var i = 0, cnt = format.parts.length; i <= cnt; i++) { if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>' + '<tr>' + '<th class="prev">&laquo;</th>' + '<th colspan="5" class="datepicker-switch"></th>' + '<th class="next">&raquo;</th>' + '</tr>' + '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>' }; DPGlobal.template = '<div class="datepicker">' + '<div class="datepicker-days">' + '<table class=" table-condensed">' + DPGlobal.headTemplate + '<tbody></tbody>' + DPGlobal.footTemplate + '</table>' + '</div>' + '<div class="datepicker-months">' + '<table class="table-condensed">' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table>' + '</div>' + '<div class="datepicker-years">' + '<table class="table-condensed">' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table>' + '</div>' + '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; /* DATEPICKER NO CONFLICT * =================== */ $.fn.datepicker.noConflict = function () { $.fn.datepicker = old; return this; }; /* DATEPICKER DATA-API * ================== */ $(document).on( 'focus.datepicker.data-api click.datepicker.data-api', '[data-provide="datepicker"]', function (e) { var $this = $(this); if ($this.data('datepicker')) return; e.preventDefault(); // component click requires us to explicitly show it $this.datepicker('show'); } ); $(function () { $('[data-provide="datepicker-inline"]').datepicker(); }); }(window.jQuery)); /** * Arabic translation for bootstrap-datepicker * Mohammed Alshehri <alshehri866@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['ar'] = { days: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"], daysShort: ["أحد", "اثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت", "أحد"], daysMin: ["ح", "ن", "ث", "ع", "خ", "ج", "س", "ح"], months: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"], monthsShort: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"], today: "هذا اليوم", rtl: true }; }(jQuery)); /** * Bulgarian translation for bootstrap-datepicker * Apostol Apostolov <apostol.s.apostolov@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['bg'] = { days: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота", "Неделя"], daysShort: ["Нед", "Пон", "Вто", "Сря", "Чет", "Пет", "Съб", "Нед"], daysMin: ["Н", "П", "В", "С", "Ч", "П", "С", "Н"], months: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Ян", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Ное", "Дек"], today: "днес" }; }(jQuery)); /** * Catalan translation for bootstrap-datepicker * J. Garcia <jogaco.en@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['ca'] = { days: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte", "Diumenge"], daysShort: ["Diu", "Dil", "Dmt", "Dmc", "Dij", "Div", "Dis", "Diu"], daysMin: ["dg", "dl", "dt", "dc", "dj", "dv", "ds", "dg"], months: ["Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"], monthsShort: ["Gen", "Feb", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Des"], today: "Avui" }; }(jQuery)); /** * Czech translation for bootstrap-datepicker * Matěj Koubík <matej@koubik.name> * Fixes by Michal Remiš <michal.remis@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['cs'] = { days: ["Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota", "Neděle"], daysShort: ["Ned", "Pon", "Úte", "Stř", "Čtv", "Pát", "Sob", "Ned"], daysMin: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So", "Ne"], months: ["Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"], monthsShort: ["Led", "Úno", "Bře", "Dub", "Kvě", "Čer", "Čnc", "Srp", "Zář", "Říj", "Lis", "Pro"], today: "Dnes" }; }(jQuery)); /** * Danish translation for bootstrap-datepicker * Christian Pedersen <http://github.com/chripede> */ ; (function ($) { $.fn.datepicker.dates['da'] = { days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"], daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"], daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"], months: ["Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"], today: "I Dag" }; }(jQuery)); /** * German translation for bootstrap-datepicker * Sam Zurcher <sam@orelias.ch> */ ; (function ($) { $.fn.datepicker.dates['de'] = { days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"], daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam", "Son"], daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"], months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"], today: "Heute", weekStart: 1, format: "dd.mm.yyyy" }; }(jQuery)); /** * Greek translation for bootstrap-datepicker */ ; (function ($) { $.fn.datepicker.dates['el'] = { days: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο", "Κυριακή"], daysShort: ["Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ", "Κυρ"], daysMin: ["Κυ", "Δε", "Τρ", "Τε", "Πε", "Πα", "Σα", "Κυ"], months: ["Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"], monthsShort: ["Ιαν", "Φεβ", "Μαρ", "Απρ", "Μάι", "Ιουν", "Ιουλ", "Αυγ", "Σεπ", "Οκτ", "Νοε", "Δεκ"], today: "Σήμερα" }; }(jQuery)); /** * Spanish translation for bootstrap-datepicker * Bruno Bonamin <bruno.bonamin@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['es'] = { days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"], daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"], daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"], months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"], monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"], today: "Hoy" }; }(jQuery)); /** * Estonian translation for bootstrap-datepicker * Ando Roots <https://github.com/anroots> */ ; (function ($) { $.fn.datepicker.dates['et'] = { days: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev", "Pühapäev"], daysShort: ["Püh", "Esm", "Tei", "Kol", "Nel", "Ree", "Lau", "Sun"], daysMin: ["P", "E", "T", "K", "N", "R", "L", "P"], months: ["Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"], monthsShort: ["Jaan", "Veeb", "Märts", "Apr", "Mai", "Juuni", "Juuli", "Aug", "Sept", "Okt", "Nov", "Dets"], today: "Täna" }; }(jQuery)); /** * Finnish translation for bootstrap-datepicker * Jaakko Salonen <https://github.com/jsalonen> */ ; (function ($) { $.fn.datepicker.dates['fi'] = { days: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai", "sunnuntai"], daysShort: ["sun", "maa", "tii", "kes", "tor", "per", "lau", "sun"], daysMin: ["su", "ma", "ti", "ke", "to", "pe", "la", "su"], months: ["tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kesäkuu", "heinäkuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu"], monthsShort: ["tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mar", "jou"], today: "tänään", weekStart: 1, format: "d.m.yyyy" }; }(jQuery)); /** * French translation for bootstrap-datepicker * Nico Mollet <nico.mollet@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['fr'] = { days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"], daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"], daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"], months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"], monthsShort: ["Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Dec"], today: "Aujourd'hui", clear: "Effacer", weekStart: 1, format: "dd/mm/yyyy" }; }(jQuery)); /** * Hebrew translation for bootstrap-datepicker * Sagie Maoz <sagie@maoz.info> */ ; (function ($) { $.fn.datepicker.dates['he'] = { days: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"], daysShort: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"], daysMin: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"], months: ["ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר"], monthsShort: ["ינו", "פבר", "מרץ", "אפר", "מאי", "יונ", "יול", "אוג", "ספט", "אוק", "נוב", "דצמ"], today: "היום", rtl: true }; }(jQuery)); /** * Croatian localisation */ ; (function ($) { $.fn.datepicker.dates['hr'] = { days: ["Nedjelja", "Ponedjelja", "Utorak", "Srijeda", "Četrtak", "Petak", "Subota", "Nedjelja"], daysShort: ["Ned", "Pon", "Uto", "Srr", "Čet", "Pet", "Sub", "Ned"], daysMin: ["Ne", "Po", "Ut", "Sr", "Če", "Pe", "Su", "Ne"], months: ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"], monthsShort: ["Sije", "Velj", "Ožu", "Tra", "Svi", "Lip", "Jul", "Kol", "Ruj", "Lis", "Stu", "Pro"], today: "Danas" }; }(jQuery)); /** * Hungarian translation for bootstrap-datepicker * Sotus László <lacisan@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['hu'] = { days: ["Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat", "Vasárnap"], daysShort: ["Vas", "Hét", "Ked", "Sze", "Csü", "Pén", "Szo", "Vas"], daysMin: ["Va", "Hé", "Ke", "Sz", "Cs", "Pé", "Sz", "Va"], months: ["Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"], monthsShort: ["Jan", "Feb", "Már", "Ápr", "Máj", "Jún", "Júl", "Aug", "Sze", "Okt", "Nov", "Dec"], today: "Ma", weekStart: 1, format: "yyyy.mm.dd" }; }(jQuery)); /** * Bahasa translation for bootstrap-datepicker * Azwar Akbar <azwar.akbar@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['id'] = { days: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"], daysShort: ["Mgu", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Mgu"], daysMin: ["Mg", "Sn", "Sl", "Ra", "Ka", "Ju", "Sa", "Mg"], months: ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ags", "Sep", "Okt", "Nov", "Des"], today: "Hari Ini", clear: "Kosongkan" }; }(jQuery)); /** * Icelandic translation for bootstrap-datepicker * Hinrik Örn Sigurðsson <hinrik.sig@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['is'] = { days: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur", "Sunnudagur"], daysShort: ["Sun", "Mán", "Þri", "Mið", "Fim", "Fös", "Lau", "Sun"], daysMin: ["Su", "Má", "Þr", "Mi", "Fi", "Fö", "La", "Su"], months: ["Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maí", "Jún", "Júl", "Ágú", "Sep", "Okt", "Nóv", "Des"], today: "Í Dag" }; }(jQuery)); /** * Italian translation for bootstrap-datepicker * Enrico Rubboli <rubboli@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['it'] = { days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"], daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"], daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"], months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"], today: "Oggi", weekStart: 1, format: "dd/mm/yyyy" }; }(jQuery)); /** * Japanese translation for bootstrap-datepicker * Norio Suzuki <https://github.com/suzuki/> */ ; (function ($) { $.fn.datepicker.dates['ja'] = { days: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜", "日曜"], daysShort: ["日", "月", "火", "水", "木", "金", "土", "日"], daysMin: ["日", "月", "火", "水", "木", "金", "土", "日"], months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], today: "今日", format: "yyyy/mm/dd" }; }(jQuery)); /** * Georgian translation for bootstrap-datepicker * Levan Melikishvili <levani0101@yahoo.com> */ ; (function ($) { $.fn.datepicker.dates['ka'] = { days: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი", "კვირა"], daysShort: ["კვი", "ორშ", "სამ", "ოთხ", "ხუთ", "პარ", "შაბ", "კვი"], daysMin: ["კვ", "ორ", "სა", "ოთ", "ხუ", "პა", "შა", "კვ"], months: ["იანვარი", "თებერვალი", "მარტი", "აპრილი", "მაისი", "ივნისი", "ივლისი", "აგვისტო", "სექტემბერი", "ოქტომები", "ნოემბერი", "დეკემბერი"], monthsShort: ["იან", "თებ", "მარ", "აპრ", "მაი", "ივნ", "ივლ", "აგვ", "სექ", "ოქტ", "ნოე", "დეკ"], today: "დღეს", clear: "გასუფთავება" }; }(jQuery)); /** * Korean translation for bootstrap-datepicker * Gu Youn <http://github.com/guyoun> */ ; (function ($) { $.fn.datepicker.dates['kr'] = { days: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"], daysShort: ["일", "월", "화", "수", "목", "금", "토", "일"], daysMin: ["일", "월", "화", "수", "목", "금", "토", "일"], months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"], monthsShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"] }; }(jQuery)); /** * Lithuanian translation for bootstrap-datepicker * Šarūnas Gliebus <ssharunas@yahoo.co.uk> */ ; (function ($) { $.fn.datepicker.dates['lt'] = { days: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis", "Sekmadienis"], daysShort: ["S", "Pr", "A", "T", "K", "Pn", "Š", "S"], daysMin: ["Sk", "Pr", "An", "Tr", "Ke", "Pn", "Št", "Sk"], months: ["Sausis", "Vasaris", "Kovas", "Balandis", "Gegužė", "Birželis", "Liepa", "Rugpjūtis", "Rugsėjis", "Spalis", "Lapkritis", "Gruodis"], monthsShort: ["Sau", "Vas", "Kov", "Bal", "Geg", "Bir", "Lie", "Rugp", "Rugs", "Spa", "Lap", "Gru"], today: "Šiandien", weekStart: 1 }; }(jQuery)); /** * Latvian translation for bootstrap-datepicker * Artis Avotins <artis@apit.lv> */ ; (function ($) { $.fn.datepicker.dates['lv'] = { days: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena", "Svētdiena"], daysShort: ["Sv", "P", "O", "T", "C", "Pk", "S", "Sv"], daysMin: ["Sv", "Pr", "Ot", "Tr", "Ce", "Pk", "St", "Sv"], months: ["Janvāris", "Februāris", "Marts", "Aprīlis", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jūn", "Jūl", "Aug", "Sep", "Okt", "Nov", "Dec."], today: "Šodien", weekStart: 1 }; }(jQuery)); /** * Macedonian translation for bootstrap-datepicker * Marko Aleksic <psybaron@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['mk'] = { days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"], daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"], daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"], months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"], today: "Денес" }; }(jQuery)); /** * Malay translation for bootstrap-datepicker * Ateman Faiz <noorulfaiz@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['ms'] = { days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu", "Ahad"], daysShort: ["Aha", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab", "Aha"], daysMin: ["Ah", "Is", "Se", "Ra", "Kh", "Ju", "Sa", "Ah"], months: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"], today: "Hari Ini" }; }(jQuery)); /** * Norwegian (bokmål) translation for bootstrap-datepicker * Fredrik Sundmyhr <http://github.com/fsundmyhr> */ ; (function ($) { $.fn.datepicker.dates['nb'] = { days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"], daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"], daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"], months: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"], today: "I Dag" }; }(jQuery)); /** * Dutch translation for bootstrap-datepicker * Reinier Goltstein <mrgoltstein@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['nl'] = { days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"], daysShort: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"], daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"], months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"], monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"], today: "Vandaag" }; }(jQuery)); /** * Norwegian translation for bootstrap-datepicker **/ ; (function ($) { $.fn.datepicker.dates['no'] = { days: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'], daysShort: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'], daysMin: ['Sø', 'Ma', 'Ti', 'On', 'To', 'Fr', 'Lø'], months: ['Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember'], monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'], today: 'I dag', clear: 'Nullstill', weekStart: 0 }; }(jQuery)); /** * Polish translation for bootstrap-datepicker * Robert <rtpm@gazeta.pl> */ ; (function ($) { $.fn.datepicker.dates['pl'] = { days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"], daysShort: ["Nie", "Pn", "Wt", "Śr", "Czw", "Pt", "So", "Nie"], daysMin: ["N", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "N"], months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"], monthsShort: ["Sty", "Lu", "Mar", "Kw", "Maj", "Cze", "Lip", "Sie", "Wrz", "Pa", "Lis", "Gru"], today: "Dzisiaj", weekStart: 1 }; }(jQuery)); /** * Brazilian translation for bootstrap-datepicker * Cauan Cabral <cauan@radig.com.br> */ ; (function ($) { $.fn.datepicker.dates['pt-BR'] = { days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"], daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"], daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"], months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"], today: "Hoje", clear: "Limpar" }; }(jQuery)); /** * Portuguese translation for bootstrap-datepicker * Original code: Cauan Cabral <cauan@radig.com.br> * Tiago Melo <tiago.blackcode@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['pt'] = { days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"], daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"], daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"], months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"], today: "Hoje", clear: "Limpar" }; }(jQuery)); /** * Romanian translation for bootstrap-datepicker * Cristian Vasile <cristi.mie@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['ro'] = { days: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică"], daysShort: ["Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"], daysMin: ["Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ", "Du"], months: ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"], monthsShort: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Astăzi", weekStart: 1 }; }(jQuery)); /** * Serbian latin translation for bootstrap-datepicker * Bojan Milosavlević <milboj@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['rs-latin'] = { days: ["Nedelja", "Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota", "Nedelja"], daysShort: ["Ned", "Pon", "Uto", "Sre", "Čet", "Pet", "Sub", "Ned"], daysMin: ["N", "Po", "U", "Sr", "Č", "Pe", "Su", "N"], months: ["Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"], today: "Danas" }; }(jQuery)); /** * Serbian cyrillic translation for bootstrap-datepicker * Bojan Milosavlević <milboj@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['rs'] = { days: ["Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота", "Недеља"], daysShort: ["Нед", "Пон", "Уто", "Сре", "Чет", "Пет", "Суб", "Нед"], daysMin: ["Н", "По", "У", "Ср", "Ч", "Пе", "Су", "Н"], months: ["Јануар", "Фебруар", "Март", "Април", "Мај", "Јун", "Јул", "Август", "Септембар", "Октобар", "Новембар", "Децембар"], monthsShort: ["Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец"], today: "Данас" }; }(jQuery)); /** * Russian translation for bootstrap-datepicker * Victor Taranenko <darwin@snowdale.com> */ ; (function ($) { $.fn.datepicker.dates['ru'] = { days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"], daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"], daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"], months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"], monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"], today: "Сегодня", weekStart: 1 }; }(jQuery)); /** * Slovak translation for bootstrap-datepicker * Marek Lichtner <marek@licht.sk> * Fixes by Michal Remiš <michal.remis@gmail.com> */ ; (function ($) { $.fn.datepicker.dates["sk"] = { days: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota", "Nedeľa"], daysShort: ["Ned", "Pon", "Uto", "Str", "Štv", "Pia", "Sob", "Ned"], daysMin: ["Ne", "Po", "Ut", "St", "Št", "Pia", "So", "Ne"], months: ["Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Máj", "Jún", "Júl", "Aug", "Sep", "Okt", "Nov", "Dec"], today: "Dnes" }; }(jQuery)); /** * Slovene translation for bootstrap-datepicker * Gregor Rudolf <gregor.rudolf@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['sl'] = { days: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota", "Nedelja"], daysShort: ["Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob", "Ned"], daysMin: ["Ne", "Po", "To", "Sr", "Če", "Pe", "So", "Ne"], months: ["Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"], today: "Danes" }; }(jQuery)); /** * Albanian translation for bootstrap-datepicker * Tomor Pupovci <http://www.github.com/ttomor> */ ; (function ($) { $.fn.datepicker.dates['sq'] = { days: ["E Diel", "E Hënë", "E martē", "E mërkurë", "E Enjte", "E Premte", "E Shtunë", "E Diel"], daysShort: ["Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu", "Die"], daysMin: ["Di", "Hë", "Ma", "Më", "En", "Pr", "Sht", "Di"], months: ["Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"], monthsShort: ["Jan", "Shk", "Mar", "Pri", "Maj", "Qer", "Korr", "Gu", "Sht", "Tet", "Nën", "Dhjet"], today: "Sot" }; }(jQuery)); /** * Swedish translation for bootstrap-datepicker * Patrik Ragnarsson <patrik@starkast.net> */ ; (function ($) { $.fn.datepicker.dates['sv'] = { days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"], daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör", "Sön"], daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö", "Sö"], months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"], today: "I Dag", format: "yyyy-mm-dd", weekStart: 1 }; }(jQuery)); /** * Swahili translation for bootstrap-datepicker * Edwin Mugendi <https://github.com/edwinmugendi> * Source: http://scriptsource.org/cms/scripts/page.php?item_id=entry_detail&uid=xnfaqyzcku */ ; (function ($) { $.fn.datepicker.dates['sw'] = { days: ["Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi", "Jumapili"], daysShort: ["J2", "J3", "J4", "J5", "Alh", "Ij", "J1", "J2"], daysMin: ["2", "3", "4", "5", "A", "I", "1", "2"], months: ["Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba"], monthsShort: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des"], today: "Leo" }; }(jQuery)); /** * Thai translation for bootstrap-datepicker * Suchau Jiraprapot <seroz24@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['th'] = { days: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"], daysShort: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"], daysMin: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"], months: ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"], monthsShort: ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."], today: "วันนี้" }; }(jQuery)); /** * Turkish translation for bootstrap-datepicker * Serkan Algur <kaisercrazy_2@hotmail.com> */ ; (function ($) { $.fn.datepicker.dates['tr'] = { days: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi", "Pazar"], daysShort: ["Pz", "Pzt", "Sal", "Çrş", "Prş", "Cu", "Cts", "Pz"], daysMin: ["Pz", "Pzt", "Sa", "Çr", "Pr", "Cu", "Ct", "Pz"], months: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"], monthsShort: ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"], today: "Bugün", format: "dd.mm.yyyy" }; }(jQuery)); /** * Ukrainian translation for bootstrap-datepicker * Andrey Vityuk <andrey [dot] vityuk [at] gmail.com> */ ; (function ($) { $.fn.datepicker.dates['uk'] = { days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота", "Неділя"], daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Нед"], daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"], months: ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"], monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"], today: "Сьогодні" }; }(jQuery)); /** * Simplified Chinese translation for bootstrap-datepicker * Yuan Cheung <advanimal@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['zh-CN'] = { days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"], daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"], daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"], months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], today: "今日", format: "yyyy年mm月dd日", weekStart: 1 }; }(jQuery)); /** * Traditional Chinese translation for bootstrap-datepicker * Rung-Sheng Jang <daniel@i-trend.co.cc> * FrankWu <frankwu100@gmail.com> Fix more appropriate use of Traditional Chinese habit */ ; (function ($) { $.fn.datepicker.dates['zh-TW'] = { days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"], daysShort: ["週日", "週一", "週二", "週三", "週四", "週五", "週六", "週日"], daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"], months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], today: "今天", format: "yyyy年mm月dd日", weekStart: 1 }; }(jQuery)); var dp; dp = angular.module('ng-bootstrap-datepicker', []); dp.directive('ngDatepicker', function () { return { restrict: 'A', replace: true, scope: { ngOptions: '=', ngModel: '=' }, template: "<div class=\"input-append date\">\n <input type=\"text\"><span class=\"add-on\"><i class=\"icon-th\"></i></span>\n</div>", link: function (scope, element) { scope.inputHasFocus = false; element.datepicker(scope.ngOptions).on('changeDate', function (e) { var defaultFormat, defaultLanguage, format, language; defaultFormat = $.fn.datepicker.defaults.format; format = scope.ngOptions.format || defaultFormat; defaultLanguage = $.fn.datepicker.defaults.language; language = scope.ngOptions.language || defaultLanguage; return scope.$apply(function () { return scope.ngModel = $.fn.datepicker.DPGlobal.formatDate(e.date, format, language); }); }); element.find('input').on('focus', function () { return scope.inputHasFocus = true; }).on('blur', function () { return scope.inputHasFocus = false; }); return scope.$watch('ngModel', function (newValue) { if (!scope.inputHasFocus) { return element.datepicker('update', newValue); } }); } }; });
andrepires/mymoney
Presentation/WebAPI/MyMoney.Presentation.WebAPI/scripts/angular-bootstrap-datepicker.js
JavaScript
mit
90,258
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Rest\IpMessaging\V1; use Twilio\Exceptions\TwilioException; use Twilio\InstanceContext; use Twilio\Options; use Twilio\Serialize; use Twilio\Values; use Twilio\Version; class CredentialContext extends InstanceContext { /** * Initialize the CredentialContext * * @param \Twilio\Version $version Version that contains the resource * @param string $sid The unique string that identifies the resource * @return \Twilio\Rest\IpMessaging\V1\CredentialContext */ public function __construct(Version $version, $sid) { parent::__construct($version); // Path Solution $this->solution = array('sid' => $sid, ); $this->uri = '/Credentials/' . \rawurlencode($sid) . ''; } /** * Fetch a CredentialInstance * * @return CredentialInstance Fetched CredentialInstance * @throws TwilioException When an HTTP error occurs. */ public function fetch() { $params = Values::of(array()); $payload = $this->version->fetch( 'GET', $this->uri, $params ); return new CredentialInstance($this->version, $payload, $this->solution['sid']); } /** * Update the CredentialInstance * * @param array|Options $options Optional Arguments * @return CredentialInstance Updated CredentialInstance * @throws TwilioException When an HTTP error occurs. */ public function update($options = array()) { $options = new Values($options); $data = Values::of(array( 'FriendlyName' => $options['friendlyName'], 'Certificate' => $options['certificate'], 'PrivateKey' => $options['privateKey'], 'Sandbox' => Serialize::booleanToString($options['sandbox']), 'ApiKey' => $options['apiKey'], 'Secret' => $options['secret'], )); $payload = $this->version->update( 'POST', $this->uri, array(), $data ); return new CredentialInstance($this->version, $payload, $this->solution['sid']); } /** * Deletes the CredentialInstance * * @return boolean True if delete succeeds, false otherwise * @throws TwilioException When an HTTP error occurs. */ public function delete() { return $this->version->delete('delete', $this->uri); } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { $context = array(); foreach ($this->solution as $key => $value) { $context[] = "$key=$value"; } return '[Twilio.IpMessaging.V1.CredentialContext ' . \implode(' ', $context) . ']'; } }
unaio/una
upgrade/files/12.1.0-13.0.0.A1/files/plugins/twilio/sdk/src/Twilio/Rest/IpMessaging/V1/CredentialContext.php
PHP
mit
2,928
__author__ = 'sei' DEFAULT_SERIAL = '/dev/ttyUSB0' DEFAULT_BAUDRATE = 57600
sdickreuter/python-pistage
build/lib/PIStage/_defines.py
Python
mit
77
<?php /** * Amathista - PHP Framework * * @author Alex J. Rondón <arondn2@gmail.com> * */ /** * Clase para instancias de relaciones hasMany. */ class AmHasManyRelation extends AmCollectionAbstractRelation{ /** * Después de guardar el registro propietario se debe guardar los registro * relacionados. */ public function afterSave(){ // Se debe actualizar todos los registros relacionados $record = $this->getRecord(); // Si no es un regsitro nuevo se deben acutalizar todas las referencias if(!$record->isNew()){ $foreign = $this->getForeign(); $index = $foreign->getCols(); $table = $foreign->getTableInstance(); $query = $table->all(); $update = false; // Asignar cada campo de la relación foreach ($index as $from => $to){ $value = itemOr($to, $this->beforeIndex); $newValue = $record->get($to); // WHEREWHERE $query->andWhere($from, $value); if($value != $newValue){ $update = true; $query->set($from, $record->get($to)); } } // Ejecutar acctualización if($update) $query->update(); } foreach($this->news as $i => $model){ $this->sync($model); if($model->save()) unset($this->news[$i]); } foreach($this->removeds as $i => $model){ $this->sync($model); if($model->delete()) unset($this->removeds[$i]); } } /** * Hace que una instancia de un modelo pertenezca el registro dueño de la * relación * @param AmModel $model Instancia del modelo a agregar. */ protected function sync(AmModel $model){ // Obtener el reistro propietario de la relación. $record = $this->getRecord(); // Obtener las columnas relacionadas. $index = $this->getForeign()->getCols(); // Realizar asignaciones foreach ($index as $from => $to) $model->set($from, $record ? $record->get($to) : null); } }
SirIdeas/amathista.php
am/exts/am_scheme/relations/AmHasManyRelation.class.php
PHP
mit
1,984
<?php /* interfaces.twig */ class __TwigTemplate_8fdc22b550eaa31e6b5cbe1b1954739cb407d722b679449628dcdbc20319c74b extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("layout/layout.twig", "interfaces.twig", 1); $this->blocks = array( 'title' => array($this, 'block_title'), 'body_class' => array($this, 'block_body_class'), 'page_content' => array($this, 'block_page_content'), ); } protected function doGetParent(array $context) { return "layout/layout.twig"; } protected function doDisplay(array $context, array $blocks = array()) { // line 2 $context["__internal_489fc7173b64d75db52ff7dfbddff6202b25e76cb4ce6bc764856d1454be0973"] = $this->loadTemplate("macros.twig", "interfaces.twig", 2); // line 1 $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_title($context, array $blocks = array()) { echo "Interfaces | "; $this->displayParentBlock("title", $context, $blocks); } // line 4 public function block_body_class($context, array $blocks = array()) { echo "interfaces"; } // line 6 public function block_page_content($context, array $blocks = array()) { // line 7 echo " <div class=\"page-header\"> <h1>Interfaces</h1> </div> "; // line 11 echo $context["__internal_489fc7173b64d75db52ff7dfbddff6202b25e76cb4ce6bc764856d1454be0973"]->macro_render_classes((isset($context["interfaces"]) || array_key_exists("interfaces", $context) ? $context["interfaces"] : (function () { throw new Twig_Error_Runtime('Variable "interfaces" does not exist.', 11, $this->getSourceContext()); })())); echo " "; } public function getTemplateName() { return "interfaces.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 55 => 11, 49 => 7, 46 => 6, 40 => 4, 33 => 3, 29 => 1, 27 => 2, 11 => 1,); } public function getSourceContext() { return new Twig_Source("{% extends \"layout/layout.twig\" %} {% from \"macros.twig\" import render_classes %} {% block title %}Interfaces | {{ parent() }}{% endblock %} {% block body_class 'interfaces' %} {% block page_content %} <div class=\"page-header\"> <h1>Interfaces</h1> </div> {{ render_classes(interfaces) }} {% endblock %} ", "interfaces.twig", "/Users/Edujugon/Code/Documentation/Documentator/vendor/sami/sami/Sami/Resources/themes/default/interfaces.twig"); } }
Edujugon/laravel-google-ads
docs/cache/master/twig/6b/6b14133a52ef0d18ba39782cb4839a649a005fb85d9ffb5b729a39e6f63ecf78.php
PHP
mit
2,804
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 org.kie.server.api.model.instance; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "task-attachment-list") public class TaskAttachmentList { @XmlElement(name="task-attachment") private TaskAttachment[] taskAttachments; public TaskAttachmentList() { } public TaskAttachmentList(TaskAttachment[] taskAttachments) { this.taskAttachments = taskAttachments; } public TaskAttachmentList(List<TaskAttachment> taskAttachments) { this.taskAttachments = taskAttachments.toArray(new TaskAttachment[taskAttachments.size()]); } public TaskAttachment[] getTasks() { return taskAttachments; } public void setTasks(TaskAttachment[] taskAttachments) { this.taskAttachments = taskAttachments; } }
rokn/Count_Words_2015
testing/droolsjbpm-integration-master/kie-server-parent/kie-server-api/src/main/java/org/kie/server/api/model/instance/TaskAttachmentList.java
Java
mit
1,582
// Insert your JS here
Malander/ReneJade
app/scripts/main.js
JavaScript
mit
22
'use strict'; const path = require('path'); // This is a custom Jest transformer turning file imports into filenames. // https://facebook.github.io/jest/docs/en/webpack.html module.exports = { process(src, filename) { const assetFilename = JSON.stringify(path.basename(filename)); if (filename.match(/\.svg$/)) { return `const React = require('react'); module.exports = { __esModule: true, default: ${assetFilename}, ReactComponent: React.forwardRef((props, ref) => ({ $$typeof: Symbol.for('react.element'), type: 'svg', ref: ref, key: null, props: Object.assign({}, props, { children: ${assetFilename} }) })), };`; } return `module.exports = ${assetFilename};`; }, };
lgollut/material-ui
examples/preact/config/jest/fileTransform.js
JavaScript
mit
816
require 'cases/helper' require 'support/schema_dumping_helper' if ActiveRecord::Base.connection.supports_datetime_with_precision? class DateTimePrecisionTest < ActiveRecord::TestCase include SchemaDumpingHelper self.use_transactional_tests = false class Foo < ActiveRecord::Base; end setup do @connection = ActiveRecord::Base.connection Foo.reset_column_information end teardown do @connection.drop_table :foos, if_exists: true end def test_datetime_data_type_with_precision @connection.create_table(:foos, force: true) @connection.add_column :foos, :created_at, :datetime, precision: 0 @connection.add_column :foos, :updated_at, :datetime, precision: 5 assert_equal 0, Foo.columns_hash['created_at'].precision assert_equal 5, Foo.columns_hash['updated_at'].precision end def test_timestamps_helper_with_custom_precision @connection.create_table(:foos, force: true) do |t| t.timestamps precision: 4 end assert_equal 4, Foo.columns_hash['created_at'].precision assert_equal 4, Foo.columns_hash['updated_at'].precision end def test_passing_precision_to_datetime_does_not_set_limit @connection.create_table(:foos, force: true) do |t| t.timestamps precision: 4 end assert_nil Foo.columns_hash['created_at'].limit assert_nil Foo.columns_hash['updated_at'].limit end def test_invalid_datetime_precision_raises_error assert_raises ActiveRecord::ActiveRecordError do @connection.create_table(:foos, force: true) do |t| t.timestamps precision: 7 end end end def test_formatting_datetime_according_to_precision @connection.create_table(:foos, force: true) do |t| t.datetime :created_at, precision: 0 t.datetime :updated_at, precision: 4 end date = ::Time.utc(2014, 8, 17, 12, 30, 0, 999999) Foo.create!(created_at: date, updated_at: date) assert foo = Foo.find_by(created_at: date) assert_equal 1, Foo.where(updated_at: date).count assert_equal date.to_s, foo.created_at.to_s assert_equal date.to_s, foo.updated_at.to_s assert_equal 000000, foo.created_at.usec assert_equal 999900, foo.updated_at.usec end def test_schema_dump_includes_datetime_precision @connection.create_table(:foos, force: true) do |t| t.timestamps precision: 6 end output = dump_table_schema("foos") assert_match %r{t\.datetime\s+"created_at",\s+precision: 6,\s+null: false$}, output assert_match %r{t\.datetime\s+"updated_at",\s+precision: 6,\s+null: false$}, output end if current_adapter?(:PostgreSQLAdapter) def test_datetime_precision_with_zero_should_be_dumped @connection.create_table(:foos, force: true) do |t| t.timestamps precision: 0 end output = dump_table_schema("foos") assert_match %r{t\.datetime\s+"created_at",\s+precision: 0,\s+null: false$}, output assert_match %r{t\.datetime\s+"updated_at",\s+precision: 0,\s+null: false$}, output end end end end
rokn/Count_Words_2015
fetched_code/ruby/date_time_precision_test.rb
Ruby
mit
3,012
import { Increment, Decrement } from '../actions' export default (state = 0, action) => { switch (action.constructor) { case Increment: return state + 1 case Decrement: return state - 1 default: return state } }
jas-chen/typed-redux
examples/counter/src/reducers/index.js
JavaScript
mit
247
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.internal.config; import com.amazonaws.annotation.Immutable; /** * Signer configuration. */ @Immutable public class SignerConfig { private final String signerType; SignerConfig(String signerType) { this.signerType = signerType; } SignerConfig(SignerConfig from) { this.signerType = from.getSignerType(); } public String getSignerType() { return signerType; } @Override public String toString() { return signerType; } }
loremipsumdolor/CastFast
src/com/amazonaws/internal/config/SignerConfig.java
Java
mit
1,109
// +build go1.9 package iris import ( "github.com/kataras/iris/context" "github.com/kataras/iris/core/host" "github.com/kataras/iris/core/router" "github.com/kataras/iris/mvc" ) type ( // Context is the midle-man server's "object" for the clients. // // A New context is being acquired from a sync.Pool on each connection. // The Context is the most important thing on the iris's http flow. // // Developers send responses to the client's request through a Context. // Developers get request information from the client's request by a Context. Context = context.Context // A Handler responds to an HTTP request. // It writes reply headers and data to the Context.ResponseWriter() and then return. // Returning signals that the request is finished; // it is not valid to use the Context after or concurrently with the completion of the Handler call. // // Depending on the HTTP client software, HTTP protocol version, // and any intermediaries between the client and the iris server, // it may not be possible to read from the Context.Request().Body after writing to the context.ResponseWriter(). // Cautious handlers should read the Context.Request().Body first, and then reply. // // Except for reading the body, handlers should not modify the provided Context. // // If Handler panics, the server (the caller of Handler) assumes that the effect of the panic was isolated to the active request. // It recovers the panic, logs a stack trace to the server error log, and hangs up the connection. Handler = context.Handler // A Map is a shortcut of the map[string]interface{}. Map = context.Map // Supervisor is a shortcut of the `host#Supervisor`. // Used to add supervisor configurators on common Runners // without the need of importing the `core/host` package. Supervisor = host.Supervisor // Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. // Party could also be named as 'Join' or 'Node' or 'Group' , Party chosen because it is fun. // // Look the `core/router#APIBuilder` for its implementation. // // A shortcut for the `core/router#Party`, useful when `PartyFunc` is being used. Party = router.Party // Controller is the base controller for the high level controllers instances. // // This base controller is used as an alternative way of building // APIs, the controller can register all type of http methods. // // Keep note that controllers are bit slow // because of the reflection use however it's as fast as possible because // it does preparation before the serve-time handler but still // remains slower than the low-level handlers // such as `Handle, Get, Post, Put, Delete, Connect, Head, Trace, Patch`. // // // All fields that are tagged with iris:"persistence"` // are being persistence and kept between the different requests, // meaning that these data will not be reset-ed on each new request, // they will be the same for all requests. // // An Example Controller can be: // // type IndexController struct { // iris.Controller // } // // func (c *IndexController) Get() { // c.Tmpl = "index.html" // c.Data["title"] = "Index page" // c.Data["message"] = "Hello world!" // } // // Usage: app.Controller("/", new(IndexController)) // // // Another example with persistence data: // // type UserController struct { // iris.Controller // // CreatedAt time.Time `iris:"persistence"` // Title string `iris:"persistence"` // DB *DB `iris:"persistence"` // } // // // Get serves using the User controller when HTTP Method is "GET". // func (c *UserController) Get() { // c.Tmpl = "user/index.html" // c.Data["title"] = c.Title // c.Data["username"] = "kataras " + c.Params.Get("userid") // c.Data["connstring"] = c.DB.Connstring // c.Data["uptime"] = time.Now().Sub(c.CreatedAt).Seconds() // } // // Usage: app.Controller("/user/{id:int}", &UserController{ // CreatedAt: time.Now(), // Title: "User page", // DB: yourDB, // }) // // Look `core/router#APIBuilder#Controller` method too. // // A shortcut for the `mvc#Controller`, // useful when `app.Controller` method is being used. // // A Controller can be declared by importing // the "github.com/kataras/iris/mvc" // package for machines that have not installed go1.9 yet. Controller = mvc.Controller // SessionController is a simple `Controller` implementation // which requires a binded session manager in order to give // direct access to the current client's session via its `Session` field. SessionController = mvc.SessionController // C is the lightweight BaseController type as an alternative of the `Controller` struct type. // It contains only the Name of the controller and the Context, it's the best option // to balance the performance cost reflection uses // if your controller uses the new func output values dispatcher feature; // func(c *ExampleController) Get() string | // (string, string) | // (string, int) | // int | // (int, string | // (string, error) | // error | // (int, error) | // (customStruct, error) | // customStruct | // (customStruct, int) | // (customStruct, string) | // Result or (Result, error) // where Get is an HTTP Method func. // // Look `core/router#APIBuilder#Controller` method too. // // A shortcut for the `mvc#C`, // useful when `app.Controller` method is being used. // // A C controller can be declared by importing // the "github.com/kataras/iris/mvc" as well. C = mvc.C // Response completes the `mvc/activator/methodfunc.Result` interface. // It's being used as an alternative return value which // wraps the status code, the content type, a content as bytes or as string // and an error, it's smart enough to complete the request and send the correct response to the client. // // A shortcut for the `mvc#Response`, // useful when return values from method functions, i.e // GetHelloworld() iris.Response { iris.Response{ Text:"Hello World!", Code: 200 }} Response = mvc.Response // View completes the `mvc/activator/methodfunc.Result` interface. // It's being used as an alternative return value which // wraps the template file name, layout, (any) view data, status code and error. // It's smart enough to complete the request and send the correct response to the client. // // A shortcut for the `mvc#View`, // useful when return values from method functions, i.e // GetUser() iris.View { iris.View{ Name:"user.html", Data: currentUser } } View = mvc.View // Result is a response dispatcher. // All types that complete this interface // can be returned as values from the method functions. // A shortcut for the `mvc#Result` which is a shortcut for `mvc/activator/methodfunc#Result`, // useful when return values from method functions, i.e // GetUser() iris.Result { iris.Response{} or a custom iris.Result } // Can be also used for the TryResult function. Result = mvc.Result ) // Try is a shortcut for the function `mvc.Try` result. // See more at `mvc#Try` documentation. var Try = mvc.Try
grvcoelho/webhulk
vendor/gopkg.in/kataras/iris.v8/go19.go
GO
mit
7,080
/* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.engine.network.activation; /** * Linear activation function that bounds the output to [-1,+1]. This * activation is typically part of a CPPN neural network, such as * HyperNEAT. * <p/> * The idea for this activation function was developed by Ken Stanley, of * the University of Texas at Austin. * http://www.cs.ucf.edu/~kstanley/ */ public class ActivationClippedLinear implements ActivationFunction { @Override public void activationFunction(double[] d, int start, int size) { for (int i = start; i < start + size; i++) { if (d[i] < -1.0) { d[i] = -1.0; } if (d[i] > 1.0) { d[i] = 1.0; } } } /** * {@inheritDoc} */ @Override public double derivativeFunction(double b, double a) { return 1; } /** * {@inheritDoc} */ @Override public boolean hasDerivative() { return true; } /** * {@inheritDoc} */ @Override public double[] getParams() { return ActivationLinear.P; } /** * {@inheritDoc} */ @Override public void setParam(int index, double value) { } /** * {@inheritDoc} */ @Override public String[] getParamNames() { return ActivationLinear.N; } /** * {@inheritDoc} */ @Override public final ActivationFunction clone() { return new ActivationClippedLinear(); } /** * {@inheritDoc} */ @Override public String getFactoryCode() { return null; } }
ladygagapowerbot/bachelor-thesis-implementation
lib/Encog/src/main/java/org/encog/engine/network/activation/ActivationClippedLinear.java
Java
mit
2,484
require 'digest/md5' module Loggr class ExceptionData def self.format_exception(ex, request=nil) res = "" # basic info res = res + sprintf("<b>Exception</b>: %s<br />", ex.message) res = res + sprintf("<b>Type</b>: %s<br />", ex.class) res = res + sprintf("<b>Machine</b>: %s<br />", get_hostname) res = res + sprintf("<b>Language</b>: ruby %s<br />", language_version_string) res = res + "<br />" # web details if !request.nil? res = res + sprintf("<b>Request URL</b>: %s<br />", (request.respond_to?(:url) ? request.url : "#{request.protocol}#{request.host}#{request.request_uri}")) res = res + sprintf("<b>User</b>: %s<br />", get_username) res = res + sprintf("<b>User host address</b>: %s<br />", (request.respond_to?(:remote_ip) ? request.remote_ip : request.ip)) res = res + sprintf("<b>Request Method</b>: %s<br />", request.request_method.to_s) res = res + sprintf("<b>User Agent</b>: %s<br />", request.env['HTTP_USER_AGENT'] || '') res = res + sprintf("<b>Referer</b>: %s<br />", request.env['HTTP_REFERER'] || '') res = res + sprintf("<b>Script Name</b>: %s<br />", request.env['SCRIPT_NAME'] || '') res = res + "<br />" end # stack res = res + "<b>Stack Trace</b><br />" res = res + (ex.backtrace || []).join("<br/>") return res end def self.get_hostname require 'socket' unless defined?(Socket) Socket.gethostname rescue 'UNKNOWN' end def self.language_version_string "#{RUBY_VERSION rescue '?.?.?'} p#{RUBY_PATCHLEVEL rescue '???'} #{RUBY_RELEASE_DATE rescue '????-??-??'} #{RUBY_PLATFORM rescue '????'}" end def self.get_username ENV['LOGNAME'] || ENV['USER'] || ENV['USERNAME'] || ENV['APACHE_RUN_USER'] || 'UNKNOWN' end end end
davideweaver/lrails
lib/loggr-rb/exceptiondata.rb
Ruby
mit
1,820
#!/usr/bin/env python # -*- coding: utf-8 -*- patterns = [r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$']*10 strings = ["/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470409.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470408_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470407_alt01.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470406_1.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/346880405.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470404_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470403.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg"]*10 def matches_pattern(str, patterns): for pattern in patterns: if pattern.match(str): return pattern.match(str), pattern return False def regex_matcherator(strings,patterns): import re compiled_patterns = list(map(re.compile, patterns)) for s in strings: if matches_pattern(s, compiled_patterns): print matches_pattern(s, compiled_patterns)[1].pattern print '--'.join(s.split('/')[-2:]) print matches_pattern(s, compiled_patterns)[0].groups() print '\n' r = regex_matcherator(strings,patterns) #print r.next()
relic7/prodimages
python/regex_matcherator_naturectr.py
Python
mit
1,999
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Installer; use Composer\Installer\InstallationManager; use Composer\Installer\NoopInstaller; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\DependencyResolver\Operation\UpdateOperation; use Composer\DependencyResolver\Operation\UninstallOperation; use Composer\Test\TestCase; class InstallationManagerTest extends TestCase { /** * @var \Composer\Repository\InstalledRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ protected $repository; /** * @var \Composer\Util\Loop&\PHPUnit\Framework\MockObject\MockObject */ protected $loop; /** * @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject */ protected $io; public function setUp() { $this->loop = $this->getMockBuilder('Composer\Util\Loop')->disableOriginalConstructor()->getMock(); $this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock(); $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); } public function testAddGetInstaller() { $installer = $this->createInstallerMock(); $installer ->expects($this->exactly(2)) ->method('supports') ->will($this->returnCallback(function ($arg) { return $arg === 'vendor'; })); $manager = new InstallationManager($this->loop, $this->io); $manager->addInstaller($installer); $this->assertSame($installer, $manager->getInstaller('vendor')); $this->setExpectedException('InvalidArgumentException'); $manager->getInstaller('unregistered'); } public function testAddRemoveInstaller() { $installer = $this->createInstallerMock(); $installer ->expects($this->exactly(2)) ->method('supports') ->will($this->returnCallback(function ($arg) { return $arg === 'vendor'; })); $installer2 = $this->createInstallerMock(); $installer2 ->expects($this->exactly(1)) ->method('supports') ->will($this->returnCallback(function ($arg) { return $arg === 'vendor'; })); $manager = new InstallationManager($this->loop, $this->io); $manager->addInstaller($installer); $this->assertSame($installer, $manager->getInstaller('vendor')); $manager->addInstaller($installer2); $this->assertSame($installer2, $manager->getInstaller('vendor')); $manager->removeInstaller($installer2); $this->assertSame($installer, $manager->getInstaller('vendor')); } public function testExecute() { $manager = $this->getMockBuilder('Composer\Installer\InstallationManager') ->setConstructorArgs(array($this->loop, $this->io)) ->setMethods(array('install', 'update', 'uninstall')) ->getMock(); $installOperation = new InstallOperation($package = $this->createPackageMock()); $removeOperation = new UninstallOperation($package); $updateOperation = new UpdateOperation( $package, $package ); $package->expects($this->any()) ->method('getType') ->will($this->returnValue('library')); $manager ->expects($this->once()) ->method('install') ->with($this->repository, $installOperation); $manager ->expects($this->once()) ->method('uninstall') ->with($this->repository, $removeOperation); $manager ->expects($this->once()) ->method('update') ->with($this->repository, $updateOperation); $manager->addInstaller(new NoopInstaller()); $manager->execute($this->repository, array($installOperation, $removeOperation, $updateOperation)); } public function testInstall() { $installer = $this->createInstallerMock(); $manager = new InstallationManager($this->loop, $this->io); $manager->addInstaller($installer); $package = $this->createPackageMock(); $operation = new InstallOperation($package); $package ->expects($this->once()) ->method('getType') ->will($this->returnValue('library')); $installer ->expects($this->once()) ->method('supports') ->with('library') ->will($this->returnValue(true)); $installer ->expects($this->once()) ->method('install') ->with($this->repository, $package); $manager->install($this->repository, $operation); } public function testUpdateWithEqualTypes() { $installer = $this->createInstallerMock(); $manager = new InstallationManager($this->loop, $this->io); $manager->addInstaller($installer); $initial = $this->createPackageMock(); $target = $this->createPackageMock(); $operation = new UpdateOperation($initial, $target); $initial ->expects($this->once()) ->method('getType') ->will($this->returnValue('library')); $target ->expects($this->once()) ->method('getType') ->will($this->returnValue('library')); $installer ->expects($this->once()) ->method('supports') ->with('library') ->will($this->returnValue(true)); $installer ->expects($this->once()) ->method('update') ->with($this->repository, $initial, $target); $manager->update($this->repository, $operation); } public function testUpdateWithNotEqualTypes() { $libInstaller = $this->createInstallerMock(); $bundleInstaller = $this->createInstallerMock(); $manager = new InstallationManager($this->loop, $this->io); $manager->addInstaller($libInstaller); $manager->addInstaller($bundleInstaller); $initial = $this->createPackageMock(); $initial ->expects($this->once()) ->method('getType') ->will($this->returnValue('library')); $target = $this->createPackageMock(); $target ->expects($this->once()) ->method('getType') ->will($this->returnValue('bundles')); $bundleInstaller ->expects($this->exactly(2)) ->method('supports') ->will($this->returnCallback(function ($arg) { return $arg === 'bundles'; })); $libInstaller ->expects($this->once()) ->method('supports') ->with('library') ->will($this->returnValue(true)); $libInstaller ->expects($this->once()) ->method('uninstall') ->with($this->repository, $initial); $bundleInstaller ->expects($this->once()) ->method('install') ->with($this->repository, $target); $operation = new UpdateOperation($initial, $target); $manager->update($this->repository, $operation); } public function testUninstall() { $installer = $this->createInstallerMock(); $manager = new InstallationManager($this->loop, $this->io); $manager->addInstaller($installer); $package = $this->createPackageMock(); $operation = new UninstallOperation($package); $package ->expects($this->once()) ->method('getType') ->will($this->returnValue('library')); $installer ->expects($this->once()) ->method('uninstall') ->with($this->repository, $package); $installer ->expects($this->once()) ->method('supports') ->with('library') ->will($this->returnValue(true)); $manager->uninstall($this->repository, $operation); } public function testInstallBinary() { $installer = $this->getMockBuilder('Composer\Installer\LibraryInstaller') ->disableOriginalConstructor() ->getMock(); $manager = new InstallationManager($this->loop, $this->io); $manager->addInstaller($installer); $package = $this->createPackageMock(); $package ->expects($this->once()) ->method('getType') ->will($this->returnValue('library')); $installer ->expects($this->once()) ->method('supports') ->with('library') ->will($this->returnValue(true)); $installer ->expects($this->once()) ->method('ensureBinariesPresence') ->with($package); $manager->ensureBinariesPresence($package); } /** * @return \Composer\Installer\InstallerInterface&\PHPUnit\Framework\MockObject\MockObject */ private function createInstallerMock() { return $this->getMockBuilder('Composer\Installer\InstallerInterface') ->getMock(); } /** * @return \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject */ private function createPackageMock() { $mock = $this->getMockBuilder('Composer\Package\PackageInterface') ->getMock(); return $mock; } }
nicolas-grekas/composer
tests/Composer/Test/Installer/InstallationManagerTest.php
PHP
mit
9,814
package May2021Leetcode; import java.util.HashMap; public class _0621TaskScheduler2 { // https://leetcode.com/discuss/interview-question/432086/Facebook-or-Phone-Screen-or-Task-Scheduler/394783 public static void main(String[] args) { System.out.println(leastInterval(new int[] { 1, 1, 2, 1 }, 2)); } public static int leastInterval(int[] tasks, int n) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int count = 0; for (int i = 0; i < tasks.length; i++) { if (!map.containsKey(tasks[i])) { map.put(tasks[i], count); count++; } else { count = Math.max(count, map.get(tasks[i]) + n + 1); map.put(tasks[i], count); count++; } } return count; } }
darshanhs90/Java-InterviewPrep
src/May2021Leetcode/_0621TaskScheduler2.java
Java
mit
711
import { RECEIVE_ALL_JOBS, RECEIVE_JOB, REQUEST_ALL_JOBS, REQUEST_JOB, RECEIVE_FILTERED_JOBS, REQUEST_FILTERED_JOBS, CREATE_JOBS, PAGINATE_JOBS, UPDATE_JOB, DELETE_JOB } from './constants' const initialState = { fetchingSelected: false, selected: null, fetchingAll: false, all: null, filteredJobs: null, filtered: false, filter: null, // we persist user's search parameters between navigations to/from home and job detail pages offset: 0, pageNum: 1 } const jobsReducer = (state = initialState, action) => { switch (action.type) { case REQUEST_ALL_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: true, all: null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } case RECEIVE_ALL_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: false, all: action.jobs, filteredJobs: null, filtered: false, filter: null, offset: 0, pageNum: 1 } case REQUEST_FILTERED_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: true, all: state.all ? [...state.all] : null, filteredJobs: null, filtered: state.filteredJobs !== null, filter: action.filter, offset: 0, pageNum: 1 } case RECEIVE_FILTERED_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: action.jobs, filtered: true, filter: {...state.filter}, offset: 0, pageNum: 1 } case PAGINATE_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: state.filteredJobs !== null, filter: state.filter ? {...state.filter} : null, offset: action.offset, pageNum: action.pageNum } case REQUEST_JOB: return { fetchingSelected: true, selected: null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: state.filteredJobs !== null, filter: state.filter ? {...state.filter} : null, offset: state.offset, pageNum: state.pageNum } case RECEIVE_JOB: return { fetchingSelected: false, selected: action.job, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: state.filteredJobs !== null, filter: state.filter ? {...state.filter} : null, offset: state.offset, pageNum: state.pageNum } case CREATE_JOBS: return { fetchingSelected: false, selected: state.selected ? {...state.selected} : null, fetchingAll: true, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } case UPDATE_JOB: return { fetchingSelected: true, selected: state.selected ? {...state.selected} : null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } case DELETE_JOB: return { fetchingSelected: true, selected: state.selected ? {...state.selected} : null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } default: return state } } export default jobsReducer
jackson-/colorforcode
src/reducers/jobsReducer.js
JavaScript
mit
3,987
module.exports = { createUser: require('./create-user') };
larsbs/graysql
examples/simple/schema/types/user/mutations/index.js
JavaScript
mit
61
"""Extension to execute code outside the Python shell window. This adds the following commands: - Check module does a full syntax check of the current module. It also runs the tabnanny to catch any inconsistent tabs. - Run module executes the module's code in the __main__ namespace. The window must have been saved previously. The module is added to sys.modules, and is also added to the __main__ namespace. XXX GvR Redesign this interface (yet again) as follows: - Present a dialog box for ``Run Module'' - Allow specify command line arguments in the dialog box """ import os import re import string import tabnanny import tokenize import tkMessageBox from idlelib import PyShell from idlelib.configHandler import idleConf IDENTCHARS = string.ascii_letters + string.digits + "_" indent_message = """Error: Inconsistent indentation detected! 1) Your indentation is outright incorrect (easy to fix), OR 2) Your indentation mixes tabs and spaces. To fix case 2, change all tabs to spaces by using Edit->Select All followed \ by Format->Untabify Region and specify the number of columns used by each tab. """ class ScriptBinding: menudefs = [ ('run', [None, ('Check Module', '<<check-module>>'), ('Run Module', '<<run-module>>'), ]), ] def __init__(self, editwin): self.editwin = editwin # Provide instance variables referenced by Debugger # XXX This should be done differently self.flist = self.editwin.flist self.root = self.editwin.root def check_module_event(self, event): filename = self.getfilename() if not filename: return 'break' if not self.checksyntax(filename): return 'break' if not self.tabnanny(filename): return 'break' def tabnanny(self, filename): f = open(filename, 'r') try: tabnanny.process_tokens(tokenize.generate_tokens(f.readline)) except tokenize.TokenError, msg: msgtxt, (lineno, start) = msg self.editwin.gotoline(lineno) self.errorbox("Tabnanny Tokenizing Error", "Token Error: %s" % msgtxt) return False except tabnanny.NannyNag, nag: # The error messages from tabnanny are too confusing... self.editwin.gotoline(nag.get_lineno()) self.errorbox("Tab/space error", indent_message) return False return True def checksyntax(self, filename): self.shell = shell = self.flist.open_shell() saved_stream = shell.get_warning_stream() shell.set_warning_stream(shell.stderr) f = open(filename, 'r') source = f.read() f.close() if '\r' in source: source = re.sub(r"\r\n", "\n", source) source = re.sub(r"\r", "\n", source) if source and source[-1] != '\n': source = source + '\n' text = self.editwin.text text.tag_remove("ERROR", "1.0", "end") try: try: # If successful, return the compiled code return compile(source, filename, "exec") except (SyntaxError, OverflowError), err: try: msg, (errorfilename, lineno, offset, line) = err if not errorfilename: err.args = msg, (filename, lineno, offset, line) err.filename = filename self.colorize_syntax_error(msg, lineno, offset) except: msg = "*** " + str(err) self.errorbox("Syntax error", "There's an error in your program:\n" + msg) return False finally: shell.set_warning_stream(saved_stream) def colorize_syntax_error(self, msg, lineno, offset): text = self.editwin.text pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1) text.tag_add("ERROR", pos) char = text.get(pos) if char and char in IDENTCHARS: text.tag_add("ERROR", pos + " wordstart", pos) if '\n' == text.get(pos): # error at line end text.mark_set("insert", pos) else: text.mark_set("insert", pos + "+1c") text.see(pos) def run_module_event(self, event): """Run the module after setting up the environment. First check the syntax. If OK, make sure the shell is active and then transfer the arguments, set the run environment's working directory to the directory of the module being executed and also add that directory to its sys.path if not already included. """ filename = self.getfilename() if not filename: return 'break' code = self.checksyntax(filename) if not code: return 'break' if not self.tabnanny(filename): return 'break' shell = self.shell interp = shell.interp if PyShell.use_subprocess: shell.restart_shell() dirname = os.path.dirname(filename) # XXX Too often this discards arguments the user just set... interp.runcommand("""if 1: _filename = %r import sys as _sys from os.path import basename as _basename if (not _sys.argv or _basename(_sys.argv[0]) != _basename(_filename)): _sys.argv = [_filename] import os as _os _os.chdir(%r) del _filename, _sys, _basename, _os \n""" % (filename, dirname)) interp.prepend_syspath(filename) # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still # go to __stderr__. With subprocess, they go to the shell. # Need to change streams in PyShell.ModifiedInterpreter. interp.runcode(code) return 'break' def getfilename(self): """Get source filename. If not saved, offer to save (or create) file The debugger requires a source file. Make sure there is one, and that the current version of the source buffer has been saved. If the user declines to save or cancels the Save As dialog, return None. If the user has configured IDLE for Autosave, the file will be silently saved if it already exists and is dirty. """ filename = self.editwin.io.filename if not self.editwin.get_saved(): autosave = idleConf.GetOption('main', 'General', 'autosave', type='bool') if autosave and filename: self.editwin.io.save(None) else: reply = self.ask_save_dialog() self.editwin.text.focus_set() if reply == "ok": self.editwin.io.save(None) filename = self.editwin.io.filename else: filename = None return filename def ask_save_dialog(self): msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?" mb = tkMessageBox.Message(title="Save Before Run or Check", message=msg, icon=tkMessageBox.QUESTION, type=tkMessageBox.OKCANCEL, default=tkMessageBox.OK, master=self.editwin.text) return mb.show() def errorbox(self, title, message): # XXX This should really be a function of EditorWindow... tkMessageBox.showerror(title, message, master=self.editwin.text) self.editwin.text.focus_set()
babyliynfg/cross
tools/project-creator/Python2.6.6/Lib/idlelib/ScriptBinding.py
Python
mit
7,992
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace PinnacleWrapper.Enums { [JsonConverter(typeof(StringEnumConverter))] public enum BetType { Spread, MoneyLine, TotalPoints, TeamTotalPoints } }
bbenetskyy/ArDependency
UniversalSolution/pinnaclewrapper/Enums/BetType.cs
C#
mit
262
/* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.tree.traverse.tasks; import org.encog.ml.tree.TreeNode; import org.encog.ml.tree.traverse.DepthFirstTraversal; import org.encog.ml.tree.traverse.TreeTraversalTask; public class TaskGetNodeIndex implements TreeTraversalTask { private int nodeCount; private int targetIndex; private TreeNode result; public TaskGetNodeIndex(int theIndex) { this.targetIndex = theIndex; this.nodeCount = 0; } @Override public boolean task(TreeNode node) { if (this.nodeCount >= targetIndex) { if (result == null) { result = node; } return false; } this.nodeCount++; return true; } public TreeNode getResult() { return result; } public static TreeNode process(int index, TreeNode node) { TaskGetNodeIndex task = new TaskGetNodeIndex(index); DepthFirstTraversal trav = new DepthFirstTraversal(); trav.traverse(node, task); return task.getResult(); } }
ladygagapowerbot/bachelor-thesis-implementation
lib/Encog/src/main/java/org/encog/ml/tree/traverse/tasks/TaskGetNodeIndex.java
Java
mit
1,915
import { t } from 'app/i18next-t'; import { DimCrafted } from 'app/inventory/item-types'; import { percent } from 'app/shell/filters'; import React from 'react'; /** * A progress bar that shows weapon crafting info like the game does. */ export function WeaponCraftedInfo({ craftInfo, className, }: { craftInfo: DimCrafted; className: string; }) { const pct = percent(craftInfo.progress || 0); const progressBarStyle = { width: pct, }; return ( <div className={className}> <div className="objective-progress"> <div className="objective-progress-bar" style={progressBarStyle} /> <div className="objective-description"> {t('MovePopup.WeaponLevel', { level: craftInfo.level })} </div> <div className="objective-text">{pct}</div> </div> </div> ); }
DestinyItemManager/DIM
src/app/dim-ui/WeaponCraftedInfo.tsx
TypeScript
mit
833
/* global logger, processWebhookMessage */ import moment from 'moment'; RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler { constructor() { this.vm = Npm.require('vm'); this.successResults = [200, 201, 202]; this.compiledScripts = {}; this.triggers = {}; RocketChat.models.Integrations.find({type: 'webhook-outgoing'}).observe({ added: (record) => { this.addIntegration(record); }, changed: (record) => { this.removeIntegration(record); this.addIntegration(record); }, removed: (record) => { this.removeIntegration(record); } }); } addIntegration(record) { logger.outgoing.debug(`Adding the integration ${ record.name } of the event ${ record.event }!`); let channels; if (record.event && !RocketChat.integrations.outgoingEvents[record.event].use.channel) { logger.outgoing.debug('The integration doesnt rely on channels.'); //We don't use any channels, so it's special ;) channels = ['__any']; } else if (_.isEmpty(record.channel)) { logger.outgoing.debug('The integration had an empty channel property, so it is going on all the public channels.'); channels = ['all_public_channels']; } else { logger.outgoing.debug('The integration is going on these channels:', record.channel); channels = [].concat(record.channel); } for (const channel of channels) { if (!this.triggers[channel]) { this.triggers[channel] = {}; } this.triggers[channel][record._id] = record; } } removeIntegration(record) { for (const trigger of Object.values(this.triggers)) { delete trigger[record._id]; } } isTriggerEnabled(trigger) { for (const trig of Object.values(this.triggers)) { if (trig[trigger._id]) { return trig[trigger._id].enabled; } } return false; } updateHistory({ historyId, step, integration, event, data, triggerWord, ranPrepareScript, prepareSentMessage, processSentMessage, resultMessage, finished, url, httpCallData, httpError, httpResult, error, errorStack }) { const history = { type: 'outgoing-webhook', step }; // Usually is only added on initial insert if (integration) { history.integration = integration; } // Usually is only added on initial insert if (event) { history.event = event; } if (data) { history.data = data; if (data.user) { history.data.user = _.omit(data.user, ['meta', '$loki', 'services']); } if (data.room) { history.data.room = _.omit(data.room, ['meta', '$loki', 'usernames']); history.data.room.usernames = ['this_will_be_filled_in_with_usernames_when_replayed']; } } if (triggerWord) { history.triggerWord = triggerWord; } if (typeof ranPrepareScript !== 'undefined') { history.ranPrepareScript = ranPrepareScript; } if (prepareSentMessage) { history.prepareSentMessage = prepareSentMessage; } if (processSentMessage) { history.processSentMessage = processSentMessage; } if (resultMessage) { history.resultMessage = resultMessage; } if (typeof finished !== 'undefined') { history.finished = finished; } if (url) { history.url = url; } if (typeof httpCallData !== 'undefined') { history.httpCallData = httpCallData; } if (httpError) { history.httpError = httpError; } if (typeof httpResult !== 'undefined') { history.httpResult = httpResult; } if (typeof error !== 'undefined') { history.error = error; } if (typeof errorStack !== 'undefined') { history.errorStack = errorStack; } if (historyId) { RocketChat.models.IntegrationHistory.update({ _id: historyId }, { $set: history }); return historyId; } else { history._createdAt = new Date(); return RocketChat.models.IntegrationHistory.insert(Object.assign({ _id: Random.id() }, history)); } } //Trigger is the trigger, nameOrId is a string which is used to try and find a room, room is a room, message is a message, and data contains "user_name" if trigger.impersonateUser is truthful. sendMessage({ trigger, nameOrId = '', room, message, data }) { let user; //Try to find the user who we are impersonating if (trigger.impersonateUser) { user = RocketChat.models.Users.findOneByUsername(data.user_name); } //If they don't exist (aka the trigger didn't contain a user) then we set the user based upon the //configured username for the integration since this is required at all times. if (!user) { user = RocketChat.models.Users.findOneByUsername(trigger.username); } let tmpRoom; if (nameOrId || trigger.targetRoom) { tmpRoom = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: nameOrId || trigger.targetRoom, errorOnEmpty: false }) || room; } else { tmpRoom = room; } //If no room could be found, we won't be sending any messages but we'll warn in the logs if (!tmpRoom) { logger.outgoing.warn(`The Integration "${ trigger.name }" doesn't have a room configured nor did it provide a room to send the message to.`); return; } logger.outgoing.debug(`Found a room for ${ trigger.name } which is: ${ tmpRoom.name } with a type of ${ tmpRoom.t }`); message.bot = { i: trigger._id }; const defaultValues = { alias: trigger.alias, avatar: trigger.avatar, emoji: trigger.emoji }; if (tmpRoom.t === 'd') { message.channel = `@${ tmpRoom._id }`; } else { message.channel = `#${ tmpRoom._id }`; } message = processWebhookMessage(message, user, defaultValues); return message; } buildSandbox(store = {}) { const sandbox = { _, s, console, moment, Store: { set: (key, val) => store[key] = val, get: (key) => store[key] }, HTTP: (method, url, options) => { try { return { result: HTTP.call(method, url, options) }; } catch (error) { return { error }; } } }; Object.keys(RocketChat.models).filter(k => !k.startsWith('_')).forEach(k => { sandbox[k] = RocketChat.models[k]; }); return { store, sandbox }; } getIntegrationScript(integration) { const compiledScript = this.compiledScripts[integration._id]; if (compiledScript && +compiledScript._updatedAt === +integration._updatedAt) { return compiledScript.script; } const script = integration.scriptCompiled; const { store, sandbox } = this.buildSandbox(); let vmScript; try { logger.outgoing.info('Will evaluate script of Trigger', integration.name); logger.outgoing.debug(script); vmScript = this.vm.createScript(script, 'script.js'); vmScript.runInNewContext(sandbox); if (sandbox.Script) { this.compiledScripts[integration._id] = { script: new sandbox.Script(), store, _updatedAt: integration._updatedAt }; return this.compiledScripts[integration._id].script; } } catch (e) { logger.outgoing.error(`Error evaluating Script in Trigger ${ integration.name }:`); logger.outgoing.error(script.replace(/^/gm, ' ')); logger.outgoing.error('Stack Trace:'); logger.outgoing.error(e.stack.replace(/^/gm, ' ')); throw new Meteor.Error('error-evaluating-script'); } if (!sandbox.Script) { logger.outgoing.error(`Class "Script" not in Trigger ${ integration.name }:`); throw new Meteor.Error('class-script-not-found'); } } hasScriptAndMethod(integration, method) { if (integration.scriptEnabled !== true || !integration.scriptCompiled || integration.scriptCompiled.trim() === '') { return false; } let script; try { script = this.getIntegrationScript(integration); } catch (e) { return false; } return typeof script[method] !== 'undefined'; } executeScript(integration, method, params, historyId) { let script; try { script = this.getIntegrationScript(integration); } catch (e) { this.updateHistory({ historyId, step: 'execute-script-getting-script', error: true, errorStack: e }); return; } if (!script[method]) { logger.outgoing.error(`Method "${ method }" no found in the Integration "${ integration.name }"`); this.updateHistory({ historyId, step: `execute-script-no-method-${ method }` }); return; } try { const { sandbox } = this.buildSandbox(this.compiledScripts[integration._id].store); sandbox.script = script; sandbox.method = method; sandbox.params = params; this.updateHistory({ historyId, step: `execute-script-before-running-${ method }` }); const result = this.vm.runInNewContext('script[method](params)', sandbox, { timeout: 3000 }); logger.outgoing.debug(`Script method "${ method }" result of the Integration "${ integration.name }" is:`); logger.outgoing.debug(result); return result; } catch (e) { this.updateHistory({ historyId, step: `execute-script-error-running-${ method }`, error: true, errorStack: e.stack.replace(/^/gm, ' ') }); logger.outgoing.error(`Error running Script in the Integration ${ integration.name }:`); logger.outgoing.debug(integration.scriptCompiled.replace(/^/gm, ' ')); // Only output the compiled script if debugging is enabled, so the logs don't get spammed. logger.outgoing.error('Stack:'); logger.outgoing.error(e.stack.replace(/^/gm, ' ')); return; } } eventNameArgumentsToObject() { const argObject = { event: arguments[0] }; switch (argObject.event) { case 'sendMessage': if (arguments.length >= 3) { argObject.message = arguments[1]; argObject.room = arguments[2]; } break; case 'fileUploaded': if (arguments.length >= 2) { const arghhh = arguments[1]; argObject.user = arghhh.user; argObject.room = arghhh.room; argObject.message = arghhh.message; } break; case 'roomArchived': if (arguments.length >= 3) { argObject.room = arguments[1]; argObject.user = arguments[2]; } break; case 'roomCreated': if (arguments.length >= 3) { argObject.owner = arguments[1]; argObject.room = arguments[2]; } break; case 'roomJoined': case 'roomLeft': if (arguments.length >= 3) { argObject.user = arguments[1]; argObject.room = arguments[2]; } break; case 'userCreated': if (arguments.length >= 2) { argObject.user = arguments[1]; } break; default: logger.outgoing.warn(`An Unhandled Trigger Event was called: ${ argObject.event }`); argObject.event = undefined; break; } logger.outgoing.debug(`Got the event arguments for the event: ${ argObject.event }`, argObject); return argObject; } mapEventArgsToData(data, { event, message, room, owner, user }) { switch (event) { case 'sendMessage': data.channel_id = room._id; data.channel_name = room.name; data.message_id = message._id; data.timestamp = message.ts; data.user_id = message.u._id; data.user_name = message.u.username; data.text = message.msg; if (message.alias) { data.alias = message.alias; } if (message.bot) { data.bot = message.bot; } break; case 'fileUploaded': data.channel_id = room._id; data.channel_name = room.name; data.message_id = message._id; data.timestamp = message.ts; data.user_id = message.u._id; data.user_name = message.u.username; data.text = message.msg; data.user = user; data.room = room; data.message = message; if (message.alias) { data.alias = message.alias; } if (message.bot) { data.bot = message.bot; } break; case 'roomCreated': data.channel_id = room._id; data.channel_name = room.name; data.timestamp = room.ts; data.user_id = owner._id; data.user_name = owner.username; data.owner = owner; data.room = room; break; case 'roomArchived': case 'roomJoined': case 'roomLeft': data.timestamp = new Date(); data.channel_id = room._id; data.channel_name = room.name; data.user_id = user._id; data.user_name = user.username; data.user = user; data.room = room; if (user.type === 'bot') { data.bot = true; } break; case 'userCreated': data.timestamp = user.createdAt; data.user_id = user._id; data.user_name = user.username; data.user = user; if (user.type === 'bot') { data.bot = true; } break; default: break; } } executeTriggers() { logger.outgoing.debug('Execute Trigger:', arguments[0]); const argObject = this.eventNameArgumentsToObject(...arguments); const { event, message, room } = argObject; //Each type of event should have an event and a room attached, otherwise we //wouldn't know how to handle the trigger nor would we have anywhere to send the //result of the integration if (!event) { return; } const triggersToExecute = []; logger.outgoing.debug('Starting search for triggers for the room:', room ? room._id : '__any'); if (room) { switch (room.t) { case 'd': const id = room._id.replace(message.u._id, ''); const username = _.without(room.usernames, message.u.username)[0]; if (this.triggers[`@${ id }`]) { for (const trigger of Object.values(this.triggers[`@${ id }`])) { triggersToExecute.push(trigger); } } if (this.triggers.all_direct_messages) { for (const trigger of Object.values(this.triggers.all_direct_messages)) { triggersToExecute.push(trigger); } } if (id !== username && this.triggers[`@${ username }`]) { for (const trigger of Object.values(this.triggers[`@${ username }`])) { triggersToExecute.push(trigger); } } break; case 'c': if (this.triggers.all_public_channels) { for (const trigger of Object.values(this.triggers.all_public_channels)) { triggersToExecute.push(trigger); } } if (this.triggers[`#${ room._id }`]) { for (const trigger of Object.values(this.triggers[`#${ room._id }`])) { triggersToExecute.push(trigger); } } if (room._id !== room.name && this.triggers[`#${ room.name }`]) { for (const trigger of Object.values(this.triggers[`#${ room.name }`])) { triggersToExecute.push(trigger); } } break; default: if (this.triggers.all_private_groups) { for (const trigger of Object.values(this.triggers.all_private_groups)) { triggersToExecute.push(trigger); } } if (this.triggers[`#${ room._id }`]) { for (const trigger of Object.values(this.triggers[`#${ room._id }`])) { triggersToExecute.push(trigger); } } if (room._id !== room.name && this.triggers[`#${ room.name }`]) { for (const trigger of Object.values(this.triggers[`#${ room.name }`])) { triggersToExecute.push(trigger); } } break; } } if (this.triggers.__any) { //For outgoing integration which don't rely on rooms. for (const trigger of Object.values(this.triggers.__any)) { triggersToExecute.push(trigger); } } logger.outgoing.debug(`Found ${ triggersToExecute.length } to iterate over and see if the match the event.`); for (const triggerToExecute of triggersToExecute) { logger.outgoing.debug(`Is "${ triggerToExecute.name }" enabled, ${ triggerToExecute.enabled }, and what is the event? ${ triggerToExecute.event }`); if (triggerToExecute.enabled === true && triggerToExecute.event === event) { this.executeTrigger(triggerToExecute, argObject); } } } executeTrigger(trigger, argObject) { for (const url of trigger.urls) { this.executeTriggerUrl(url, trigger, argObject, 0); } } executeTriggerUrl(url, trigger, { event, message, room, owner, user }, theHistoryId, tries = 0) { if (!this.isTriggerEnabled(trigger)) { logger.outgoing.warn(`The trigger "${ trigger.name }" is no longer enabled, stopping execution of it at try: ${ tries }`); return; } logger.outgoing.debug(`Starting to execute trigger: ${ trigger.name } (${ trigger._id })`); let word; //Not all triggers/events support triggerWords if (RocketChat.integrations.outgoingEvents[event].use.triggerWords) { if (trigger.triggerWords && trigger.triggerWords.length > 0) { for (const triggerWord of trigger.triggerWords) { if (!trigger.triggerWordAnywhere && message.msg.indexOf(triggerWord) === 0) { word = triggerWord; break; } else if (trigger.triggerWordAnywhere && message.msg.includes(triggerWord)) { word = triggerWord; break; } } // Stop if there are triggerWords but none match if (!word) { logger.outgoing.debug(`The trigger word which "${ trigger.name }" was expecting could not be found, not executing.`); return; } } } const historyId = this.updateHistory({ step: 'start-execute-trigger-url', integration: trigger, event }); const data = { token: trigger.token, bot: false }; if (word) { data.trigger_word = word; } this.mapEventArgsToData(data, { trigger, event, message, room, owner, user }); this.updateHistory({ historyId, step: 'mapped-args-to-data', data, triggerWord: word }); logger.outgoing.info(`Will be executing the Integration "${ trigger.name }" to the url: ${ url }`); logger.outgoing.debug(data); let opts = { params: {}, method: 'POST', url, data, auth: undefined, npmRequestOptions: { rejectUnauthorized: !RocketChat.settings.get('Allow_Invalid_SelfSigned_Certs'), strictSSL: !RocketChat.settings.get('Allow_Invalid_SelfSigned_Certs') }, headers: { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36' } }; if (this.hasScriptAndMethod(trigger, 'prepare_outgoing_request')) { opts = this.executeScript(trigger, 'prepare_outgoing_request', { request: opts }, historyId); } this.updateHistory({ historyId, step: 'after-maybe-ran-prepare', ranPrepareScript: true }); if (!opts) { this.updateHistory({ historyId, step: 'after-prepare-no-opts', finished: true }); return; } if (opts.message) { const prepareMessage = this.sendMessage({ trigger, room, message: opts.message, data }); this.updateHistory({ historyId, step: 'after-prepare-send-message', prepareSentMessage: prepareMessage }); } if (!opts.url || !opts.method) { this.updateHistory({ historyId, step: 'after-prepare-no-url_or_method', finished: true }); return; } this.updateHistory({ historyId, step: 'pre-http-call', url: opts.url, httpCallData: opts.data }); HTTP.call(opts.method, opts.url, opts, (error, result) => { if (!result) { logger.outgoing.warn(`Result for the Integration ${ trigger.name } to ${ url } is empty`); } else { logger.outgoing.info(`Status code for the Integration ${ trigger.name } to ${ url } is ${ result.statusCode }`); } this.updateHistory({ historyId, step: 'after-http-call', httpError: error, httpResult: result }); if (this.hasScriptAndMethod(trigger, 'process_outgoing_response')) { const sandbox = { request: opts, response: { error, status_code: result ? result.statusCode : undefined, //These values will be undefined to close issues #4175, #5762, and #5896 content: result ? result.data : undefined, content_raw: result ? result.content : undefined, headers: result ? result.headers : {} } }; const scriptResult = this.executeScript(trigger, 'process_outgoing_response', sandbox, historyId); if (scriptResult && scriptResult.content) { const resultMessage = this.sendMessage({ trigger, room, message: scriptResult.content, data }); this.updateHistory({ historyId, step: 'after-process-send-message', processSentMessage: resultMessage, finished: true }); return; } if (scriptResult === false) { this.updateHistory({ historyId, step: 'after-process-false-result', finished: true }); return; } } // if the result contained nothing or wasn't a successful statusCode if (!result || !this.successResults.includes(result.statusCode)) { if (error) { logger.outgoing.error(`Error for the Integration "${ trigger.name }" to ${ url } is:`); logger.outgoing.error(error); } if (result) { logger.outgoing.error(`Error for the Integration "${ trigger.name }" to ${ url } is:`); logger.outgoing.error(result); if (result.statusCode === 410) { this.updateHistory({ historyId, step: 'after-process-http-status-410', error: true }); logger.outgoing.error(`Disabling the Integration "${ trigger.name }" because the status code was 401 (Gone).`); RocketChat.models.Integrations.update({ _id: trigger._id }, { $set: { enabled: false }}); return; } if (result.statusCode === 500) { this.updateHistory({ historyId, step: 'after-process-http-status-500', error: true }); logger.outgoing.error(`Error "500" for the Integration "${ trigger.name }" to ${ url }.`); logger.outgoing.error(result.content); return; } } if (trigger.retryFailedCalls) { if (tries < trigger.retryCount && trigger.retryDelay) { this.updateHistory({ historyId, error: true, step: `going-to-retry-${ tries + 1 }` }); let waitTime; switch (trigger.retryDelay) { case 'powers-of-ten': // Try again in 0.1s, 1s, 10s, 1m40s, 16m40s, 2h46m40s, 27h46m40s, etc waitTime = Math.pow(10, tries + 2); break; case 'powers-of-two': // 2 seconds, 4 seconds, 8 seconds waitTime = Math.pow(2, tries + 1) * 1000; break; case 'increments-of-two': // 2 second, 4 seconds, 6 seconds, etc waitTime = (tries + 1) * 2 * 1000; break; default: const er = new Error('The integration\'s retryDelay setting is invalid.'); this.updateHistory({ historyId, step: 'failed-and-retry-delay-is-invalid', error: true, errorStack: er.stack }); return; } logger.outgoing.info(`Trying the Integration ${ trigger.name } to ${ url } again in ${ waitTime } milliseconds.`); Meteor.setTimeout(() => { this.executeTriggerUrl(url, trigger, { event, message, room, owner, user }, historyId, tries + 1); }, waitTime); } else { this.updateHistory({ historyId, step: 'too-many-retries', error: true }); } } else { this.updateHistory({ historyId, step: 'failed-and-not-configured-to-retry', error: true }); } return; } //process outgoing webhook response as a new message if (result && this.successResults.includes(result.statusCode)) { if (result && result.data && (result.data.text || result.data.attachments)) { const resultMsg = this.sendMessage({ trigger, room, message: result.data, data }); this.updateHistory({ historyId, step: 'url-response-sent-message', resultMessage: resultMsg, finished: true }); } } }); } replay(integration, history) { if (!integration || integration.type !== 'webhook-outgoing') { throw new Meteor.Error('integration-type-must-be-outgoing', 'The integration type to replay must be an outgoing webhook.'); } if (!history || !history.data) { throw new Meteor.Error('history-data-must-be-defined', 'The history data must be defined to replay an integration.'); } const event = history.event; const message = RocketChat.models.Messages.findOneById(history.data.message_id); const room = RocketChat.models.Rooms.findOneById(history.data.channel_id); const user = RocketChat.models.Users.findOneById(history.data.user_id); let owner; if (history.data.owner && history.data.owner._id) { owner = RocketChat.models.Users.findOneById(history.data.owner._id); } this.executeTriggerUrl(history.url, integration, { event, message, room, owner, user }); } };
mwharrison/Rocket.Chat
packages/rocketchat-integrations/server/lib/triggerHandler.js
JavaScript
mit
23,767
'use strict'; module.exports = function (t, a) { t(document.createElement('p')); };
medikoo/site-tree
test/lib/fix-dynamic-style-sheets.js
JavaScript
mit
86
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M11 17h10v-2H11v2zm-8-5l4 4V8l-4 4zm0 9h18v-2H3v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z" /></React.Fragment> , 'FormatIndentDecreaseSharp');
Kagami/material-ui
packages/material-ui-icons/src/FormatIndentDecreaseSharp.js
JavaScript
mit
285
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http\Authenticator\Passport\Badge; use Symfony\Component\Security\Core\Exception\AuthenticationServiceException; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Http\EventListener\UserProviderListener; /** * Represents the user in the authentication process. * * It uses an identifier (e.g. email, or username) and * "user loader" to load the related User object. * * @author Wouter de Jong <wouter@wouterj.nl> */ class UserBadge implements BadgeInterface { private $userIdentifier; private $userLoader; private $user; /** * Initializes the user badge. * * You must provide a $userIdentifier. This is a unique string representing the * user for this authentication (e.g. the email if authentication is done using * email + password; or a string combining email+company if authentication is done * based on email *and* company name). This string can be used for e.g. login throttling. * * Optionally, you may pass a user loader. This callable receives the $userIdentifier * as argument and must return a UserInterface object (otherwise an AuthenticationServiceException * is thrown). If this is not set, the default user provider will be used with * $userIdentifier as username. */ public function __construct(string $userIdentifier, ?callable $userLoader = null) { $this->userIdentifier = $userIdentifier; $this->userLoader = $userLoader; } public function getUserIdentifier(): string { return $this->userIdentifier; } /** * @throws AuthenticationException when the user cannot be found */ public function getUser(): UserInterface { if (null === $this->user) { if (null === $this->userLoader) { throw new \LogicException(sprintf('No user loader is configured, did you forget to register the "%s" listener?', UserProviderListener::class)); } $this->user = ($this->userLoader)($this->userIdentifier); if (!$this->user instanceof UserInterface) { throw new AuthenticationServiceException(sprintf('The user provider must return a UserInterface object, "%s" given.', get_debug_type($this->user))); } } return $this->user; } public function getUserLoader(): ?callable { return $this->userLoader; } public function setUserLoader(callable $userLoader): void { $this->userLoader = $userLoader; } public function isResolved(): bool { return true; } }
Slamdunk/symfony
src/Symfony/Component/Security/Http/Authenticator/Passport/Badge/UserBadge.php
PHP
mit
2,898
KEY_UP = "up" KEY_DOWN = "down" KEY_RIGHT = "right" KEY_LEFT = "left" KEY_INSERT = "insert" KEY_HOME = "home" KEY_END = "end" KEY_PAGEUP = "pageup" KEY_PAGEDOWN = "pagedown" KEY_BACKSPACE = "backspace" KEY_DELETE = "delete" KEY_TAB = "tab" KEY_ENTER = "enter" KEY_PAUSE = "pause" KEY_ESCAPE = "escape" KEY_SPACE = "space" KEY_KEYPAD0 = "keypad0" KEY_KEYPAD1 = "keypad1" KEY_KEYPAD2 = "keypad2" KEY_KEYPAD3 = "keypad3" KEY_KEYPAD4 = "keypad4" KEY_KEYPAD5 = "keypad5" KEY_KEYPAD6 = "keypad6" KEY_KEYPAD7 = "keypad7" KEY_KEYPAD8 = "keypad8" KEY_KEYPAD9 = "keypad9" KEY_KEYPAD_PERIOD = "keypad_period" KEY_KEYPAD_DIVIDE = "keypad_divide" KEY_KEYPAD_MULTIPLY = "keypad_multiply" KEY_KEYPAD_MINUS = "keypad_minus" KEY_KEYPAD_PLUS = "keypad_plus" KEY_KEYPAD_ENTER = "keypad_enter" KEY_CLEAR = "clear" KEY_F1 = "f1" KEY_F2 = "f2" KEY_F3 = "f3" KEY_F4 = "f4" KEY_F5 = "f5" KEY_F6 = "f6" KEY_F7 = "f7" KEY_F8 = "f8" KEY_F9 = "f9" KEY_F10 = "f10" KEY_F11 = "f11" KEY_F12 = "f12" KEY_F13 = "f13" KEY_F14 = "f14" KEY_F15 = "f15" KEY_F16 = "f16" KEY_F17 = "f17" KEY_F18 = "f18" KEY_F19 = "f19" KEY_F20 = "f20" KEY_SYSREQ = "sysreq" KEY_BREAK = "break" KEY_CONTEXT_MENU = "context_menu" KEY_BROWSER_BACK = "browser_back" KEY_BROWSER_FORWARD = "browser_forward" KEY_BROWSER_REFRESH = "browser_refresh" KEY_BROWSER_STOP = "browser_stop" KEY_BROWSER_SEARCH = "browser_search" KEY_BROWSER_FAVORITES = "browser_favorites" KEY_BROWSER_HOME = "browser_home"
FichteFoll/CSScheme
my_sublime_lib/constants.py
Python
mit
2,230
import { Button } from './button'; export { Button }; export default null;
rs3d/fuse-box
playground/react_ssr_csr/src/client/components/button/index.js
JavaScript
mit
77
package cn.edu.gdut.zaoying.Option.series.treemap.itemStyle.emphasis; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ColorSaturationNumber { double value() default 0; }
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/series/treemap/itemStyle/emphasis/ColorSaturationNumber.java
Java
mit
368
using System; using System.ComponentModel.Composition; using System.Linq; using UniRx; using UnityEngine; namespace Inconspicuous.Framework { public class QuitApplicationCommand : ICommand<Unit> { } public class QuitApplicationCommandHandler : CommandHandler<QuitApplicationCommand, Unit> { private const string webPlayerQuitUrl = "http://www.inconspicuous.no"; public override IObservable<Unit> Handle(QuitApplicationCommand macroCommand) { if(Application.isEditor) { var editorApplicationType = AppDomain.CurrentDomain.GetAssemblies() .Select(x => x.GetType("UnityEditor.EditorApplication")) .Where(x => x != null) .FirstOrDefault(); if(editorApplicationType != null) { editorApplicationType.GetProperty("isPlaying").SetValue(null, false, null); } } else if(Application.isWebPlayer) { Application.OpenURL(webPlayerQuitUrl); } else { Application.Quit(); } return Observable.Return(Unit.Default); } } }
inconspicuous-creations/Inconspicuous.Framework
Inconspicuous.Framework/Providers/Controller/QuitApplicationCommand.cs
C#
mit
970
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var imageHeight = 0; /** * @function addFrame * @private * @since 3.0.0 */ var addFrame = function (texture, sourceIndex, name, frame) { // The frame values are the exact coordinates to cut the frame out of the atlas from var y = imageHeight - frame.y - frame.height; texture.add(name, sourceIndex, frame.x, y, frame.width, frame.height); // These are the original (non-trimmed) sprite values /* if (src.trimmed) { newFrame.setTrim( src.sourceSize.w, src.sourceSize.h, src.spriteSourceSize.x, src.spriteSourceSize.y, src.spriteSourceSize.w, src.spriteSourceSize.h ); } */ }; /** * Parses a Unity YAML File and creates Frames in the Texture. * For more details about Sprite Meta Data see https://docs.unity3d.com/ScriptReference/SpriteMetaData.html * * @function Phaser.Textures.Parsers.UnityYAML * @memberof Phaser.Textures.Parsers * @private * @since 3.0.0 * * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. * @param {integer} sourceIndex - The index of the TextureSource. * @param {object} yaml - The YAML data. * * @return {Phaser.Textures.Texture} The Texture modified by this parser. */ var UnityYAML = function (texture, sourceIndex, yaml) { // Add in a __BASE entry (for the entire atlas) var source = texture.source[sourceIndex]; texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); imageHeight = source.height; var data = yaml.split('\n'); var lineRegExp = /^[ ]*(- )*(\w+)+[: ]+(.*)/; var prevSprite = ''; var currentSprite = ''; var rect = { x: 0, y: 0, width: 0, height: 0 }; // var pivot = { x: 0, y: 0 }; // var border = { x: 0, y: 0, z: 0, w: 0 }; for (var i = 0; i < data.length; i++) { var results = data[i].match(lineRegExp); if (!results) { continue; } var isList = (results[1] === '- '); var key = results[2]; var value = results[3]; if (isList) { if (currentSprite !== prevSprite) { addFrame(texture, sourceIndex, currentSprite, rect); prevSprite = currentSprite; } rect = { x: 0, y: 0, width: 0, height: 0 }; } if (key === 'name') { // Start new list currentSprite = value; continue; } switch (key) { case 'x': case 'y': case 'width': case 'height': rect[key] = parseInt(value, 10); break; // case 'pivot': // pivot = eval('var obj = ' + value); // break; // case 'border': // border = eval('var obj = ' + value); // break; } } if (currentSprite !== prevSprite) { addFrame(texture, sourceIndex, currentSprite, rect); } return texture; }; module.exports = UnityYAML; /* Example data: TextureImporter: spritePivot: {x: .5, y: .5} spriteBorder: {x: 0, y: 0, z: 0, w: 0} spritePixelsToUnits: 100 spriteSheet: sprites: - name: asteroids_0 rect: serializedVersion: 2 x: 5 y: 328 width: 65 height: 82 alignment: 0 pivot: {x: 0, y: 0} border: {x: 0, y: 0, z: 0, w: 0} - name: asteroids_1 rect: serializedVersion: 2 x: 80 y: 322 width: 53 height: 88 alignment: 0 pivot: {x: 0, y: 0} border: {x: 0, y: 0, z: 0, w: 0} spritePackingTag: Asteroids */
mahill/phaser
src/textures/parsers/UnityYAML.js
JavaScript
mit
3,910
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v2c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-2c0-2.66-5.33-4-8-4z" /></g></React.Fragment> , 'PersonOutlineRounded');
Kagami/material-ui
packages/material-ui-icons/src/PersonOutlineRounded.js
JavaScript
mit
509
'use strict'; var element = require('../element'); module.exports = function(node) { var el = element('phpdbg'); el.innerHTML = node.nodeValue; return el; };
ralt/phpdbg-ext
src/phpdbg/commands/phpdbg.js
JavaScript
mit
172
<?php namespace Oro\Bundle\IntegrationBundle\Tests\Unit\Async; use Doctrine\DBAL\Connection; use Doctrine\ORM\Configuration; use Doctrine\ORM\EntityManagerInterface; use Oro\Bundle\EntityBundle\ORM\DoctrineHelper; use Oro\Bundle\IntegrationBundle\Async\ReversSyncIntegrationProcessor; use Oro\Bundle\IntegrationBundle\Async\Topics; use Oro\Bundle\IntegrationBundle\Entity\Channel as Integration; use Oro\Bundle\IntegrationBundle\Logger\LoggerStrategy; use Oro\Bundle\IntegrationBundle\Manager\TypesRegistry; use Oro\Bundle\IntegrationBundle\Provider\ConnectorInterface; use Oro\Bundle\IntegrationBundle\Provider\ReverseSyncProcessor; use Oro\Bundle\IntegrationBundle\Provider\TwoWaySyncConnectorInterface; use Oro\Component\MessageQueue\Client\TopicSubscriberInterface; use Oro\Component\MessageQueue\Consumption\MessageProcessorInterface; use Oro\Component\MessageQueue\Test\JobRunner; use Oro\Component\MessageQueue\Transport\Null\NullMessage; use Oro\Component\MessageQueue\Transport\Null\NullSession; use Oro\Component\MessageQueue\Util\JSON; use Oro\Component\Testing\ClassExtensionTrait; use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface; class ReversSyncIntegrationProcessorTest extends \PHPUnit_Framework_TestCase { use ClassExtensionTrait; public function testShouldImplementMessageProcessorInterface() { $this->assertClassImplements(MessageProcessorInterface::class, ReversSyncIntegrationProcessor::class); } public function testShouldImplementTopicSubscriberInterface() { $this->assertClassImplements(TopicSubscriberInterface::class, ReversSyncIntegrationProcessor::class); } public function testShouldImplementContainerAwareInterface() { $this->assertClassImplements(ContainerAwareInterface::class, ReversSyncIntegrationProcessor::class); } public function testShouldSubscribeOnReversSyncIntegrationTopic() { $this->assertEquals([Topics::REVERS_SYNC_INTEGRATION], ReversSyncIntegrationProcessor::getSubscribedTopics()); } public function testCouldBeConstructedWithExpectedArguments() { new ReversSyncIntegrationProcessor( $this->createDoctrineHelperStub(), $this->createReversSyncProcessorMock(), $this->createTypeRegistryMock(), new JobRunner(), $this->createLoggerMock() ); } public function testRejectAndLogIfMessageBodyMissIntegrationId() { $logger = $this->createLoggerMock(); $logger ->expects($this->once()) ->method('critical') ->with('Invalid message: integration_id and connector should not be empty: []') ; $processor = new ReversSyncIntegrationProcessor( $this->createDoctrineHelperStub(), $this->createReversSyncProcessorMock(), $this->createTypeRegistryMock(), new JobRunner(), $logger ); $message = new NullMessage(); $message->setBody('[]'); $status = $processor->process($message, new NullSession()); $this->assertEquals(MessageProcessorInterface::REJECT, $status); } /** * @expectedException \LogicException * @expectedExceptionMessage The malformed json given. */ public function testThrowIfMessageBodyInvalidJson() { $processor = new ReversSyncIntegrationProcessor( $this->createDoctrineHelperStub(), $this->createReversSyncProcessorMock(), $this->createTypeRegistryMock(), new JobRunner(), $this->createLoggerMock() ); $message = new NullMessage(); $message->setBody('[}'); $processor->process($message, new NullSession()); } public function testRejectAndLogIfMessageBodyMissConnector() { $logger = $this->createLoggerMock(); $logger ->expects($this->once()) ->method('critical') ->with( 'Invalid message: integration_id and connector should not be empty:'. ' {"integration_id":"theIntegrationId"}' ) ; $processor = new ReversSyncIntegrationProcessor( $this->createDoctrineHelperStub(), $this->createReversSyncProcessorMock(), $this->createTypeRegistryMock(), new JobRunner(), $logger ); $message = new NullMessage(); $message->setBody(JSON::encode(['integration_id' => 'theIntegrationId'])); $status = $processor->process($message, new NullSession()); $this->assertEquals(MessageProcessorInterface::REJECT, $status); } public function testShouldRejectAndLogIfIntegrationNotExist() { $logger = $this->createLoggerMock(); $logger ->expects($this->once()) ->method('critical') ->with('Integration should exist and be enabled: theIntegrationId') ; $entityManagerMock = $this->createEntityManagerStub(); $entityManagerMock ->expects($this->once()) ->method('find') ->with(Integration::class, 'theIntegrationId') ->willReturn(null) ; $doctrineHelperStub = $this->createDoctrineHelperStub($entityManagerMock); $processor = new ReversSyncIntegrationProcessor( $doctrineHelperStub, $this->createReversSyncProcessorMock(), $this->createTypeRegistryMock(), new JobRunner(), $logger ); $message = new NullMessage(); $message->setBody(JSON::encode(['integration_id' => 'theIntegrationId', 'connector' => 'connector'])); $status = $processor->process($message, new NullSession()); $this->assertEquals(MessageProcessorInterface::REJECT, $status); } public function testShouldRejectAndLogIfIntegrationIsNotEnabled() { $logger = $this->createLoggerMock(); $logger ->expects($this->once()) ->method('critical') ->with('Integration should exist and be enabled: theIntegrationId') ; $integration = new Integration(); $integration->setEnabled(false); $entityManagerMock = $this->createEntityManagerStub(); $entityManagerMock ->expects($this->once()) ->method('find') ->with(Integration::class, 'theIntegrationId') ->willReturn($integration); ; $doctrineHelperStub = $this->createDoctrineHelperStub($entityManagerMock); $processor = new ReversSyncIntegrationProcessor( $doctrineHelperStub, $this->createReversSyncProcessorMock(), $this->createTypeRegistryMock(), new JobRunner(), $logger ); $message = new NullMessage(); $message->setBody(JSON::encode(['integration_id' => 'theIntegrationId', 'connector' => 'connector'])); $status = $processor->process($message, new NullSession()); $this->assertEquals(MessageProcessorInterface::REJECT, $status); } public function testRejectIfConnectionIsNotInstanceOfTwoWaySyncConnector() { $integration = new Integration(); $integration->setEnabled(true); $integration->setType('theIntegrationType'); $entityManagerMock = $this->createEntityManagerStub(); $entityManagerMock ->expects($this->once()) ->method('find') ->with(Integration::class, 'theIntegrationId') ->willReturn($integration); ; $doctrineHelperStub = $this->createDoctrineHelperStub($entityManagerMock); $typeRegistryMock = $this->createTypeRegistryMock(); $typeRegistryMock ->expects(self::once()) ->method('getConnectorType') ->with('theIntegrationType', 'theConnector') ->willReturn($this->createMock(ConnectorInterface::class)); $reversSyncProcessorMock = $this->createReversSyncProcessorMock(); $reversSyncProcessorMock ->expects(self::never()) ->method('process'); $processor = new ReversSyncIntegrationProcessor( $doctrineHelperStub, $reversSyncProcessorMock, $typeRegistryMock, new JobRunner(), $this->createLoggerMock() ); $message = new NullMessage(); $message->setBody(JSON::encode(['integration_id' => 'theIntegrationId', 'connector' => 'theConnector'])); $status = $processor->process($message, new NullSession()); $this->assertEquals(MessageProcessorInterface::REJECT, $status); } public function testShouldRunSyncAsUniqueJob() { $integration = new Integration(); $integration->setEnabled(true); $integration->setType('theIntegrationType'); $entityManagerMock = $this->createEntityManagerStub(); $entityManagerMock ->expects($this->once()) ->method('find') ->with(Integration::class, 'theIntegrationId') ->willReturn($integration); ; $doctrineHelperStub = $this->createDoctrineHelperStub($entityManagerMock); $typeRegistryMock = $this->createTypeRegistryMock(); $typeRegistryMock ->expects(self::once()) ->method('getConnectorType') ->willReturn($this->createMock(TwoWaySyncConnectorInterface::class)); $jobRunner = new JobRunner(); $processor = new ReversSyncIntegrationProcessor( $doctrineHelperStub, $this->createReversSyncProcessorMock(), $typeRegistryMock, $jobRunner, $this->createLoggerMock() ); $message = new NullMessage(); $message->setBody(JSON::encode(['integration_id' => 'theIntegrationId', 'connector' => 'theConnector'])); $message->setMessageId('theMessageId'); $processor->process($message, new NullSession()); $uniqueJobs = $jobRunner->getRunUniqueJobs(); self::assertCount(1, $uniqueJobs); self::assertEquals('oro_integration:revers_sync_integration:theIntegrationId', $uniqueJobs[0]['jobName']); self::assertEquals('theMessageId', $uniqueJobs[0]['ownerId']); } public function testShouldPerformReversSyncIfConnectorIsInstanceOfTwoWaySyncInterface() { $integration = new Integration(); $integration->setEnabled(true); $integration->setType('theIntegrationType'); $entityManagerMock = $this->createEntityManagerStub(); $entityManagerMock ->expects($this->once()) ->method('find') ->with(Integration::class, 'theIntegrationId') ->willReturn($integration) ; $doctrineHelperStub = $this->createDoctrineHelperStub($entityManagerMock); $typeRegistryMock = $this->createTypeRegistryMock(); $typeRegistryMock ->expects(self::once()) ->method('getConnectorType') ->with('theIntegrationType', 'theConnector') ->willReturn($this->createMock(TwoWaySyncConnectorInterface::class)); $processor = new ReversSyncIntegrationProcessor( $doctrineHelperStub, $this->createReversSyncProcessorMock(), $typeRegistryMock, new JobRunner(), $this->createLoggerMock() ); $message = new NullMessage(); $message->setBody(JSON::encode(['integration_id' => 'theIntegrationId', 'connector' => 'theConnector'])); $status = $processor->process($message, new NullSession()); $this->assertEquals(MessageProcessorInterface::ACK, $status); } /** * @return \PHPUnit_Framework_MockObject_MockObject|TypesRegistry */ private function createTypeRegistryMock() { return $this->createMock(TypesRegistry::class); } /** * @return \PHPUnit_Framework_MockObject_MockObject|ReverseSyncProcessor */ private function createReversSyncProcessorMock() { $reverseSyncProcessor = $this->createMock(ReverseSyncProcessor::class); $reverseSyncProcessor ->expects($this->any()) ->method('getLoggerStrategy') ->willReturn(new LoggerStrategy()) ; return $reverseSyncProcessor; } /** * @return \PHPUnit_Framework_MockObject_MockObject|EntityManagerInterface */ private function createEntityManagerStub() { $configuration = new Configuration(); $connectionMock = $this->createMock(Connection::class); $connectionMock ->expects($this->any()) ->method('getConfiguration') ->willReturn($configuration); $entityManagerMock = $this->createMock(EntityManagerInterface::class); $entityManagerMock ->expects($this->any()) ->method('getConnection') ->willReturn($connectionMock); return $entityManagerMock; } /** * @return \PHPUnit_Framework_MockObject_MockObject|DoctrineHelper */ private function createDoctrineHelperStub($entityManager = null) { $helperMock = $this->createMock(DoctrineHelper::class); $helperMock ->expects($this->any()) ->method('getEntityManagerForClass') ->willReturn($entityManager); return $helperMock; } /** * @return \PHPUnit_Framework_MockObject_MockObject | LoggerInterface */ private function createLoggerMock() { return $this->createMock(LoggerInterface::class); } }
Djamy/platform
src/Oro/Bundle/IntegrationBundle/Tests/Unit/Async/ReversSyncIntegrationProcessorTest.php
PHP
mit
13,759
require File.expand_path("../../../../../base", __FILE__) describe VagrantPlugins::CommandPlugin::Action::UninstallPlugin do let(:app) { lambda { |env| } } let(:env) {{ ui: Vagrant::UI::Silent.new, }} let(:manager) { double("manager") } subject { described_class.new(app, env) } before do Vagrant::Plugin::Manager.stub(instance: manager) end it "uninstalls the specified plugin" do manager.should_receive(:uninstall_plugin).with("bar").ordered app.should_receive(:call).ordered env[:plugin_name] = "bar" subject.call(env) end end
gavioto/vagrant
test/unit/plugins/commands/plugin/action/uninstall_plugin_test.rb
Ruby
mit
578
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert()
frappe/frappe
frappe/desk/doctype/todo/todo.py
Python
mit
4,119
<?php namespace Renatio\DynamicPDF\Console; use Illuminate\Console\Command; use Renatio\DynamicPDF\Models\Layout; use Renatio\DynamicPDF\Models\Template; use System\Classes\PluginManager; use System\Models\Parameter; class Demo extends Command { protected $signature = 'dynamicpdf:demo {--disable}'; protected $description = 'Enable/Disable PDF demo templates.'; public function handle() { if ($this->option('disable')) { $this->disableDemo(); } else { $this->enableDemo(); } } protected function enableDemo() { Parameter::set('renatio::dynamicpdf.demo', 1); $this->info(e(trans('renatio.dynamicpdf::lang.demo.enabled'))); } protected function disableDemo() { $plugin = PluginManager::instance()->findByNamespace('Renatio.DynamicPDF'); foreach ($plugin->registerPDFTemplates() as $template) { Template::where('code', $template)->delete(); } foreach ($plugin->registerPDFLayouts() as $layout) { Layout::where('code', $layout)->delete(); } Parameter::set('renatio::dynamicpdf.demo', 0); $this->info(e(trans('renatio.dynamicpdf::lang.demo.disabled'))); } }
mplodowski/dynamicpdf-plugin
console/Demo.php
PHP
mit
1,254
require 'bipbip' require 'bipbip/plugin/memcached' describe Bipbip::Plugin::Memcached do let(:plugin) { Bipbip::Plugin::Memcached.new('memcached', { 'hostname' => 'localhost', 'port' => 11_211 }, 10) } it 'should collect data' do data = plugin.monitor data['cmd_get'].should be_instance_of(Fixnum) data['cmd_set'].should be_instance_of(Fixnum) data['get_misses'].should be_instance_of(Fixnum) data['bytes'].should be_instance_of(Fixnum) data['evictions'].should be_instance_of(Fixnum) end end
ppp0/bipbip
spec/bipbip/plugin/memcached_spec.rb
Ruby
mit
526
<?php namespace TelegramBot\Api\Types\InputMedia; use TelegramBot\Api\BaseType; use TelegramBot\Api\Collection\CollectionItemInterface; /** * Class InputMedia * This object represents the content of a media message to be sent. * * @package TelegramBot\Api */ class InputMedia extends BaseType implements CollectionItemInterface { /** * {@inheritdoc} * * @var array */ static protected $requiredParams = ['type', 'media']; /** * {@inheritdoc} * * @var array */ static protected $map = [ 'type' => true, 'media' => true, 'caption' => true, 'parse_mode' => true, ]; /** * Type of the result. * * @var string */ protected $type; /** * File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), * pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" * to upload a new one using multipart/form-data under <file_attach_name> name. * * @var string */ protected $media; /** * Optional. Caption of the photo to be sent, 0-200 characters. * * @var string */ protected $caption; /** * Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, * fixed-width text or inline URLs in the media caption. * * @var string */ protected $parseMode; /** * @return string */ public function getType() { return $this->type; } /** * @param string $type */ public function setType($type) { $this->type = $type; } /** * @return string */ public function getMedia() { return $this->media; } /** * @param string $media */ public function setMedia($media) { $this->media = $media; } /** * @return string */ public function getCaption() { return $this->caption; } /** * @param string $caption */ public function setCaption($caption) { $this->caption = $caption; } /** * @return string */ public function getParseMode() { return $this->parseMode; } /** * @param string $parseMode */ public function setParseMode($parseMode) { $this->parseMode = $parseMode; } }
tgbot/api
src/Types/InputMedia/InputMedia.php
PHP
mit
2,448
<?php namespace Oro\Bundle\SearchBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\Output; use Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper; use Symfony\Component\Console\Helper\HelperInterface; class AddFulltextIndexesCommand extends ContainerAwareCommand { const COMMAND_NAME = 'oro:search:create-index'; /** * Console command configuration */ public function configure() { $this->setName(self::COMMAND_NAME); $this->setDescription('Creates fulltext index for search_index_text table'); } /** * Update indexes for MySQL database * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * * @return int|null|void */ public function execute(InputInterface $input, OutputInterface $output) { $manager = $this->getContainer()->get('oro_search.fulltext_index_manager'); $dialog = $this->getDialogHelper(); $dialog->writeSection($output, 'Creating indexes for string index table'); $result = $manager->createIndexes(); if ($result) { $dialog->writeSection($output, 'Completed.'); } } /** * @return DialogHelper|HelperInterface */ protected function getDialogHelper() { $dialog = $this->getHelperSet()->get('dialog'); if (!$dialog || get_class($dialog) !== 'Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper') { $this->getHelperSet()->set($dialog = new DialogHelper()); } return $dialog; } }
MarkThink/OROCRM
vendor/oro/platform/src/Oro/Bundle/SearchBundle/Command/AddFulltextIndexesCommand.php
PHP
mit
1,797
$(function () { // Prepare demo data var data = [ { "hc-key": "dm-lu", "value": 0 }, { "hc-key": "dm-ma", "value": 1 }, { "hc-key": "dm-pk", "value": 2 }, { "hc-key": "dm-da", "value": 3 }, { "hc-key": "dm-pl", "value": 4 }, { "hc-key": "dm-pr", "value": 5 }, { "hc-key": "dm-an", "value": 6 }, { "hc-key": "dm-go", "value": 7 }, { "hc-key": "dm-jn", "value": 8 }, { "hc-key": "dm-jh", "value": 9 } ]; // Initiate the chart $('#container').highcharts('Map', { title : { text : 'Highmaps basic demo' }, subtitle : { text : 'Source map: <a href="http://code.highcharts.com/mapdata/countries/dm/dm-all.js">Dominica</a>' }, mapNavigation: { enabled: true, buttonOptions: { verticalAlign: 'bottom' } }, colorAxis: { min: 0 }, series : [{ data : data, mapData: Highcharts.maps['countries/dm/dm-all'], joinBy: 'hc-key', name: 'Random data', states: { hover: { color: '#BADA55' } }, dataLabels: { enabled: true, format: '{point.name}' } }] }); });
Oxyless/highcharts-export-image
lib/highcharts.com/samples/mapdata/countries/dm/dm-all/demo.js
JavaScript
mit
1,719
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Olympus; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Gradation extends AbstractTag { protected $Id = 1295; protected $Name = 'Gradation'; protected $FullName = 'Olympus::CameraSettings'; protected $GroupName = 'Olympus'; protected $g0 = 'MakerNotes'; protected $g1 = 'Olympus'; protected $g2 = 'Camera'; protected $Type = 'int16s'; protected $Writable = true; protected $Description = 'Gradation'; protected $flag_Permanent = true; protected $Values = array( '-1 -1 1' => array( 'Id' => '-1 -1 1', 'Label' => 'Low Key', ), '0 -1 1' => array( 'Id' => '0 -1 1', 'Label' => 'Normal', ), '0 0 0' => array( 'Id' => '0 0 0', 'Label' => 'n/a', ), '1 -1 1' => array( 'Id' => '1 -1 1', 'Label' => 'High Key', ), ); }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Olympus/Gradation.php
PHP
mit
1,281
/// <reference path="sugar.ts" /> module vs.tools.util { 'use strict'; angular.module('vs.tools.util', []) /* @ngInject */ .factory('sugar', (config, $http) => Sugar.getInstance(config, $http)); }
voyagersearch/voyager-ui-toolkit
src/util/util.module.ts
TypeScript
mit
210
@extends('admin::admin.index') @section('th') <th>@sortablelink('created_at', trans('admin::fields.created_at'))</th> <th>@sortablelink('name', trans('admins::admin.name'))</th> <th>@sortablelink('email', 'Email')</th> <th>@lang('admin::admin.control')</th> @endsection @section('td') @foreach ($entities as $entity) <tr> <td>{{ $entity->created_at }}</td> <td>{{ $entity->name }}</td> <td>{{ $entity->email }}</td> <td> @include('admin::common.controls.edit', ['routePrefix'=>$routePrefix, 'id'=>$entity->id]) @if (Auth::guard('admin')->user()->id != $entity->id) @include('admin::common.controls.destroy', ['routePrefix'=>$routePrefix, 'id'=>$entity->id]) @endif </td> </tr> @endforeach @endsection
akhan-weltkind/larawelt2
app/Modules/Admins/Resources/Views/admin/index.blade.php
PHP
mit
871
<?php /** * UnsupportedPaymentActionException * * Throw this type of exception when a processor can not implement one method because the API does not support it. * * @author Florian Krämer * @copyright 2012 Florian Krämer * @license MIT */ class UnsupportedPaymentActionException extends Exception { }
floreadm/cakephp-payments-plugin
Lib/Error/UnsupportedPaymentActionException.php
PHP
mit
312
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/shared/each' require 'timeout' # force reload for Prime::method_added and Prime::instance Object.send(:remove_const, :Prime) if defined?(Prime) load 'prime.rb' describe "Prime.each" do it_behaves_like :prime_each, :each, Prime end describe "Prime#each" do it_behaves_like :prime_each, :each, Prime.instance end describe "Prime#each", "when an instance created via Prime.new" do before(:all) do @enough_seconds = 3 @primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ].freeze end before do @ps = Prime.new end it "iterates the given block over all prime numbers" do enumerated = [] @ps.each do |prime| break if prime >= 100 enumerated << prime end enumerated.should == @primes end it "infinitely iterates the given block passing a prime" do lambda { Timeout.timeout(@enough_seconds) { @ps.each {|prime| primality = (2..Math.sqrt(prime)).all?{|n| prime%n != 0 } primality.should be_true } } }.should raise_error(Timeout::Error) end it "raises a ArgumentError when is called with some argumetns" do lambda { @ps.each(100) do |prime| # do something end }.should raise_error(ArgumentError) end it "passes a prime to the given block ascendently" do prev = 1 @ps.each do |prime| break if prime >= 10000 prime.should > prev prev = prime end end it "returns an evaluated value of the given block" do expected = Object.new Prime.new.each{ break expected }.should equal(expected) end it "returns an enumerator (or a compatible object) if no block given" do obj = @ps.each obj.should be_kind_of(Enumerable) obj.should respond_to(:with_index) obj.should respond_to(:with_object) obj.should respond_to(:next) obj.should respond_to(:rewind) end it "raises an ArgumentError if no block given and is called with some arguments" do lambda { @ps.each(100) }.should raise_error(ArgumentError) end it "does not rewind the generator, each loop start at the current value" do @ps.next result = [] @ps.each do |p| result << p break if p > 10 end result.should == [3, 5, 7, 11] result = [] @ps.each do |p| result << p break if p > 20 end result.should == [13, 17, 19, 23] end end
sorah/rubyspec
library/prime/each_spec.rb
Ruby
mit
2,532
/*global require: false, module: false, process: false */ "use strict"; var mod = function( _, Promise, Options, Logger ) { var Log = Logger.create("AppContainer"); var WebAppContainer = function() { this.initialize.apply(this, arguments); }; _.extend(WebAppContainer.prototype, { initialize: function(opts) { opts = Options.fromObject(opts) this._app = opts.getOrError("app"); }, start: Promise.method(function() { return Promise .bind(this) .then(function() { return this._app.start(); }); }), stop: Promise.method(function(reason) { return this._app.stop().then(function() { if (reason) { Log.error("Stopping due to reason:", reason); } }); }) }); return WebAppContainer; }; module.exports = mod( require("underscore"), require("bluebird"), require("../core/options"), require("../core/logging/logger") );
maseb/thicket
src/web/thicket/appkit/web-app-container.js
JavaScript
mit
963
"use strict"; const Base = require('yeoman-generator'); const generatorArguments = require('./arguments'); const generatorOptions = require('./options'); const generatorSteps = require('./steps'); module.exports = class ResponseGenerator extends Base { constructor(args, options) { super(args, options); Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key])); Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key])); this.description = 'Scaffold a new response'; } get configuring() { return generatorSteps.configuring; } get conflicts() { return generatorSteps.conflicts; } get default() { return generatorSteps.default; } get end() { return generatorSteps.end; } get initializing() { return generatorSteps.initializing } get install() { return generatorSteps.install; } get prompting() { return generatorSteps.prompting } get writing() { return generatorSteps.writing; } };
italoag/generator-sails-rest-api
generators/response/index.js
JavaScript
mit
1,039
''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages
ArcticWarriors/scouting-app
ScoutingWebsite/Scouting2011/model/validate_match.py
Python
mit
2,608
/* * File: gtypes.cpp * ---------------- * This file implements the classes in the gtypes.h interface. * * @version 2016/10/14 * - modified floating-point equality tests to use floatingPointEqual function * @version 2015/07/05 * - using global hashing functions rather than global variables * @version 2014/10/08 * - removed 'using namespace' statement */ #include "gtypes.h" #include <cmath> #include <string> #include "error.h" #include "gmath.h" #include "hashcode.h" #include "strlib.h" /* * Implementation notes: GPoint class * ---------------------------------- * The GPoint class itself is entirely straightforward. The relational * operators compare the x components first, followed by the y component. * The hashCode function computes the exclusive-or of the individual words. */ GPoint::GPoint() { x = 0; y = 0; } GPoint::GPoint(double x, double y) { this->x = x; this->y = y; } double GPoint::getX() const { return x; } double GPoint::getY() const { return y; } std::string GPoint::toString() const { return "(" + realToString(x) + ", " + realToString(y) + ")"; } std::ostream& operator <<(std::ostream& os, const GPoint& pt) { return os << pt.toString(); } bool operator ==(const GPoint& p1, const GPoint& p2) { return floatingPointEqual(p1.x, p2.x) && floatingPointEqual(p1.y, p2.y); } bool operator !=(const GPoint& p1, const GPoint& p2) { return !(p1 == p2); } int hashCode(const GPoint& pt) { int hash = 0; for (size_t i = 0; i < sizeof(double) / sizeof(int); i++) { hash ^= ((int *) &pt.x)[i] ^ ((int *) &pt.y)[i]; } return hashMask() & hash; } /* * Implementation notes: GDimension class * -------------------------------------- * The GDimension class itself is entirely straightforward. The * relational operators compare the width first, followed by the height. * The hashCode function computes the exclusive-or of the individual words. */ GDimension::GDimension() { width = 0; height = 0; } GDimension::GDimension(double width, double height) { this->width = width; this->height = height; } double GDimension::getWidth() const { return width; } double GDimension::getHeight() const { return height; } std::string GDimension::toString() const { return "(" + realToString(width) + ", " + realToString(height) + ")"; } std::ostream& operator <<(std::ostream& os, const GDimension& dim) { return os << dim.toString(); } bool operator ==(const GDimension& d1, const GDimension& d2) { return floatingPointEqual(d1.width, d2.width) && floatingPointEqual(d1.height, d2.height); } bool operator !=(const GDimension& d1, const GDimension& d2) { return !(d1 == d2); } int hashCode(const GDimension& dim) { int hash = 0; for (size_t i = 0; i < sizeof(double) / sizeof(int); i++) { hash ^= ((int *) &dim.width)[i] ^ ((int *) &dim.height)[i]; } return hashMask() & hash; } /* * Implementation notes: GRectangle class * -------------------------------------- * The GRectangle class itself is entirely straightforward. The * relational operators compare the components in the following order: * x, y, width, height. The hashCode function computes the exclusive-or * of the individual words. */ GRectangle::GRectangle() { x = 0; y = 0; width = 0; height = 0; } GRectangle::GRectangle(double x, double y, double width, double height) { this->x = x; this->y = y; this->width = width; this->height = height; } double GRectangle::getX() const { return x; } double GRectangle::getY() const { return y; } double GRectangle::getWidth() const { return width; } double GRectangle::getHeight() const { return height; } bool GRectangle::isEmpty() const { return width <= 0 || height <= 0; } bool GRectangle::contains(double x, double y) const { return x >= this->x && y >= this->y && x < this->x + width && y < this->y + height; } bool GRectangle::contains(GPoint pt) const { return contains(pt.getX(), pt.getY()); } std::string GRectangle::toString() const { return "(" + realToString(x) + ", " + realToString(y) + ", " + realToString(width) + ", " + realToString(height) + ")"; } std::ostream& operator <<(std::ostream& os, const GRectangle& rect) { return os << rect.toString(); } bool operator ==(const GRectangle& r1, const GRectangle& r2) { return floatingPointEqual(r1.x, r2.x) && floatingPointEqual(r1.y, r2.y) && floatingPointEqual(r1.width, r2.width) && floatingPointEqual(r1.height, r2.height); } bool operator !=(const GRectangle& r1, const GRectangle& r2) { return !(r1 == r2); } int hashCode(const GRectangle& r) { int hash = 0; for (size_t i = 0; i < sizeof(double) / sizeof(int); i++) { hash ^= ((int *) &r.x)[i] ^ ((int *) &r.y)[i]; hash ^= ((int *) &r.width)[i] ^ ((int *) &r.height)[i]; } return hashMask() & hash; }
tofergregg/cs106X-website-winter-2017
lectures/26-Inheritance/code/Polymorphism/lib/StanfordCPPLib/graphics/gtypes.cpp
C++
mit
5,032
<? header('Content-Type: application/json'); $userid=$_GET["id"]; $password=$_GET["pw"]; $result = file_get_contents('http://ysweb.yonsei.ac.kr/ysbus.jsp'); $JSESSIONID= substr($http_response_header[8],23,91); $__smVisitorID= substr($http_response_header[7],26,11); $postdata = http_build_query( array( 'userid' => $userid, 'password' => $password ) ); $opts = array( "http"=>array( "method"=>"POST", "header"=>"Content-type: application/x-www-form-urlencoded\r\n". "Cookie: JSESSIONID=$JSESSIONID; __smVisitorID=$__smVisitorID", "content" => $postdata ) ); $context = stream_context_create($opts); $file = file_get_contents('http://ysweb.yonsei.ac.kr/ysbus_main.jsp', false, $context); $opts = array( "http"=>array( "method"=>"GET", "header"=>"Content-type: application/x-www-form-urlencoded\r\n". "Cookie: JSESSIONID=$JSESSIONID; __smVisitorID=$__smVisitorID" ) ); $context = stream_context_create($opts); //api selector switch($_GET['type']){ case "status": $file = file_get_contents('http://ysweb.yonsei.ac.kr/busTest/reserveinfo2.jsp', false, $context); $DOM = new DOMDocument; $DOM->loadHTML($file); $tbody = $DOM->getElementsByTagName('tbody'); $tr=$tbody->item(0)->getElementsByTagName('tr'); $result=array(); for ($i=0; $i < $tr->length; $i++) { $td=$tr->item($i)->getElementsByTagName('td'); $departure= $td->item(0)->nodeValue; $time=$td->item(1)->nodeValue; $seatNum=$td->item(2)->nodeValue; //출발위치 $departure=explode('(',$departure); //시간 $time=explode(' ',$time); $temp_date=explode('/',$time[0]); $time=$time[1]; $date=array("year"=>$temp_date[0],"month"=>$temp_date[1],"date"=>$temp_date[2]); //자리 $pos=strrpos($seatNum,"Seat No:"); $seatNum= substr($seatNum,$pos+9,strlen($seatNum)-$pos-10); $result["$i"]["departure"]=($departure[0]=="신촌캠퍼스 "?"C":"D"); $result["$i"]["time"]["date"]=$date; $result["$i"]["time"]["time"]=$time; $result["$i"]["seatNum"]=$seatNum; } echo json_encode($result); break; //예약 내역 끝 case "name": $file = file_get_contents('http://ysweb.yonsei.ac.kr/busTest/notice2.jsp', false, $context); $DOM = new DOMDocument; $DOM->loadHTML($file); $classname = 'idname'; $finder = new DomXPath($DOM); $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]"); $tmp_dom = new DOMDocument(); foreach ($nodes as $node) { $tmp_dom->appendChild($tmp_dom->importNode($node,true)); } $innerHTML=trim($tmp_dom->saveHTML()); $result=array(); $result["name"]=substr($innerHTML,21,stripos($innerHTML,"<br>")-21); echo json_encode($result); break; //이름 검색 끝 case "login": $file = file_get_contents('http://ysweb.yonsei.ac.kr/busTest/notice2.jsp', false, $context); $DOM = new DOMDocument; $DOM->loadHTML($file); $classname = 'idname'; $finder = new DomXPath($DOM); $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]"); $tmp_dom = new DOMDocument(); foreach ($nodes as $node) { $tmp_dom->appendChild($tmp_dom->importNode($node,true)); } $innerHTML=trim($tmp_dom->saveHTML()); $result=array(); $result["login"]=(substr($innerHTML,21,stripos($innerHTML,"<br>")-21)?true:false); echo json_encode($result); break; //이름 검색 끝 case "reserve": break; }
r45r54r45/bus_reserve
application/views/temp/__delete_api.php
PHP
mit
3,429
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.resources.fluentcore.arm.models; import com.microsoft.azure.management.apigeneration.Fluent; import com.microsoft.azure.management.resources.ResourceGroup; import com.microsoft.azure.management.resources.fluentcore.model.Creatable; /** * Base interface for resources in resource groups. */ @Fluent() public interface GroupableResource extends Resource { /** * @return the name of the resource group */ String resourceGroupName(); /** * Grouping of all the definition stages. */ interface DefinitionStages { /** * A resource definition allowing a resource group to be selected. * * @param <T> the next stage of the resource definition */ interface WithGroup<T> extends WithExistingResourceGroup<T>, WithNewResourceGroup<T> { } /** * A resource definition allowing a new resource group to be created. * * @param <T> the next stage of the resource definition */ interface WithNewResourceGroup<T> { /** * Creates a new resource group to put the resource in. * <p> * The group will be created in the same location as the resource. * @param name the name of the new group * @return the next stage of the resource definition */ T withNewResourceGroup(String name); /** * Creates a new resource group to put the resource in. * <p> * The group will be created in the same location as the resource. * The group's name is automatically derived from the resource's name. * @return the next stage of the resource definition */ T withNewResourceGroup(); /** * Creates a new resource group to put the resource in, based on the definition specified. * @param groupDefinition a creatable definition for a new resource group * @return the next stage of the resource definition */ T withNewResourceGroup(Creatable<ResourceGroup> groupDefinition); } /** * A resource definition allowing an existing resource group to be selected. * * @param <T> the next stage of the resource definition */ interface WithExistingResourceGroup<T> { /** * Associates the resource with an existing resource group. * @param groupName the name of an existing resource group to put this resource in. * @return the next stage of the resource definition */ T withExistingResourceGroup(String groupName); /** * Associates the resource with an existing resource group. * @param group an existing resource group to put the resource in * @return the next stage of the resource definition */ T withExistingResourceGroup(ResourceGroup group); } } }
herveyw/azure-sdk-for-java
azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/models/GroupableResource.java
Java
mit
3,293
using System; using System.Collections.Generic; using RightpointLabs.ConferenceRoom.Domain.Models; namespace RightpointLabs.ConferenceRoom.Domain.Services { public interface ISyncConferenceRoomService { RoomInfo GetStaticInfo(IRoom room); RoomStatusInfo GetStatus(IRoom room, bool isSimple = false); void StartMeeting(IRoom room, string uniqueId); bool StartMeetingFromClient(IRoom room, string uniqueId, string signature); void WarnMeeting(IRoom room, string uniqueId, Func<string, string> buildStartUrl, Func<string, string> buildCancelUrl); void AbandonMeeting(IRoom room, string uniqueId); void CancelMeeting(IRoom room, string uniqueId); void EndMeeting(IRoom room, string uniqueId); void StartNewMeeting(IRoom room, string title, DateTime endTime); void MessageMeeting(IRoom room, string uniqueId); bool CancelMeetingFromClient(IRoom room, string uniqueId, string signature); void SecurityCheck(IRoom room); Dictionary<string, Tuple<RoomInfo, IRoom>> GetInfoForRoomsInBuilding(string buildingId); } }
RightpointLabs/conference-room
Domain/Services/ISyncConferenceRoomService.cs
C#
mit
1,126
using Ploeh.AutoFixture; using Xunit; using Xunit.Extensions; namespace Ploeh.Samples.ProductManagement.PresentationLogic.Wpf.UnitTest { public class MoneyViewModelTest { [Theory, AutoMoqData] public void AmountIsProperWritableProperty(decimal expectedAmount, MoneyViewModel sut) { // Fixture setup // Exercise system sut.Amount = expectedAmount; decimal result = sut.Amount; // Verify outcome Assert.Equal(expectedAmount, result); // Teardown } [Theory, AutoMoqData] public void CurrencyIsProperWritableProperty(string expectedCurrency, MoneyViewModel sut) { // Fixture setup // Exercise system sut.CurrencyCode = expectedCurrency; string result = sut.CurrencyCode; // Verify outcome Assert.Equal(expectedCurrency, result); // Teardown } [Theory, AutoMoqData] public void ToStringReturnsCorrectResult(MoneyViewModel sut) { // Fixture setup var expectedResult = string.Format("{0} {1:F}", sut.CurrencyCode, sut.Amount); // Exercise system var result = sut.ToString(); // Verify outcome Assert.Equal(expectedResult, result); // Teardown } } }
owolp/Telerik-Academy
Module-2/Design-Patterns/Materials/DI.NET/WpfProductManagementClient/PresentationLogicUnitTest/MoneyViewModelTest.cs
C#
mit
1,408
describe('validation phone', function () { var $scope, $compile, element; beforeEach(angular.mock.module('dd.ui.validation.phone')); beforeEach(inject(function ($rootScope, _$compile_) { $scope = $rootScope; $compile = _$compile_; })); describe('general phone', function(){ beforeEach(function() { element = $compile('<form name="forma"><input type="text" name="phone" ng-model="phone" phone /></form>')($scope); }); it('should mark valid empty', function(){ $scope.phone = ''; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid when changed from invalid to empty', function(){ $scope.phone = '+123'; $scope.$digest(); $scope.phone = ''; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid null', function(){ $scope.phone = null; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid 13 numbers starting with plus', function(){ $scope.phone = '+1234567890123'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); expect($scope.forma.phone.$error).toEqual({}); }); it('should mark invalid 13 numbers wo plus sign', function(){ $scope.phone = '1234567890123'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); expect($scope.forma.phone.$error.phone).toBe(true); }); it('should mark invalid 9 numbers starting with plus', function(){ $scope.phone = '+123456789'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); }); it('should mark invalid 15 numbers starting with plus', function(){ $scope.phone = '+123456789012345'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); }); it('should mark invalid 13 numbers with one letter', function(){ $scope.phone = '+1234567890123a'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); }); }); describe('phoneCountryCode', function(){ beforeEach(function() { element = $compile('<form name="forma"><input type="text" name="phone" ng-model="phone" phone-country-code /></form>')($scope); }); it('should mark valid empty', function(){ $scope.phone = ''; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid when changed from invalid to empty', function(){ $scope.phone = 'aaa'; $scope.$digest(); $scope.phone = ''; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid null', function(){ $scope.phone = null; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid 3 numbers starting with plus', function(){ $scope.phone = '+123'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); expect($scope.forma.phone.$error).toEqual({}); }); it('should mark valid 1 number starting with plus', function(){ $scope.phone = '+1'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark invalid 3 numbers wo plus sign', function(){ $scope.phone = '123'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); expect($scope.forma.phone.$error.phoneCountryCode).toBe(true); }); it('should mark invalid 4 numbers starting with plus', function(){ $scope.phone = '+1234'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); }); it('should mark invalid 2 numbers with one letter', function(){ $scope.phone = '+12a'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); }); }); describe('phoneWoCountryCode', function(){ beforeEach(function() { element = $compile('<form name="forma"><input type="text" name="phone" ng-model="phone" phone-wo-country-code /></form>')($scope); }); it('should mark valid empty', function(){ $scope.phone = ''; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid when changed from invalid to empty', function(){ $scope.phone = 'aaa'; $scope.$digest(); $scope.phone = ''; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid null', function(){ $scope.phone = null; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); }); it('should mark valid 7 numbers', function(){ $scope.phone = '1234567'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(false); expect($scope.forma.phone.$error).toEqual({}); }); it('should mark invalid 7 numbers with plus sign', function(){ $scope.phone = '+1234567'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); expect($scope.forma.phone.$error.phoneWoCountryCode).toBe(true); }); it('should mark invalid 14 numbers', function(){ $scope.phone = '12345678901234'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); }); it('should mark invalid 7 numbers with one letter', function(){ $scope.phone = '1234567a'; $scope.$digest(); expect($scope.forma.phone.$invalid).toBe(true); }); }); });
drivr/dd-ui
src/validation/test/phone.spec.ts
TypeScript
mit
5,577
/* * Copyright (c) 2010-2017 Nathan Rajlich * * 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.java_websocket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SocketChannel; public class AbstractWrappedByteChannel implements WrappedByteChannel { private final ByteChannel channel; public AbstractWrappedByteChannel( ByteChannel towrap ) { this.channel = towrap; } public AbstractWrappedByteChannel( WrappedByteChannel towrap ) { this.channel = towrap; } @Override public int read( ByteBuffer dst ) throws IOException { return channel.read( dst ); } @Override public boolean isOpen() { return channel.isOpen(); } @Override public void close() throws IOException { channel.close(); } @Override public int write( ByteBuffer src ) throws IOException { return channel.write( src ); } @Override public boolean isNeedWrite() { return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedWrite(); } @Override public void writeMore() throws IOException { if( channel instanceof WrappedByteChannel ) ( (WrappedByteChannel) channel ).writeMore(); } @Override public boolean isNeedRead() { return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedRead(); } @Override public int readMore( ByteBuffer dst ) throws IOException { return channel instanceof WrappedByteChannel ? ( (WrappedByteChannel) channel ).readMore( dst ) : 0; } @Override public boolean isBlocking() { if( channel instanceof SocketChannel ) return ( (SocketChannel) channel ).isBlocking(); else if( channel instanceof WrappedByteChannel ) return ( (WrappedByteChannel) channel ).isBlocking(); return false; } }
leancloud/Java-WebSocket
src/main/java/org/java_websocket/AbstractWrappedByteChannel.java
Java
mit
2,843
'use strict'; const _ = require('lodash'); const moment = require('moment-timezone'); module.exports = BaseTypes => { BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types'; /** * types: [buffer_type, ...] * @see documentation : https://mariadb.com/kb/en/library/resultset/#field-types * @see connector implementation : https://github.com/MariaDB/mariadb-connector-nodejs/blob/master/lib/const/field-type.js */ BaseTypes.DATE.types.mariadb = ['DATETIME']; BaseTypes.STRING.types.mariadb = ['VAR_STRING']; BaseTypes.CHAR.types.mariadb = ['STRING']; BaseTypes.TEXT.types.mariadb = ['BLOB']; BaseTypes.TINYINT.types.mariadb = ['TINY']; BaseTypes.SMALLINT.types.mariadb = ['SHORT']; BaseTypes.MEDIUMINT.types.mariadb = ['INT24']; BaseTypes.INTEGER.types.mariadb = ['LONG']; BaseTypes.BIGINT.types.mariadb = ['LONGLONG']; BaseTypes.FLOAT.types.mariadb = ['FLOAT']; BaseTypes.TIME.types.mariadb = ['TIME']; BaseTypes.DATEONLY.types.mariadb = ['DATE']; BaseTypes.BOOLEAN.types.mariadb = ['TINY']; BaseTypes.BLOB.types.mariadb = ['TINYBLOB', 'BLOB', 'LONGBLOB']; BaseTypes.DECIMAL.types.mariadb = ['NEWDECIMAL']; BaseTypes.UUID.types.mariadb = false; BaseTypes.ENUM.types.mariadb = false; BaseTypes.REAL.types.mariadb = ['DOUBLE']; BaseTypes.DOUBLE.types.mariadb = ['DOUBLE']; BaseTypes.GEOMETRY.types.mariadb = ['GEOMETRY']; BaseTypes.JSON.types.mariadb = ['JSON']; class DECIMAL extends BaseTypes.DECIMAL { toSql() { let definition = super.toSql(); if (this._unsigned) { definition += ' UNSIGNED'; } if (this._zerofill) { definition += ' ZEROFILL'; } return definition; } } class DATE extends BaseTypes.DATE { toSql() { return `DATETIME${this._length ? `(${this._length})` : ''}`; } _stringify(date, options) { date = this._applyTimezone(date, options); return date.format('YYYY-MM-DD HH:mm:ss.SSS'); } static parse(value, options) { value = value.string(); if (value === null) { return value; } if (moment.tz.zone(options.timezone)) { value = moment.tz(value, options.timezone).toDate(); } else { value = new Date(`${value} ${options.timezone}`); } return value; } } class DATEONLY extends BaseTypes.DATEONLY { static parse(value) { return value.string(); } } class UUID extends BaseTypes.UUID { toSql() { return 'CHAR(36) BINARY'; } } class GEOMETRY extends BaseTypes.GEOMETRY { constructor(type, srid) { super(type, srid); if (_.isEmpty(this.type)) { this.sqlType = this.key; } else { this.sqlType = this.type; } } toSql() { return this.sqlType; } } class ENUM extends BaseTypes.ENUM { toSql(options) { return `ENUM(${this.values.map(value => options.escape(value)).join(', ')})`; } } class JSONTYPE extends BaseTypes.JSON { _stringify(value, options) { return options.operation === 'where' && typeof value === 'string' ? value : JSON.stringify(value); } } return { ENUM, DATE, DATEONLY, UUID, GEOMETRY, DECIMAL, JSON: JSONTYPE }; };
yjwong/sequelize
lib/dialects/mariadb/data-types.js
JavaScript
mit
3,315
// // Copyright (c) .NET Foundation and Contributors // See LICENSE file in the project root for full license information. // #include <nanoHAL.h> #include <lwip/netif.h> extern "C" struct netif * nf_getNetif(); bool Network_Interface_Bind(int index) { (void)index; return true; } int Network_Interface_Open(int index) { HAL_Configuration_NetworkInterface networkConfiguration; // load network interface configuration from storage if(!ConfigurationManager_GetConfigurationBlock((void*)&networkConfiguration, DeviceConfigurationOption_Network, index)) { // failed to load configuration // FIXME output error? return SOCK_SOCKET_ERROR; } _ASSERTE(networkConfiguration.StartupAddressMode > 0); switch(index) { case 0: { // Open the network interface and set its config // TODO / FIXME // Return index to NetIF in its linked list, return 0 (probably right if only interface) // This used by Network stack to hook in to status/address changes for events to users // For now get the Netif number form original Chibios binding code struct netif * nptr = nf_getNetif(); return nptr->num; } break; } return SOCK_SOCKET_ERROR; } bool Network_Interface_Close(int index) { switch(index) { case 0: return true; } return false; }
nanoframework/nf-interpreter
targets/FreeRTOS/NXP/_nanoCLR/Target_Network.cpp
C++
mit
1,449
namespace HydrantWiki.Mobile.Api.ResponseObjects { public class BaseResponse { public bool Success { get; set; } public string Error { get; set; } public string Message { get; set; } public BaseResponse() { } public BaseResponse(bool _success) { Success = _success; } } }
hydrantwiki/hwMobileAPI
src/hwMobileApi/ResponseObjects/BaseResponse.cs
C#
mit
357
module.exports = function () { var faker = require('faker'); var _ = require('lodash'); var getUserInfo = require('./mocks/getUserInfo.js'); var productName = function () { return faker.commerce.productAdjective() + ' ' + faker.commerce.productMaterial() + ' Widget'; }; var productImage = function () { return faker.image.imageUrl(); }; // This is your json structurn each named object below can match a remote call return { getUserInfo: getUserInfo, getSidebar: _.times(3, function (id) { return { id: id + 1, name: 'Home', icon: 'home', iconBackground: faker.internet.color(), sequence: id + 1 }; }), products: _.times(9, function (id) { var title = productName(); return { id: id + 1, title: title, image: productImage(), price: faker.commerce.price(), description: faker.lorem.paragraph(), summary: faker.lorem.paragraph() }; }), products6: _.times(6, function (id) { var title = productName(); return { id: id + 1, title: title, image: productImage(), price: faker.commerce.price(), description: faker.lorem.paragraph(), summary: faker.lorem.paragraph() }; }) }; };
matt-newell/generator-force
generators/ng/templates/api/generate.js
JavaScript
mit
1,333
/*jshint esversion: 6 */ import Service from '@ember/service'; export default Service.extend({ createCustomBlock(name, options, callback_to_change_block) { options.colour = options.colour || '#4453ff'; if (Blockly.Blocks[name]) { //console.warn(`Redefiniendo el bloque ${name}`); } Blockly.Blocks[name] = { init: function () { this.jsonInit(options); if (callback_to_change_block) { callback_to_change_block.call(this); } } }; Blockly.Blocks[name].isCustomBlock = true; if (!Blockly.MyLanguage) { Blockly.MyLanguage = Blockly.JavaScript; } if (options.code) { Blockly.MyLanguage[name] = function (block) { let variables = options.code.match(/\$(\w+)/g); let code = options.code; if (variables) { variables.forEach((v) => { let regex = new RegExp('\\' + v, "g"); let variable_name = v.slice(1); var variable_object = null; if (variable_name === "DO") { variable_object = Blockly.JavaScript.statementToCode(block, variable_name); } else { variable_object = Blockly.MyLanguage.valueToCode(block, variable_name) || block.getFieldValue(variable_name) || null; } code = code.replace(regex, variable_object); }); } return code; }; } return Blockly.Blocks[name]; }, createBlockWithAsyncDropdown(name, options) { function callback_to_change_block() { this. appendDummyInput(). appendField(options.label || ""). appendField(new Blockly.FieldDropdown(options.callbackDropdown), 'DROPDOWN_VALUE'); } return this.createCustomBlock(name, options, callback_to_change_block); }, createCustomBlockWithHelper(name, options) { let block_def = { message0: options.descripcion, colour: options.colour || '#4a6cd4', previousStatement: true, nextStatement: true, args0: [], code: options.code || `hacer(actor_id, "${options.comportamiento}", ${options.argumentos});`, }; if (options.icono) { block_def.message0 = `%1 ${options.descripcion}`; block_def.args0.push({ "type": "field_image", "src": `iconos/${options.icono}`, "width": 16, "height": 16, "alt": "*" }); } return this.createCustomBlock(name, block_def); }, createBlockValue(name, options) { let block = this.createCustomBlock(name, { message0: `%1 ${options.descripcion}`, colour: options.colour || '#4a6cd4', output: 'String', args0: [ { "type": "field_image", "src": `iconos/${options.icono}`, "width": 16, "height": 16, "alt": "*" } ], }); Blockly.MyLanguage[name] = function () { return [`'${options.valor}'`, Blockly.JavaScript.ORDER_ATOMIC]; }; return block; }, getBlocksList() { return Object.keys(Blockly.Blocks); }, getCustomBlocksList() { return Object.keys(Blockly.Blocks).filter((e) => { return Blockly.Blocks[e].isCustomBlock; } ); }, createAlias(new_name, original_block_name) { let original_block = Blockly.Blocks[original_block_name]; Blockly.Blocks[new_name] = Object.assign({}, original_block); let new_block = Blockly.Blocks[new_name]; new_block.isCustomBlock = true; new_block.aliases = [original_block_name]; if (!original_block.aliases) original_block.aliases = []; original_block.aliases.push(new_name); if (!Blockly.MyLanguage) { Blockly.MyLanguage = Blockly.JavaScript; } Blockly.MyLanguage[new_name] = Blockly.JavaScript[original_block_name]; return Blockly.Blocks[new_name]; }, setStartHat(state) { Blockly.BlockSvg.START_HAT = state; } });
hugoruscitti/ember-blockly
addon/services/blockly.js
JavaScript
mit
3,914