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
export interface IContact { id?: number; email: string; listName: string; name: string; }
SimpleCom/simplecom-web
src/interfaces/contacts.interface.ts
TypeScript
mit
98
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk.Interop { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public unsafe partial struct ExternalMemoryImageCreateInfo { /// <summary> /// The type of this structure. /// </summary> public SharpVk.StructureType SType; /// <summary> /// Null or an extension-specific structure. /// </summary> public void* Next; /// <summary> /// /// </summary> public SharpVk.ExternalMemoryHandleTypeFlags HandleTypes; } }
FacticiusVir/SharpVk
src/SharpVk/Interop/ExternalMemoryImageCreateInfo.gen.cs
C#
mit
1,882
using System; namespace Sherlock { /// <summary> /// A reader than can read values from a pipe. /// </summary> /// <typeparam name="T">The type of value to read.</typeparam> public interface IPipeReader<T> : IDisposable { /// <summary> /// Attempts to read a value from the pipe. /// </summary> /// <param name="item">The read value.</param> /// <returns>A value indicating success.</returns> bool Read(out T item); /// <summary> /// Closes the reader. /// </summary> void Close(); /// <summary> /// Gets a value indicating whether the reader is closed. /// </summary> bool IsClosed { get; } } }
tessellator/sherlock
Sherlock/IPipeReader.cs
C#
mit
742
# Load DSL and set up stages require 'capistrano/setup' # Include default deployment tasks require 'capistrano/deploy' # Include tasks from other gems included in your Gemfile require 'capistrano/rvm' require 'capistrano/bundler' require 'capistrano/rails' require 'capistrano/rails/migrations' require 'capistrano/nginx_unicorn' require 'capistrano/rails/assets' # Load custom tasks from `lib/capistrano/tasks` if you have any defined Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
a11ejandro/project_prototype
Capfile.rb
Ruby
mit
501
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var saltRounds = 10; var userSchema = new mongoose.Schema({ email: { type: String, index: {unique: true} }, password: String, name: String }); //hash password userSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds)); } userSchema.methods.validPassword = function(password){ return bcrypt.compareSync(password, this.password); } var User = mongoose.model('User',userSchema); module.exports = User;
zymokey/mission-park
models/user/user.js
JavaScript
mit
541
<?php namespace Wolphy\Jobs; use Illuminate\Bus\Queueable; abstract class Job { /* |-------------------------------------------------------------------------- | Queueable Jobs |-------------------------------------------------------------------------- | | This job base class provides a central location to place any logic that | is shared across all of your jobs. The trait included with the class | provides access to the "queueOn" and "delay" queue helper methods. | */ use Queueable; }
lezhnev74/wolphy
app/Jobs/Job.php
PHP
mit
538
<?php namespace RectorPrefix20210615; if (\class_exists('t3lib_collection_StaticRecordCollection')) { return; } class t3lib_collection_StaticRecordCollection { } \class_alias('t3lib_collection_StaticRecordCollection', 't3lib_collection_StaticRecordCollection', \false);
RectorPHP/Rector
vendor/ssch/typo3-rector/stubs/t3lib_collection_StaticRecordCollection.php
PHP
mit
276
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("RedditImageDownloader.GUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RedditImageDownloader.GUI")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] //Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie //<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei //in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch //(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung //des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile, //sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher //(wird verwendet, wenn eine Ressource auf der Seite // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.) ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs //(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.) )] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Aniel/RedditImageDownloader
RedditImageDownloader.GUI/Properties/AssemblyInfo.cs
C#
mit
2,715
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' from layers_basic import LW_Layer, default_data_format from layers_convolutional import conv_output_length ############################################### class _LW_Pooling1D(LW_Layer): input_dim = 3 def __init__(self, pool_size=2, strides=None, padding='valid'): if strides is None: strides = pool_size assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.pool_length = pool_size self.stride = strides self.border_mode = padding def get_output_shape_for(self, input_shape): length = conv_output_length(input_shape[1], self.pool_length, self.border_mode, self.stride) return (input_shape[0], length, input_shape[2]) class LW_MaxPooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_MaxPooling1D, self).__init__(pool_size, strides, padding) class LW_AveragePooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_AveragePooling1D, self).__init__(pool_size, strides, padding) ############################################### class _LW_Pooling2D(LW_Layer): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): if data_format == 'default': data_format = default_data_format assert data_format in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = padding self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'channels_last': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.pool_size[0], self.border_mode, self.strides[0]) cols = conv_output_length(cols, self.pool_size[1], self.border_mode, self.strides[1]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], rows, cols) elif self.dim_ordering == 'channels_last': return (input_shape[0], rows, cols, input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_MaxPooling2D, self).__init__(pool_size, strides, padding, data_format) class LW_AveragePooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_AveragePooling2D, self).__init__(pool_size, strides, padding, data_format) ############################################### class _LW_Pooling3D(LW_Layer): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): if dim_ordering == 'default': dim_ordering = default_data_format assert dim_ordering in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.dim_ordering = dim_ordering def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] elif self.dim_ordering == 'channels_last': len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) len_dim1 = conv_output_length(len_dim1, self.pool_size[0], self.border_mode, self.strides[0]) len_dim2 = conv_output_length(len_dim2, self.pool_size[1], self.border_mode, self.strides[1]) len_dim3 = conv_output_length(len_dim3, self.pool_size[2], self.border_mode, self.strides[2]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3) elif self.dim_ordering == 'channels_last': return (input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_MaxPooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) class LW_AveragePooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_AveragePooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) ############################################### class _LW_GlobalPooling1D(LW_Layer): def __init__(self): pass def get_output_shape_for(self, input_shape): return (input_shape[0], input_shape[2]) class LW_GlobalAveragePooling1D(_LW_GlobalPooling1D): pass class LW_GlobalMaxPooling1D(_LW_GlobalPooling1D): pass ############################################### class _LW_GlobalPooling2D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[3]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling2D(_LW_GlobalPooling2D): pass class LW_GlobalMaxPooling2D(_LW_GlobalPooling2D): pass ############################################### class _LW_GlobalPooling3D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[4]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling3D(_LW_GlobalPooling3D): pass class LW_GlobalMaxPooling3D(_LW_GlobalPooling3D): pass ############################################### if __name__ == '__main__': pass
SummaLabs/DLS
app/backend/core/models-keras-2x-api/lightweight_layers/layers_pooling.py
Python
mit
7,111
class CreateEventTypes < ActiveRecord::Migration def change create_table :event_types do |t| t.string :name, :limit => 80 t.timestamps end end end
nac13k/iAdmin
db/migrate/20140408042944_create_event_types.rb
Ruby
mit
172
module.exports = { 'throttle': 10, 'hash': true, 'gzip': false, 'baseDir': 'public', 'buildDir': 'build', 'prefix': '' };
wunderlist/bilder-aws
lib/defaults.js
JavaScript
mit
133
import type { FormatRelativeFn } from '../../../types' // Source: https://www.unicode.org/cldr/charts/32/summary/te.html const formatRelativeLocale = { lastWeek: "'గత' eeee p", // CLDR #1384 yesterday: "'నిన్న' p", // CLDR #1393 today: "'ఈ రోజు' p", // CLDR #1394 tomorrow: "'రేపు' p", // CLDR #1395 nextWeek: "'తదుపరి' eeee p", // CLDR #1386 other: 'P', } const formatRelative: FormatRelativeFn = (token, _date, _baseDate, _options) => formatRelativeLocale[token] export default formatRelative
date-fns/date-fns
src/locale/te/_lib/formatRelative/index.ts
TypeScript
mit
557
/* * * BitcoinLikeKeychain * ledger-core * * Created by Pierre Pollastri on 17/01/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #define LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #include "../../../bitcoin/BitcoinLikeExtendedPublicKey.hpp" #include <string> #include <vector> #include <utils/DerivationScheme.hpp> #include "../../../utils/Option.hpp" #include "../../../preferences/Preferences.hpp" #include "../../../api/Configuration.hpp" #include "../../../api/DynamicObject.hpp" #include <api/Currency.hpp> #include <api/AccountCreationInfo.hpp> #include <api/ExtendedKeyAccountCreationInfo.hpp> #include <api/Keychain.hpp> #include <bitcoin/BitcoinLikeAddress.hpp> namespace ledger { namespace core { class BitcoinLikeKeychain: public api::Keychain { public: enum KeyPurpose { RECEIVE, CHANGE }; public: using Address = std::shared_ptr<BitcoinLikeAddress>; BitcoinLikeKeychain( const std::shared_ptr<api::DynamicObject>& configuration, const api::Currency& params, int account, const std::shared_ptr<Preferences>& preferences); virtual bool markAsUsed(const std::vector<std::string>& addresses); virtual bool markAsUsed(const std::string& address, bool needExtendKeychain = true); virtual bool markPathAsUsed(const DerivationPath& path, bool needExtendKeychain = true) = 0; virtual std::vector<Address> getAllObservableAddresses(uint32_t from, uint32_t to) = 0; virtual std::vector<std::string> getAllObservableAddressString(uint32_t from, uint32_t to) = 0; virtual std::vector<Address> getAllObservableAddresses(KeyPurpose purpose, uint32_t from, uint32_t to) = 0; virtual Address getFreshAddress(KeyPurpose purpose) = 0; virtual std::vector<Address> getFreshAddresses(KeyPurpose purpose, size_t n) = 0; virtual Option<KeyPurpose> getAddressPurpose(const std::string& address) const = 0; virtual Option<std::string> getAddressDerivationPath(const std::string& address) const = 0; virtual bool isEmpty() const = 0; int getAccountIndex() const; const api::BitcoinLikeNetworkParameters& getNetworkParameters() const; const api::Currency& getCurrency() const; virtual Option<std::vector<uint8_t>> getPublicKey(const std::string& address) const = 0; std::shared_ptr<api::DynamicObject> getConfiguration() const; const DerivationScheme& getDerivationScheme() const; const DerivationScheme& getFullDerivationScheme() const; std::string getKeychainEngine() const; bool isSegwit() const; bool isNativeSegwit() const; virtual std::string getRestoreKey() const = 0; virtual int32_t getObservableRangeSize() const = 0; virtual bool contains(const std::string& address) const = 0; virtual std::vector<Address> getAllAddresses() = 0; virtual int32_t getOutputSizeAsSignedTxInput() const = 0; static bool isSegwit(const std::string &keychainEngine); static bool isNativeSegwit(const std::string &keychainEngine); std::shared_ptr<Preferences> getPreferences() const; protected: DerivationScheme& getDerivationScheme(); private: const api::Currency _currency; DerivationScheme _scheme; DerivationScheme _fullScheme; int _account; std::shared_ptr<Preferences> _preferences; std::shared_ptr<api::DynamicObject> _configuration; }; } } #endif //LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP
LedgerHQ/lib-ledger-core
core/src/wallet/bitcoin/keychains/BitcoinLikeKeychain.hpp
C++
mit
4,962
<?php namespace AppBundle\Repository; /** * Buyers_PropertiesRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class Buyers_PropertiesRepository extends \Doctrine\ORM\EntityRepository { }
asimo124/MLSSite
src/AppBundle/Repository/Buyers_PropertiesRepository.php
PHP
mit
257
#!/usr/bin/env ruby #Example handler file.. infile = ARGV.first outfile = File.basename(infile, ".tif") + ".jpg.tif" system("~/cm/processing_scripts/rgb_to_jpeg_tif.rb --internal-mask #{infile} #{outfile}")
spruceboy/jays_geo_tools
examples/sample_handler_for_do_several_at_once.rb
Ruby
mit
210
using Newtonsoft.Json; using ProtoBuf; using ITK.ModelManager; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Steam.Models { [Model("SteamPlayerBans")] [ProtoContract] [JsonObject(MemberSerialization.OptIn)] public class PlayerBans { /// <summary> /// A string containing the player's 64 bit ID. /// </summary> [JsonProperty("SteamID")] [ProtoMember(1, IsRequired = true)] public ulong SteamId {get; set;} /// <summary> /// Boolean indicating whether or not the player is banned from Community /// </summary> [JsonProperty("CommunityBanned")] [ProtoMember(2)] public bool IsCommunityBanned {get; set;} /// <summary> /// Boolean indicating whether or not the player has VAC bans on record. /// </summary> [JsonProperty("VACBanned")] [ProtoMember(3)] public bool IsVACBanned {get; set;} /// <summary> /// Amount of VAC bans on record. /// </summary> [JsonProperty("NumberOfVACBans")] [ProtoMember(4)] public int VACBanCount {get; set;} /// <summary> /// Amount of days since last ban. /// </summary> [JsonProperty("DaysSinceLastBan")] [ProtoMember(5)] public int DaysSinceLastBan {get; set;} /// <summary> /// String containing the player's ban status in the economy. If the player has no bans on record the string will be "none", if the player is on probation it will say "probation", and so forth. /// </summary> [JsonProperty("EconomyBan")] [ProtoMember(6)] public string EconomyBan {get; set;} public override int GetHashCode() { return SteamId.GetHashCode(); } public override bool Equals(object obj) { var other = obj as PlayerBans; return other != null && SteamId.Equals(other.SteamId); } } }
inlinevoid/Overust
Steam/Models/PlayerBans.cs
C#
mit
2,083
var modules = { "success" : [ {id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'} ], "error" : { code : "0200-ERROR", msg : "There are some errors occured." } } module.exports = { "modules": modules }
chinakite/wukong
data/datas/modules.js
JavaScript
mit
545
const { createServer, plugins: { queryParser, serveStatic } } = require('restify'); const { join } = require('path'); const fetch = require('node-fetch'); const proxy = require('http-proxy-middleware'); const { PORT = 5000 } = process.env; const server = createServer(); server.use(queryParser()); server.get('/', async (req, res, next) => { if (!req.query.b) { const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { headers: { origin: 'http://localhost:5000' }, method: 'POST' }); if (!tokenRes.ok) { return res.send(500); } const { token } = await tokenRes.json(); return res.send(302, null, { location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}` }); } return serveStatic({ directory: join(__dirname, 'dist'), file: 'index.html' })(req, res, next); }); server.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' })); server.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));
billba/botchat
packages/embed/hostDevServer.js
JavaScript
mit
1,094
/** * @author: * @date: 2016/1/21 */ define(["core/js/layout/Panel"], function (Panel) { var view = Panel.extend({ /*Panel的配置项 start*/ title:"表单-", help:"内容", brief:"摘要", /*Panel 配置 End*/ oninitialized:function(triggerEvent){ this._super(); this.mainRegion={ comXtype:$Component.TREE, comConf:{ data:[this.getModuleTree("core/js/base/AbstractView")], } }; var that = this; this.footerRegion = { comXtype: $Component.TOOLSTRIP, comConf: { /*Panel的配置项 start*/ textAlign: $TextAlign.RIGHT, items: [{ text: "展开所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().expandAll(); }, },{ text: "折叠所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().collapseAll(); }, }] /*Panel 配置 End*/ } }; }, getModuleTree:function(moduleName,arr){ var va = window.rtree.tree[moduleName]; var tree = {title: moduleName}; if(!arr){ arr = []; }else{ if(_.contains(arr,moduleName)){ return false; } } arr.push(moduleName); if(va&&va.deps&&va.deps.length>0){ tree.children = []; tree.folder=true; for(var i=0;i<va.deps.length;i++){ var newTree = this.getModuleTree(va.deps[i],arr); if(newTree){ tree.children.push(newTree); }else{ if(!tree.count){ tree.count = 0; } tree.count++; } } } return tree; } }); return view; });
huangfeng19820712/hfast
example/view/tree/treeAndTable.js
JavaScript
mit
2,606
<!-- Safe sample input : get the $_GET['userData'] in an array sanitize : settype (float) File : unsafe, use of untrusted data in a comment --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <!-- <?php $array = array(); $array[] = 'safe' ; $array[] = $_GET['userData'] ; $array[] = 'safe' ; $tainted = $array[1] ; if(settype($tainted, "float")) $tainted = $tainted ; else $tainted = 0.0 ; echo $tainted ; ?> --> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/safe/CWE_79__array-GET__CAST-func_settype_float__Unsafe_use_untrusted_data-comment.php
PHP
mit
1,367
$('#modalUploader').on('show.bs.modal', function (event) { var uploader = new qq.FileUploaderBasic({ element: document.getElementById('file-uploader-demo1'), button: document.getElementById('areaSubir'), action: '/Files/Upload', params: { ruta: $('#RutaActual').val() }, allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'], multiple: false, onComplete: function (id, fileName, responseJSON) { $.gritter.add({ title: 'Upload file', text: responseJSON.message }); }, onSubmit: function (id, fileName) { var strHtml = "<li>" + fileName + "</li>"; $("#dvxArchivos").append(strHtml); } }); }); $('#modalUploader').on('hidden.bs.modal', function () { RecargarRuta(); }) function AbrirCarpeta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function AbrirRuta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function RecargarRuta() { AbrirCarpeta($("#RutaActual").val()); } function EliminarArchivo(pRuta) { if (confirm("Are you sure that want to delete this file?")) { $.gritter.add({ title: 'Delete file', text: "File deleted" }); $("#ArchivoParaEliminar").val(pRuta); AbrirCarpeta($("#RutaActual").val()); } } function SubirNivel() { if ($("#TieneSuperior").val() == "1") { var strRutaAnterior = $("#RutaSuperior").val(); AbrirRuta(strRutaAnterior); } } function IrInicio() { AbrirRuta($("#RutaRaiz").val()); } function AbrirDialogoArchivo() { $("#modalUploader").modal(); } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); }
walalm/MVC-Azure-Explorer
MVC_Azure_Explorer/MVC_Azure_Explorer/Scripts/UtilsFileManager.js
JavaScript
mit
2,111
// setToken when re-connecting var originalReconnect = Meteor.connection.onReconnect; Meteor.connection.onReconnect = function() { setToken(); if(originalReconnect) { originalReconnect(); } }; if(Meteor.status().connected) { setToken(); } function setToken() { var firewallHumanToken = Cookie.get('sikka-human-token'); Meteor.call('setSikkaHumanToken', firewallHumanToken); } // reloading the page window.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands'); sikkaCommands.find({}).observe({ added: function(command) { if(command._id === "reload") { location.reload(); } } });
meteorhacks/sikka
lib/client/core.js
JavaScript
mit
631
using System.Collections.ObjectModel; using System.ComponentModel; using GalaSoft.MvvmLight.Command; namespace Treehopper.Mvvm.ViewModels { /// <summary> /// A delegate called when the selected board changes /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The new selected board</param> public delegate void SelectedBoardChangedEventHandler(object sender, SelectedBoardChangedEventArgs e); /// <summary> /// A delegate called when the selected board has connected /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The connected board</param> public delegate void BoardConnectedEventHandler(object sender, BoardConnectedEventArgs e); /// <summary> /// A delegate called when the selected board has disconnected /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The disconnected board</param> public delegate void BoardDisconnectedEventHandler(object sender, BoardDisconnectedEventArgs e); /// <summary> /// Base interface for the selector view model /// </summary> public interface ISelectorViewModel : INotifyPropertyChanged { /// <summary> /// Get the collection of boards /// </summary> ObservableCollection<TreehopperUsb> Boards { get; } /// <summary> /// Whether the board selection can be changed /// </summary> bool CanChangeBoardSelection { get; set; } /// <summary> /// The currently selected board /// </summary> TreehopperUsb SelectedBoard { get; set; } /// <summary> /// Occurs when the window closes /// </summary> RelayCommand WindowClosing { get; set; } /// <summary> /// Occurs when the connection occurs /// </summary> RelayCommand ConnectCommand { get; set; } /// <summary> /// Connect button text /// </summary> string ConnectButtonText { get; set; } /// <summary> /// Close command /// </summary> RelayCommand CloseCommand { get; set; } /// <summary> /// Board selection changed /// </summary> event SelectedBoardChangedEventHandler OnSelectedBoardChanged; /// <summary> /// Board connected /// </summary> event BoardConnectedEventHandler OnBoardConnected; /// <summary> /// Board disconnected /// </summary> event BoardDisconnectedEventHandler OnBoardDisconnected; } }
treehopper-electronics/treehopper-sdk
NET/Demos/WPF/DeviceManager/ViewModels/ISelectorViewModel.cs
C#
mit
2,665
import React from 'react'; import ReactDOM from 'react-dom'; import componentOrElement from 'react-prop-types/lib/componentOrElement'; import ownerDocument from './utils/ownerDocument'; import getContainer from './utils/getContainer'; /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: React.PropTypes.oneOfType([ componentOrElement, React.PropTypes.func ]), /** * Classname to use for the Portal Component */ className: React.PropTypes.string }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); if (this.props.className) { this._overlayTarget.className = this.props.className; } this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer( this, overlay, this._overlayTarget ); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { ReactDOM.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getMountNode(){ return this._overlayTarget; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; } }); export default Portal;
HPate-Riptide/react-overlays
src/Portal.js
JavaScript
mit
3,227
dojo.provide("plugins.dijit.SyncDialog"); // HAS A dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ValidationTextBox"); // INHERITS dojo.require("plugins.core.Common"); dojo.declare( "plugins.dijit.SyncDialog", [ dijit._Widget, dijit._Templated, plugins.core.Common ], { //Path to the template of this widget. templatePath: dojo.moduleUrl("plugins", "dijit/templates/syncdialog.html"), // OR USE @import IN HTML TEMPLATE cssFiles : [ dojo.moduleUrl("plugins", "dijit/css/syncdialog.css") ], // Calls dijit._Templated.widgetsInTemplate widgetsInTemplate : true, // PARENT plugins.workflow.Apps WIDGET parentWidget : null, // DISPLAYED MESSAGE message : null, //////}} constructor : function(args) { console.log("SyncDialog.constructor args:"); console.dir({args:args}); // LOAD CSS this.loadCSS(); }, postCreate : function() { //////console.log("SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()"); this.startup(); }, startup : function () { ////console.log("SyncDialog.startup plugins.dijit.SyncDialog.startup()"); ////console.log("SyncDialog.startup this.parentWidget: " + this.parentWidget); this.inherited(arguments); // SET UP DIALOG this.setDialogue(); // SET KEY LISTENER this.setKeyListener(); // ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING this.setNamespaceClass("syncDialog"); }, setKeyListener : function () { dojo.connect(this.dialog, "onkeypress", dojo.hitch(this, "handleOnKeyPress")); }, handleOnKeyPress: function (event) { var key = event.charOrCode; console.log("SyncDialog.handleOnKeyPress key: " + key); if ( key == null ) return; event.stopPropagation(); if ( key == dojo.keys.ESCAPE ) this.hide(); }, setNamespaceClass : function (ccsClass) { // ADD CSS NAMESPACE CLASS dojo.addClass(this.dialog.domNode, ccsClass); dojo.addClass(this.dialog.titleNode, ccsClass); dojo.addClass(this.dialog.closeButtonNode, ccsClass); }, show: function () { // SHOW THE DIALOGUE this.dialog.show(); this.message.focus(); }, hide: function () { // HIDE THE DIALOGUE this.dialog.hide(); }, doEnter : function(type) { // RUN ENTER CALLBACK IF 'ENTER' CLICKED console.log("SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()"); var inputs = this.validateInputs(["message", "details"]); console.log("SyncDialog.doEnter inputs:"); console.dir({inputs:inputs}); if ( ! inputs ) { console.log("SyncDialog.doEnter inputs is null. Returning"); return; } // RESET this.message.set('value', ""); this.details.value = ""; // HIDE this.hide(); // DO CALLBACK this.dialog.enterCallback(inputs); }, validateInputs : function (keys) { console.log("Hub.validateInputs keys: "); console.dir({keys:keys}); var inputs = new Object; this.isValid = true; for ( var i = 0; i < keys.length; i++ ) { console.log("Hub.validateInputs Doing keys[" + i + "]: " + keys[i]); inputs[keys[i]] = this.verifyInput(keys[i]); } console.log("Hub.validateInputs inputs: "); console.dir({inputs:inputs}); if ( ! this.isValid ) return null; return inputs; }, verifyInput : function (input) { console.log("Aws.verifyInput input: "); console.dir({this_input:this[input]}); var value = this[input].value; console.log("Aws.verifyInput value: " + value); var className = this.getClassName(this[input]); console.log("Aws.verifyInput className: " + className); if ( className ) { console.log("Aws.verifyInput this[input].isValid(): " + this[input].isValid()); if ( ! value || ! this[input].isValid() ) { console.log("Aws.verifyInput input " + input + " value is empty. Adding class 'invalid'"); dojo.addClass(this[input].domNode, 'invalid'); this.isValid = false; } else { console.log("SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'"); dojo.removeClass(this[input].domNode, 'invalid'); return value; } } else { if ( input.match(/;/) || input.match(/`/) ) { console.log("SyncDialog.verifyInput value is INVALID. Adding class 'invalid'"); dojo.addClass(this[input], 'invalid'); this.isValid = false; return null; } else { console.log("SyncDialog.verifyInput value is VALID. Removing class 'invalid'"); dojo.removeClass(this[input], 'invalid'); return value; } } return null; }, doCancel : function() { // RUN CANCEL CALLBACK IF 'CANCEL' CLICKED ////console.log("SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()"); this.dialog.cancelCallback(); this.dialog.hide(); }, setDialogue : function () { // APPEND DIALOG TO DOCUMENT document.body.appendChild(this.dialog.domNode); this.dialog.parentWidget = this; // AVOID this._fadeOutDeferred NOT DEFINED ERROR this._fadeOutDeferred = function () {}; }, load : function (args) { console.log("SyncDialog.load args:"); console.dir({args:args}); if ( args.title ) { console.log("SyncDialog.load SETTING TITLE: " + args.title); this.dialog.set('title', args.title); } this.headerNode.innerHTML = args.header; if (args.message) this.message.set('value', args.message); if (args.details) this.details.value = args.details; //if (args.details) this.details.innerHTML(args.details); this.dialog.enterCallback = args.enterCallback; this.show(); } });
agua/aguadev
html/plugins/dijit/SyncDialog.js
JavaScript
mit
5,315
namespace TraktApiSharp.Objects.Basic.Json.Factories { using Objects.Basic.Json.Reader; using Objects.Basic.Json.Writer; using Objects.Json; internal class CommentLikeJsonIOFactory : IJsonIOFactory<ITraktCommentLike> { public IObjectJsonReader<ITraktCommentLike> CreateObjectReader() => new CommentLikeObjectJsonReader(); public IArrayJsonReader<ITraktCommentLike> CreateArrayReader() => new CommentLikeArrayJsonReader(); public IObjectJsonWriter<ITraktCommentLike> CreateObjectWriter() => new CommentLikeObjectJsonWriter(); } }
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Basic/Json/Factories/CommentLikeJsonIOFactory.cs
C#
mit
583
package com.sdl.selenium.extjs3.button; import com.sdl.selenium.bootstrap.button.Download; import com.sdl.selenium.extjs3.ExtJsComponent; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; public class DownloadLink extends ExtJsComponent implements Download { public DownloadLink() { setClassName("DownloadLink"); setTag("a"); } public DownloadLink(WebLocator container) { this(); setContainer(container); } public DownloadLink(WebLocator container, String text) { this(container); setText(text, SearchType.EQUALS); } /** * Wait for the element to be activated when there is deactivation mask on top of it * * @param seconds time */ @Override public boolean waitToActivate(int seconds) { return getXPath().contains("ext-ux-livegrid") || super.waitToActivate(seconds); } /** * if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT. * Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome * Use only this: button.download("C:\\TestSet.tmx"); * return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false. * * @param fileName e.g. "TestSet.tmx" */ @Override public boolean download(String fileName) { openBrowse(); return executor.download(fileName, 10000L); } private void openBrowse() { executor.browse(this); } }
sdl/Testy
src/main/java/com/sdl/selenium/extjs3/button/DownloadLink.java
Java
mit
1,642
angular.module('perCapita.controllers', []) .controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService', function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) { $scope.loginData = $localStorage.getObject('userinfo', '{}'); $scope.reservation = {}; $scope.registration = {}; $scope.loggedIn = false; if (AuthService.isAuthenticated()) { $scope.loggedIn = true; $scope.username = AuthService.getUsername(); } // Create the login modal that we will use later $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function (modal) { $scope.modal = modal; }); // Triggered in the login modal to close it $scope.closeLogin = function () { $scope.modal.hide(); }; // Open the login modal $scope.login = function () { $scope.modal.show(); }; // Perform the login action when the user submits the login form $scope.doLogin = function () { console.log('Doing login', $scope.loginData); $localStorage.storeObject('userinfo', $scope.loginData); AuthService.login($scope.loginData); $scope.closeLogin(); }; $scope.logOut = function () { AuthService.logout(); $scope.loggedIn = false; $scope.username = ''; }; $rootScope.$on('login:Successful', function () { $scope.loggedIn = AuthService.isAuthenticated(); $scope.username = AuthService.getUsername(); }); $ionicModal.fromTemplateUrl('templates/register.html', { scope: $scope }).then(function (modal) { $scope.registerform = modal; }); $scope.closeRegister = function () { $scope.registerform.hide(); }; $scope.register = function () { $scope.registerform.show(); }; $scope.doRegister = function () { console.log('Doing registration', $scope.registration); $scope.loginData.username = $scope.registration.username; $scope.loginData.password = $scope.registration.password; AuthService.register($scope.registration); $timeout(function () { $scope.closeRegister(); }, 1000); }; $rootScope.$on('registration:Successful', function () { $localStorage.storeObject('userinfo', $scope.loginData); }); }]) .controller('FavoriteDetailsController', ['$scope', '$rootScope', '$state', '$stateParams', 'Favorites', function ($scope, $rootScope, $state, $stateParams, Favorites) { $scope.showFavButton = false; // Lookup favorites for a given user id Favorites.findById({id: $stateParams.id}) .$promise.then( function (response) { $scope.city = response; }, function (response) { $scope.message = "Error: " + response.status + " " + response.statusText; } ); }]) .controller('HomeController', ['$scope', 'perCapitaService', '$stateParams', '$rootScope', 'Favorites', '$ionicPlatform', '$cordovaLocalNotification', '$cordovaToast', function ($scope, perCapitaService, $stateParams, $rootScope, Favorites, $ionicPlatform, $cordovaLocalNotification, $cordovaToast) { $scope.showFavButton = $rootScope.currentUser; $scope.controlsData = {skills: $rootScope.skills}; // Look up jobs data $scope.doLookup = function () { $rootScope.skills = $scope.controlsData.skills; perCapitaService.lookup($scope.controlsData.skills); }; // Post process the jobs data, by adding Indeeds link and calculating jobsPer1kPeople and jobsRank $scope.updatePerCapitaData = function () { $scope.cities = perCapitaService.response.data.docs; var arrayLength = $scope.cities.length; for (var i = 0; i < arrayLength; i++) { var obj = $scope.cities[i]; obj.jobsPer1kPeople = Math.round(obj.totalResults / obj.population * 1000); obj.url = "https://www.indeed.com/jobs?q=" + $scope.controlsData.skills + "&l=" + obj.city + ", " + obj.state; } // rank jobs var sortedObjs; if (perCapitaService.isSkills) { sortedObjs = _.sortBy($scope.cities, 'totalResults').reverse(); } else { sortedObjs = _.sortBy($scope.cities, 'jobsPer1kPeople').reverse(); } $scope.cities.forEach(function (element) { element.jobsRank = sortedObjs.indexOf(element) + 1; }); if (!$scope.$$phase) { $scope.$apply(); } $rootScope.cities = $scope.cities; console.log("Loaded " + arrayLength + " results.") }; perCapitaService.registerObserverCallback($scope.updatePerCapitaData); $scope.addToFavorites = function () { delete $scope.city._id; delete $scope.city._rev; $scope.city.customerId = $rootScope.currentUser.id Favorites.create($scope.city); $ionicPlatform.ready(function () { $cordovaLocalNotification.schedule({ id: 1, title: "Added Favorite", text: $scope.city.city }).then(function () { console.log('Added Favorite ' + $scope.city.city); }, function () { console.log('Failed to add Favorite '); }); $cordovaToast .show('Added Favorite ' + $scope.city.city, 'long', 'center') .then(function (success) { // success }, function (error) { // error }); }); } if ($stateParams.id) { console.log("param " + $stateParams.id); $scope.city = $rootScope.cities.filter(function (obj) { return obj._id === $stateParams.id; })[0]; console.log($scope.city); } else { $scope.doLookup(); } }]) .controller('AboutController', ['$scope', function ($scope) { }]) .controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) { $scope.shouldShowDelete = false; /*$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { console.log("State changed: ", toState); if(toState.name === "app.favorites") $scope.refreshItems(); });*/ $scope.refreshItems = function () { if ($rootScope.currentUser) { Favorites.find({ filter: { where: { customerId: $rootScope.currentUser.id } } }).$promise.then( function (response) { $scope.favorites = response; console.log("Got favorites"); }, function (response) { console.log(response); }); } else { $scope.message = "You are not logged in" } } $scope.refreshItems(); $scope.toggleDelete = function () { $scope.shouldShowDelete = !$scope.shouldShowDelete; console.log($scope.shouldShowDelete); } $scope.deleteFavorite = function (favoriteid) { var confirmPopup = $ionicPopup.confirm({ title: '<h3>Confirm Delete</h3>', template: '<p>Are you sure you want to delete this item?</p>' }); confirmPopup.then(function (res) { if (res) { console.log('Ok to delete'); Favorites.deleteById({id: favoriteid}).$promise.then( function (response) { $scope.favorites = $scope.favorites.filter(function (el) { return el.id !== favoriteid; }); $state.go($state.current, {}, {reload: false}); // $window.location.reload(); }, function (response) { console.log(response); $state.go($state.current, {}, {reload: false}); }); } else { console.log('Canceled delete'); } }); $scope.shouldShowDelete = false; } }]) ;
vjuylov/percapita-mobile
www/js/controllers/controllers.js
JavaScript
mit
8,105
var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(preHeaders,preAnalysisFields,logName){ this.headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** * 获取服务配置信息 * @param 服务名 * @return object */ ProxyAgent.prototype.getReqConfig = function(logName){ var _self=this; var Obj={}; Obj=Config[logName]; Obj.logger=Analysis.getLogger(logName); Obj.name=logName; return Obj; } ProxyAgent.prototype.doRequest=function(_req,_res){ var _self=this; _self.reqConf=_self.getReqConfig(this.logName); logger.debug('进入'+_self.reqConf.desc+"服务"); var header_obj =this.packageHeaders(_req.headers,this.headNeeds); var url_obj = url.parse(request.url, true); var query_obj = url_obj.query; var postData = request.body|| ""; // 获取请求参数 _res.setHeader("Content-Type", config.contentType); _res.setHeader(config.headerkey, config.headerval); var opts=_self.packData(header_obj,query_obj,postData); logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]); if(typeof(postData) =="object" && postData.redis_key.length>0){ this.getRedis(opts[0],opts[1]); } else{ this.httpProxy(opts[0],opts[1]); } } /** * 封装get post接口 * @param headers * @param query * @param body * @return [] */ ProxyAgent.prototype.packData=function(headers,query,body){ var _self=this; //resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据 var type=_self.reqConf.resType || ""; body = body || ""; var len=0; var query_str=""; var body_str=""; if(type==""){ query=common.extends(query,headers); query_str = querystring.stringify(query, '&', '='); } else if(type=="body"){ body=common.extends(body,headers); body_str = querystring.stringify(body, '&', '='); len=body_str.length; if(body.redis_key){ this.redis={}; this.redis.redis_key=body.redis_key; } } else if(type=="json"){ query=common.extends(query,headers); query_str = 'json='+querystring.stringify(query, '&', '='); } else if(type=="raw"){ len=body.length; body_str=body; } var actionlocation = headers.actionlocation || ""; if(actionlocation==""){ actionlocation=query.actionlocation||""; } var opts=_self.getRequestOptions(len,actionlocation); opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str; return [opts,body_str]; } /** * 获取请求头信息 * @param len数据长度 * @param actiontion 通用访问地址 * @return object 头信息 */ ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){ var _self=this; var options = { //http请求参数设置 host: _self.reqConf.host, // 远端服务器域名 port: _self.reqConf.port, // 远端服务器端口号 path: _self.reqConf.path||"", headers : {'Connection' : 'keep-alive'} }; if(actionlocation.length>0){ options.path=actionlocation; } var rtype= _self.reqConf.reqType || ""; if(rtype.length>0){ options.headers['Content-Type']=rtype; } if(len>0){ options.headers['Content-Length']=len; } return options; } ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){ var obj={}; return obj; } /** * 获取头部信息进行封装 * @param request.headers * @param need fields ;split with ',' * @return object headers */ ProxyAgent.prototype.packageHeaders = function(headers) { var fields=arguments[1]||""; var query_obj = {}; var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址 var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源 var osversion = headers['osversion'] || '0';// 客户端系统 var devicemodel = headers['devicemodel'] || '0';// 客户端型号 var manufacturername = headers['manufacturername'] || '0';// 制造厂商 var actionlocation = headers['actionlocation']; // 请求后台地址 var dpi = headers['dpi'] || '2.0';// 密度 var imsi = headers['imsi'] || '0'; // 客户端imsi var mobileid = headers['mobileid'] || '0'; // 客户端mibileid var version = headers['version'] || '0';// 客户端版本version var selflon = headers['selflon'] || '0';// 经度 var selflat = headers['selflat'] || '0';// 维度 var uid = headers['uid'] || '0'; // 犬号 var radius=headers['radius']||'0';//误差半径 var platform=headers['platform']||"";//平台 ios ,android var gender= headers['gender'] || '0'; query_obj.gender = gender; query_obj.reqip = reqip; query_obj.forward = forward; query_obj.osversion = osversion; query_obj.devicemodel = devicemodel; query_obj.manufacturername = manufacturername; query_obj.actionlocation = actionlocation; query_obj.dpi = dpi; query_obj.imsi = imsi; query_obj.mobileid = mobileid; query_obj.version = version; query_obj.selflon = selflon; query_obj.selflat = selflat; query_obj.uid = uid; query_obj.radius=radius; query_obj.platform=platform; if(fields.length > 0){ var afields = fields.split(","); var newObj = {}; for(var i = 0; i < afields.length ; i ++){ newObj[afields[i]] = query_obj[afields[i]] || ""; } return newObj; } else{ return query_obj; } } /** * http 请求代理 * @param options 远程接口信息 * @param reqData 请求内容 req.method== get时一般为空 */ ProxyAgent.prototype.httpProxy = function (options,reqData){ var _self=this; var TongjiObj={}; var req = http.request(options, function(res) { TongjiObj.statusCode = res.statusCode ||500; var tmptime=Date.now(); TongjiObj.restime = tmptime; TongjiObj.resEnd =tmptime; TongjiObj.ends = tmptime; TongjiObj.length = 0; TongjiObj.last = tmptime; var sbuffer=new SBuffer(); res.setEncoding("utf-8"); res.on('data', function (trunk) { sbuffer.append(trunk); }); res.on('end', function () { TongjiObj.resEnd = Date.now(); //doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt); _self.emmit("onDone",sbuffer,TongjiObj); }); }); req.setTimeout(timeout,function(){ req.emit('timeOut',{message:'have been timeout...'}); }); req.on('error', function(e) { TongjiObj.statusCode=500; _self.emmit("onDone","",500,TongjiObj); }); req.on('timeOut', function(e) { req.abort(); TongjiObj.statusCode=500; TongjiObj.last = Date.now(); _self.emmit("onDone","",500,TongjiObj); }); req.end(reqData); } /** * 设置缓存 * @param redis_key * @param redis_time * @param resultBuffer */ ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) { redis_pool.acquire(function(err, client) { if (!err) { client.setex(redis_key, redis_time, resultBuffer, function(err, repliy) { redis_pool.release(client); // 链接使用完毕释放链接 }); logger.debug(redis_key + '设置缓存数据成功!'); } else { writeLogs.logs(Analysis.getLogger('error'), 'error', { msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常', err : 14 }); logger.debug(redis_key + '设置缓存数据失败!'); } }); } /** * 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存 * redis_key通过self变量中取 * @param options * @param reqData */ ProxyAgent.prototype.getRedis = function ( options, reqData) { var _self=this; var redis_key=this.redis.redis_key || ""; redis_pool.acquire(function(err, client) { if (!err) { client.get(redis_key, function(err, date) { redis_pool.release(client) // 用完之后释放链接 if (!err && date != null) { var resultBuffer = new Buffer(date); _self.response.statusCode = 200; _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); logger.debug(redis_key + '通用接口下行缓存数据:' + date); } else { _self.httpProxy(options, reqData); } }); } else { _self.httpProxy(options, reqData); } }); } /** * 输出gzip数据 * response 内置 * @param resultBuffer */ ProxyAgent.prototype.gzipOutPut = function (resultBuffer){ var _self=this; zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩 if (code != null) { // 如果正常结束 logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length); _self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志 } else { buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}'); _self.response.statusCode=500; } _self.response.setHeader("Content-Length", buffer.length); _self.response.write(buffer); _self.response.end(); }); } /** * 请求完毕处理 * @param buffer type buffer/string * @param status 请求http状态 * @param tongji object统计对象 */ ProxyAgent.prototype.onDone =function(buffer,status){ var tongji=arguments[2] ||""; var _self=this; var resultStr = typeof(buffer)=="object"?buffer.toString():buffer; if(this.reqConf.isjson==1){ var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式 if (resultObj) { // 返回结果是json格式 resultStr = JSON.stringify(resultObj); _self.response.statusCode = status; } else { resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}'; _self.response.statusCode = 500; } } else{ _self.response.statusCode = status; } var resultBuffer = new Buffer(resultStr); if(tongji!=""){ tongji.ends = Date.now(); tongji.length = resultBuffer.length; } if(resultBuffer.length > 500 ){ //压缩输出 _self.gzipOutPut(resultBuffer); }else{ _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); } if(tongji!=""){ tongji.last= Date.now(); tongji=common.extends(tongji,_self.preAnalysisFields); logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status); writeLogs.logs(poiDetailServer,'poiDetailServer',obj); } }); ProxyAgent.prototype.onDones =function(buffer,status){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); ProxyAgent.prototype.dealDones =function(){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); //ProxyAgent 从event 集成 //utils.inherit(ProxyAgent,event); exports.ProxyAgent=ProxyAgent;
RazarDessun/fastProxy
test/test_timeout2.js
JavaScript
mit
11,087
/* * The MIT License * * Copyright 2016 njacinto. * * 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.nfpj.utils.arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.Predicate; import org.nfpj.utils.predicates.TruePredicate; /** * * @author njacinto * @param <T> the type of object being returned by this iterator */ public class ArrayFilterIterator<T> implements Iterator<T> { protected static final int END_OF_ITERATION = -2; // private int nextIndex; // protected final T[] array; protected final Predicate<T> predicate; // <editor-fold defaultstate="expanded" desc="Constructors"> /** * Creates an instance of this class * * @param array the array from where this instance will extract the elements * @param predicate the filter to be applied to the elements */ public ArrayFilterIterator(T[] array, Predicate<T> predicate) { this(array, predicate, -1); } /** * * @param array * @param predicate * @param prevIndex */ protected ArrayFilterIterator(T[] array, Predicate<T> predicate, int prevIndex) { this.array = array!=null ? array : ArrayUtil.empty(); this.predicate = predicate!=null ? predicate : TruePredicate.getInstance(); this.nextIndex = getNextIndex(prevIndex); } // </editor-fold> // <editor-fold defaultstate="expanded" desc="Public methods"> /** * {@inheritDoc} */ @Override public boolean hasNext() { return nextIndex != END_OF_ITERATION; } /** * {@inheritDoc} */ @Override public T next() { if(nextIndex==END_OF_ITERATION){ throw new NoSuchElementException("The underline collection has no elements."); } int index = nextIndex; nextIndex = getNextIndex(nextIndex); return array[index]; } /** * {@inheritDoc} */ @Override public void remove() { throw new UnsupportedOperationException("The iterator doesn't allow changes."); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Protected methods"> /** * Searches for the next element that matches the filtering conditions and * returns it. * * @param currIndex * @return the next element that matches the filtering conditions or null * if no more elements are available */ protected int getNextIndex(int currIndex){ if(currIndex!=END_OF_ITERATION){ for(int i=currIndex+1; i<array.length; i++){ if(predicate.test(array[i])){ return i; } } } return END_OF_ITERATION; } // </editor-fold> }
njacinto/Utils
src/main/java/org/nfpj/utils/arrays/ArrayFilterIterator.java
Java
mit
3,840
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosHeart extends React.Component { render() { if(this.props.bare) { return <g> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </g>; } return <IconBase> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </IconBase>; } };IosHeart.defaultProps = {bare: false}
fbfeix/react-icons
src/icons/IosHeart.js
JavaScript
mit
1,031
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2010 osCommerce Released under the GNU General Public License */ require('includes/application_top.php'); require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_SPECIALS); $breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_SPECIALS)); require(DIR_WS_INCLUDES . 'template_top.php'); ?> <h1><?php echo HEADING_TITLE; ?></h1> <div class="contentContainer"> <div class="contentText"> <?php // BOF Enable & Disable Categories $specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where c.categories_status='1' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and p.products_status = '1' and p.products_id = s.products_id and pd.products_id = s.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; // EOF Enable & Disable Categories //$specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s where p.products_status = '1' and s.products_id = p.products_id and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; $specials_split = new splitPageResults($specials_query_raw, MAX_DISPLAY_SPECIAL_PRODUCTS); if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3'))) { ?> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span> </div> <br /> <?php } ?> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <?php $row = 0; $specials_query = tep_db_query($specials_split->sql_query); while ($specials = tep_db_fetch_array($specials_query)) { $row++; echo '<td align="center" width="33%"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $specials['products_image'], $specials['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a><br /><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . $specials['products_name'] . '</a><br /><del>' . $currencies->display_price($specials['products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</del><br /><span class="productSpecialPrice">' . $currencies->display_price($specials['specials_new_products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</span></td>' . "\n"; if ((($row / 3) == floor($row / 3))) { ?> </tr> <tr> <?php } } ?> </tr> </table> <?php if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '2') || (PREV_NEXT_BAR_LOCATION == '3'))) { ?> <br /> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span> </div> <?php } ?> </div> </div> <?php require(DIR_WS_INCLUDES . 'template_bottom.php'); require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
gliss/oscommerce-bootstrap
catalog/specials.php
PHP
mit
3,956
<?php declare(strict_types=1); namespace Atk4\Ui\Demos; use Atk4\Ui\Crud; use Atk4\Ui\UserAction\ExecutorFactory; // Test for hasOne Lookup as dropdown control. /** @var \Atk4\Ui\App $app */ require_once __DIR__ . '/../init-app.php'; $model = new Product($app->db); $model->addCondition($model->fieldName()->name, '=', 'Mustard'); // use default. $app->getExecutorFactory()->useTriggerDefault(ExecutorFactory::TABLE_BUTTON); $edit = $model->getUserAction('edit'); $edit->callback = function (Product $model) { return $model->product_category_id->getTitle() . ' - ' . $model->product_sub_category_id->getTitle(); }; $crud = Crud::addTo($app); $crud->setModel($model, [$model->fieldName()->name]);
atk4/ui
demos/_unit-test/lookup.php
PHP
mit
709
import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as courseActions from '../../actions/courseActions'; import CourseForm from './CourseForm'; import {authorsFormattedForDropdown} from '../../selectors/selectors'; import toastr from 'toastr'; export class ManageCoursePage extends React.Component { constructor(props, context) { super(props, context); this.state = { course: Object.assign({}, props.course), errors: {}, saving: false }; this.updateCourseState = this.updateCourseState.bind(this); this.saveCourse = this.saveCourse.bind(this); } componentWillReceiveProps(nextProps) { if (this.props.course.id != nextProps.course.id) { // Necessary to populate form when existing course is loaded directly. this.setState({course: Object.assign({}, nextProps.course)}); } } updateCourseState(event) { // handler for each form field const field = event.target.name; let course = this.state.course; course[field] = event.target.value; return this.setState({course: course}); } courseFormValid() { let formIsValid = true; let errors = {}; if (this.state.course.title.length < 5) { errors.title = 'Title must be at least 5 characters.'; formIsValid = false; } this.setState({errors: errors}); return formIsValid; } saveCourse(event) { event.preventDefault(); if (!this.courseFormValid()) { return; } this.setState({saving: true}); this.props.actions.saveCourse(this.state.course) .then(() => this.redirect()) .catch(error => { toastr.error(error); this.setState({saving: false}); }); } redirect() { // redirect to courses route this.setState({saving: false}); toastr.success('Course saved!'); this.context.router.push('/courses'); } render() { return ( <CourseForm allAuthors={this.props.authors} onChange={this.updateCourseState} onSave={this.saveCourse} errors={this.state.errors} course={this.state.course} saving={this.state.saving}/> ); } } ManageCoursePage.propTypes = { course: PropTypes.object.isRequired, authors: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; //Pull in the React Router context so router is available on this.context.router. ManageCoursePage.contextTypes = { router: PropTypes.object }; function getCourseById(courses, id) { const course = courses.filter(course => course.id == id); if (course.length) return course[0]; //since filter returns an array, have to grab the first. return null; } function mapStateToProps(state, ownProps) { let course = { id: "", title: "", watchHref: "", authorId: "", length: "23", category: "" }; const courseId = ownProps.params.id; // from the path `/course/:id` if (courseId && state.courses.length > 0) { course = getCourseById(state.courses, courseId); } return { course: course, authors: authorsFormattedForDropdown(state.authors) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(courseActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
vitaliykrushinsky/react-redux-demo
src/components/course/ManageCoursePage.js
JavaScript
mit
3,176
AmazonTemplateDescriptionCategorySpecificGridRowRenderer = Class.create(AmazonTemplateDescriptionCategorySpecificRenderer, { // --------------------------------------- attributeHandler: null, // --------------------------------------- process: function() { if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (!this.load()) { return ''; } this.renderParentSpecific(); if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (this.specificHandler.isSpecificRendered(this.indexedXPath)) { if (this.isValueForceSet()) { this.forceSelectAndDisable(this.getForceSetValue()); this.hideButton($(this.indexedXPath + '_remove_button')); var myEvent = new CustomEvent('undeleteble-specific-appear'); $(this.getParentIndexedXpath()).dispatchEvent(myEvent); } return ''; } this.renderSelf(); if (this.isValueForceSet()) { this.forceSelectAndDisable(this.getForceSetValue()); } this.observeToolTips(this.indexedXPath); this.checkSelection(); this.renderSpecificAttributes(); }, // --------------------------------------- load: function($super) { this.attributeHandler = AttributeHandlerObj; return $super(); }, //######################################## renderParentSpecific: function() { if (this.specific.parent_specific_id == null) { return ''; } if (!this.dictionaryHelper.isSpecificTypeContainer(this.parentSpecific)) { return ''; } var parentBlockRenderer = new AmazonTemplateDescriptionCategorySpecificBlockRenderer(); parentBlockRenderer.setSpecificsHandler(this.specificHandler); parentBlockRenderer.setIndexedXpath(this.getParentIndexedXpath()); parentBlockRenderer.process(); }, renderSelf: function() { this.renderLabel(); this.renderChooseMode(); this.renderValueInputs(); // affects the appearance of the actions buttons this.specificHandler.markSpecificAsRendered(this.indexedXPath); this.renderButtons(); // --------------------------------------- $(this.indexedXPath).observe('my-duplicate-is-rendered', this.onMyDuplicateRendered.bind(this)); // --------------------------------------- // like grid visibility or view of 'Add Specific' container this.throwEventsToParents(); }, renderSpecificAttributes: function() { var self = this; if (!this.specific.params.hasOwnProperty('attributes')) { return ''; } this.specific.params.attributes.each(function(attribute, index) { var renderer = new AmazonTemplateDescriptionCategorySpecificGridRowAttributeRenderer(); renderer.setSpecificsHandler(self.specificHandler); renderer.setIndexedXpath(self.indexedXPath); renderer.attribute = attribute; renderer.attributeIndex = index; renderer.process(); }); }, //######################################## renderLabel: function() { var td = new Element('td'); var title = this.specific.title; if (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) { title += ' <span class="required">*</span>'; } else if (this.dictionaryHelper.isSpecificDesired(this.specific)) { title += ' <span style="color: grey; font-style: italic;">(' + M2ePro.translator.translate('Desired') + ')</span>'; } td.appendChild((new Element('span').insert(title))); var note = this.getDefinitionNote(this.specific.data_definition); if (note) { var toolTip = this.getToolTipBlock(this.indexedXPath + '_definition_note', note); toolTip.show(); td.appendChild(toolTip); } var notice = this.getSpecificOverriddenNotice(); if (notice) td.appendChild(notice); notice = this.getSpecificParentageNotice(); if (notice) td.appendChild(notice); this.getRowContainer().appendChild(td); }, // --------------------------------------- renderChooseMode: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_mode', 'indexedxpath': this.indexedXPath, 'class' : 'M2ePro-required-when-visible', 'style' : 'width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none'})); if (this.specific.recommended_values.length > 0) { select.appendChild(new Element('option', {'value': this.MODE_RECOMMENDED_VALUE})) .insert(M2ePro.translator.translate('Recommended Values')); } select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_VALUE})) .insert(M2ePro.translator.translate('Custom Value')); select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_ATTRIBUTE})) .insert(M2ePro.translator.translate('Custom Attribute')); select.observe('change', this.onChangeChooseMode.bind(this)); this.getRowContainer().appendChild(new Element('td')).appendChild(select); }, onChangeChooseMode: function(event) { var customValue = $(this.indexedXPath + '_' + this.MODE_CUSTOM_VALUE), customValueNote = $(this.indexedXPath + '_custom_value_note'), customValueNoteError = $('advice-M2ePro-specifics-validation-' + customValue.id); var customAttribute = $(this.indexedXPath + '_' + this.MODE_CUSTOM_ATTRIBUTE), customAttributeNote = $(this.indexedXPath + '_custom_attribute_note'), customAttributeError = $('advice-M2ePro-required-when-visible-' + customAttribute.id); var recommendedValue = $(this.indexedXPath + '_' + this.MODE_RECOMMENDED_VALUE); customValue && customValue.hide(); customValueNote && customValueNote.hide(); customValueNoteError && customValueNoteError.hide(); customAttribute && customAttribute.hide(); customAttributeNote && customAttributeNote.hide(); customAttributeError && customAttributeError.hide(); recommendedValue && recommendedValue.hide(); if (event.target.value == this.MODE_CUSTOM_VALUE) { customValue && customValue.show(); customValueNote && customValueNote.show(); customValueNoteError && customValueNoteError.show(); } if (event.target.value == this.MODE_CUSTOM_ATTRIBUTE) { customAttribute && customAttribute.show(); customAttributeNote && customAttributeNote.show(); customAttributeError && customAttributeError.show(); } if (event.target.value == this.MODE_RECOMMENDED_VALUE) { recommendedValue && recommendedValue.show(); } }, // --------------------------------------- renderValueInputs: function() { var td = this.getRowContainer().appendChild(new Element('td')); // --------------------------------------- if (this.dictionaryHelper.isSpecificTypeText(this.specific)) { var note = this.getCustomValueTypeNote(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_value_note', note)); td.appendChild(this.getTextTypeInput()); } if (this.dictionaryHelper.isSpecificTypeSelect(this.specific)) { td.appendChild(this.getSelectTypeInput()); } // --------------------------------------- // --------------------------------------- note = this.getCustomAttributeTypeNote(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_attribute_note', note)); td.appendChild(this.getCustomAttributeSelect()); // --------------------------------------- td.appendChild(this.getRecommendedValuesSelect()); }, // --------------------------------------- getTextTypeInput: function() { if (this.dictionaryHelper.isSpecificTypeTextArea(this.specific)) { var input = new Element('textarea', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : 'M2ePro-required-when-visible M2ePro-specifics-validation', 'style' : 'width: 91.4%; display: none;' }); } else { var input = new Element('input', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'specific_type' : this.specific.params.type, 'type' : 'text', 'class' : 'input-text M2ePro-required-when-visible M2ePro-specifics-validation', 'style' : 'display: none; width: 91.4%;' }); this.specific.params.type == 'date_time' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d %H:%M:%S", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); this.specific.params.type == 'date' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); } input.observe('change', this.onChangeValue.bind(this)); return input; }, getSelectTypeInput: function() { var self = this; var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : 'M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none;'})); var specificOptions = this.specific.values; specificOptions.each(function(option) { var label = option == 'true' ? 'Yes' : (option == 'false' ? 'No' : option), tempOption = new Element('option', {'value': option}); select.appendChild(tempOption).insert(label); }); select.observe('change', this.onChangeValue.bind(this)); return select; }, getCustomAttributeSelect: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.MODE_CUSTOM_ATTRIBUTE, 'class' : 'attributes M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;', 'apply_to_all_attribute_sets' : '0' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.attributeHandler.availableAttributes.each(function(el) { select.appendChild(new Element('option', {'value': el.code})).insert(el.label); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); var handlerObj = new AttributeCreator(select.id); handlerObj.setSelectObj(select); handlerObj.injectAddOption(); return select; }, getRecommendedValuesSelect: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_RECOMMENDED_VALUE, 'class' : 'M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.specific.recommended_values.each(function(value) { select.appendChild(new Element('option', {'value': value})).insert(value); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); return select; }, onChangeValue: function(event) { var selectedObj = {}; selectedObj['mode'] = event.target.getAttribute('mode'); selectedObj['type'] = event.target.getAttribute('specific_type'); selectedObj['is_required'] = (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) ? 1 : 0; selectedObj[selectedObj.mode] = event.target.value; this.specificHandler.markSpecificAsSelected(this.indexedXPath, selectedObj); }, // --------------------------------------- renderButtons: function() { var td = this.getRowContainer().appendChild(new Element('td')); var cloneButton = this.getCloneButton(); if(cloneButton !== null) td.appendChild(cloneButton); var removeButton = this.getRemoveButton(); if(removeButton !== null) td.appendChild(removeButton); }, // --------------------------------------- throwEventsToParents: function() { var myEvent, parentXpath; // --------------------------------------- myEvent = new CustomEvent('child-specific-rendered'); parentXpath = this.getParentIndexedXpath(); $(parentXpath + '_grid').dispatchEvent(myEvent); $(parentXpath + '_add_row').dispatchEvent(myEvent); // --------------------------------------- // my duplicate is already rendered this.touchMyNeighbors(); // --------------------------------------- // --------------------------------------- if (this.isValueForceSet()) { this.hideButton($(this.indexedXPath + '_remove_button')); myEvent = new CustomEvent('undeleteble-specific-appear'); $(this.getParentIndexedXpath()).dispatchEvent(myEvent); } // --------------------------------------- }, //######################################## checkSelection: function() { if (this.specific.values.length == 1) { this.forceSelectAndDisable(this.specific.values[0]); return ''; } if (!this.specificHandler.isMarkedAsSelected(this.indexedXPath) && !this.specificHandler.isInFormData(this.indexedXPath)) { return ''; } var selectionInfo = this.specificHandler.getSelectionInfo(this.indexedXPath); var id = this.indexedXPath + '_mode'; $(id).value = selectionInfo.mode; this.simulateAction($(id), 'change'); if (selectionInfo.mode == this.MODE_CUSTOM_VALUE) { id = this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE; $(id).value = selectionInfo['custom_value']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.MODE_CUSTOM_ATTRIBUTE) { id = this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE; $(id).value = selectionInfo['custom_attribute']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.MODE_RECOMMENDED_VALUE) { id = this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE; $(id).value = selectionInfo['recommended_value']; this.simulateAction($(id), 'change'); } }, forceSelectAndDisable: function(value) { if (!value) { return; } var modeSelect = $(this.indexedXPath + '_mode'); modeSelect.value = this.MODE_CUSTOM_VALUE; this.simulateAction(modeSelect, 'change'); modeSelect.setAttribute('disabled','disabled'); var valueObj = $(this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE); valueObj.value = value; this.simulateAction(valueObj, 'change'); valueObj.setAttribute('disabled', 'disabled'); }, //######################################## getToolTipBlock: function(id, messageHtml) { var container = new Element('div', { 'id' : id, 'style': 'float: right; display: none;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/tool-tip-icon.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px;' })); htmlCont.appendChild(new Element('img', { 'src': M2ePro.url.get('m2epro_skin_url') + '/images/help.png' })); htmlCont.appendChild(new Element('span')).insert(messageHtml); return container; }, // --------------------------------------- getCustomValueTypeNote: function() { if (this.specific.data_definition.definition) { return null; } if (this.specific.params.type == 'int') return this.getIntTypeNote(this.specific.params); if (this.specific.params.type == 'float') return this.getFloatTypeNote(this.specific.params); if (this.specific.params.type == 'string') return this.getStringTypeNote(this.specific.params); if (this.specific.params.type == 'date_time') return this.getDatTimeTypeNote(this.specific.params); return this.getAnyTypeNote(this.specific.params); }, getIntTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'total_digits': function(restriction) { notes[3] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getFloatTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric floating point.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'decimal_places': function(restriction) { notes[3] = M2ePro.translator.translate('Decimal places (not more):') + ' ' + restriction.value + '. '; }, 'total_digits': function(restriction) { notes[4] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getStringTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: String.') + ' '; }, 'min_length': function(restriction) { notes[1] = restriction != 1 ? M2ePro.translator.translate('Min length:') + ' ' + restriction : ''; }, 'max_length': function(restriction) { notes[2] = M2ePro.translator.translate('Max length:') + ' ' + restriction; }, 'pattern': function(restriction) { if (restriction == '[a-zA-Z][a-zA-Z]|unknown') { notes[3] = M2ePro.translator.translate('Two uppercase letters or "unknown".'); } } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getDatTimeTypeNote: function(params) { var notes = []; var handler = { 'type': function(restriction) { notes.push(M2ePro.translator.translate('Type: Date time. Format: YYYY-MM-DD hh:mm:ss')); } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getAnyTypeNote: function(params) { return M2ePro.translator.translate('Can take any value.'); }, // --------------------------------------- getCustomAttributeTypeNote: function() { if (this.specific.values.length <= 0 && this.specific.recommended_values.length <= 0) { return null; } var span = new Element('span'); var title = this.specific.values.length > 0 ? M2ePro.translator.translate('Allowed Values') : M2ePro.translator.translate('Recommended Values'); span.appendChild(new Element('span')).insert('<b>' + title + ': </b>'); var ul = span.appendChild(new Element('ul')); var noteValues = this.specific.values.length > 0 ? this.specific.values : this.specific.recommended_values; noteValues.each(function(value) { ul.appendChild(new Element('li')).insert(value); }); return span.outerHTML; }, // --------------------------------------- getDefinitionNote: function(definitionPart) { if (!definitionPart.definition) { return; } var div = new Element('div'); div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Definition:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.definition); if (definitionPart.tips && definitionPart.tips.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Tips:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.tips); } if (definitionPart.example && definitionPart.example.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Examples:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.example); } return div.outerHTML; }, // --------------------------------------- getSpecificOverriddenNotice: function() { if (!this.specificHandler.canSpecificBeOverwrittenByVariationTheme(this.specific)) { return null; } var variationThemesList = this.specificHandler.themeAttributes[this.specific.xml_tag]; var message = '<b>' + M2ePro.translator.translate('Value of this Specific can be automatically overwritten by M2E Pro.') + '</b>'; message += '<br/><br/>' + variationThemesList.join(', '); return this.constructNotice(message); }, getSpecificParentageNotice: function() { if (this.specific.xml_tag != 'Parentage') { return null; } return this.constructNotice(M2ePro.translator.translate('Amazon Parentage Specific will be overridden notice.')); }, constructNotice: function(message) { var container = new Element('div', { 'style': 'float: right; margin-right: 3px; margin-top: 1px;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/warning.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px; border-color: #ffd967; background-color: #fffbf0;' })); htmlCont.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/i_notice.gif', 'style' : 'margin-top: -21px;' })); htmlCont.appendChild(new Element('span')).insert(message); return container; }, //######################################## observeToolTips: function(indexedXpath) { $$('tr[id="' + indexedXpath + '"] .tool-tip-image').each(function(element) { element.observe('mouseover', MagentoFieldTipObj.showToolTip); element.observe('mouseout', MagentoFieldTipObj.onToolTipIconMouseLeave); }); $$('tr[id="' + indexedXpath + '"] .tool-tip-message').each(function(element) { element.observe('mouseout', MagentoFieldTipObj.onToolTipMouseLeave); element.observe('mouseover', MagentoFieldTipObj.onToolTipMouseEnter); }); }, //######################################## removeAction: function($super, event) { // for attributes removing var myEvent = new CustomEvent('parent-specific-row-is-removed'); $(this.indexedXPath).dispatchEvent(myEvent); // --------------------------------------- var deleteResult = $super(event); this.throwEventsToParents(); return deleteResult; }, cloneAction: function($super, event) { var newIndexedXpath = $super(event); this.observeToolTips(newIndexedXpath); var myEvent = new CustomEvent('parent-specific-row-is-cloned', { 'new_indexed_xpath': newIndexedXpath }); $(this.indexedXPath).dispatchEvent(myEvent); return newIndexedXpath; }, // --------------------------------------- getRowContainer: function() { if ($(this.indexedXPath)) { return $(this.indexedXPath); } var grid = $$('table[id="'+ this.getParentIndexedXpath() +'_grid"] table.border tbody').first(); return grid.appendChild(new Element('tr', {id: this.indexedXPath})); } // --------------------------------------- });
portchris/NaturalRemedyCompany
src/js/M2ePro/Amazon/Template/Description/Category/Specific/Grid/RowRenderer.js
JavaScript
mit
28,752
Rails.application.config.middleware.use OmniAuth::Builder do provider :provider, ENV["KEY"], ENV["SECRET"] end
mariochavez/mac_generators
lib/generators/authentication/omniauth/templates/omniauth.rb
Ruby
mit
113
package controller.server; import controller.LibraryService; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.rmi.RemoteException; public class RMIServer { public static void main(String[] args) throws RemoteException, NamingException { LibraryService service = new DBController(); Context namingContext = new InitialContext(); namingContext.rebind("rmi:books", service); System.out.println("RMI-server is working..."); } }
niralittle/LibraryApp
src/controller/server/RMIServer.java
Java
mit
533
define([ 'angular' ], function (ng) { 'use strict'; return ng.module('backgroundModule', []); });
lukasz-si/resume
app/components/background-code/module.js
JavaScript
mit
112
const pkg = state => state.pkg const app = state => state.app const device = state => state.app.device const sidebar = state => state.app.sidebar const effect = state => state.app.effect const menuitems = state => state.menu.items const componententry = state => { return state.menu.item.filter(c => c.meta && c.meta.label === 'Components')[0] } export { pkg, app, device, sidebar, effect, menuitems, componententry }
blushft/wespk
client/src/store/getters.js
JavaScript
mit
435
using System; using System.Collections.Generic; using System.Linq; using BlackBox.Service; using EbInstanceModel; using IFC2X3; namespace BlackBox.Predefined { public partial class BbProduct : BbBase { [EarlyBindingInstance] public virtual IfcRelAggregates IfcRelAggregates { get; protected set; } public BbLocalPlacement3D ObjectBbLocalPlacement { get; protected set; } public virtual IfcObject IfcObject { get; protected set; } public string Name { get { return IfcObject.Name; } protected set { IfcObject.Name = value; } } public string Description { get { return IfcObject.Description; } protected set { IfcObject.Description = value; } } public string ObjectType { get { return IfcObject.ObjectType; } protected set { IfcObject.ObjectType = value; } } [EarlyBindingInstanceCollection] public BbProduct HostObject { get; protected set; } protected BbProduct() : this(Guid.NewGuid()) { } protected BbProduct(Guid guid) : base(guid) { } public void AddToHostObject(BbProduct hostObject) { HostObject = hostObject; var a = EarlyBindingInstanceModel.GetReferencedEntities(hostObject.IfcObject.EIN).Values; var b = (from x in a.OfType<IfcRelAggregates>() where x.RelatingObject.EIN == hostObject.IfcObject.EIN select x).ToList(); switch (b.Count) { case 0: IfcRelAggregates = new IfcRelAggregates { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostObject.IfcObject.OwnerHistory, RelatingObject = hostObject.IfcObject, RelatedObjects = new List<IfcObjectDefinition>() { }, }; break; case 1: IfcRelAggregates = b[0]; break; default: throw new NotImplementedException(); } var aa = GetType().GetProperty("IfcObject").GetValue(this, null) as IfcObject; IfcRelAggregates.RelatedObjects.Add(aa); } } }
donghoon/ifctoolkit
BlackBox/Predefined/BbProduct/BbProduct.cs
C#
mit
2,469
using UnityEngine; public class Crouch : MonoBehaviour { public float crouchColliderProportion = 0.75f; private bool crouching; private float colliderCenterY, centerOffsetY; private ChipmunkBoxShape box; private Jump jump; private Sneak sneak; private WalkAbs move; private AnimateTiledConfig crouchAC; void Awake () { crouching = false; // take the collider and some useful values box = GetComponent<ChipmunkBoxShape>(); colliderCenterY = box.center.y; centerOffsetY = ((1f - crouchColliderProportion)*0.5f) * box.size.y; jump = GetComponent<Jump>(); sneak = GetComponent<Sneak>(); move = GetComponent<WalkAbs>(); crouchAC = AnimateTiledConfig.getByName(gameObject, EnumAnimateTiledName.Crouch, true); } // Update is called once per frame public void crouch () { // is it jumping? bool jumping = false; if (jump != null && jump.isJumping()) jumping = true; // is it moving? bool moving = false; if (move != null && move.isWalking()) moving = true; // if crouching then update accordingly if (sneak != null && crouching) { // while in the air we can't sneak if (jumping) { if (sneak.isSneaking()) { sneak.stopSneaking(); crouchAC.setupAndPlay(); } } // if not jumping and not moving and sneaking: stop sneaking and do crouch else if (!moving) { if (sneak.isSneaking()) { sneak.stopSneaking(); crouchAC.setupAndPlay(); } } // if not jumping and moving: sneak else sneak.sneak(); } // don't update if (crouching || jumping) return; crouching = true; // resize the collider Vector3 theSize = box.size; theSize.y *= crouchColliderProportion; box.size = theSize; // transform the collider Vector3 theCenter = box.center; theCenter.y -= centerOffsetY; box.center = theCenter; // set the correct sprite animation crouchAC.setupAndPlay(); } public void noCrouch () { if (sneak != null) sneak.stopSneaking(); if (!crouching) return; move.stop(); // this force the reset of the sprite animation crouchAC.stop(); crouching = false; // transform the collider Vector3 theCenter = box.center; theCenter.y = colliderCenterY; box.center = theCenter; // resize the collider Vector3 theSize = box.size; theSize.y /= crouchColliderProportion; box.size = theSize; } public bool isCrouching () { return crouching; } }
fabri1983/marioBadClone
Assets/Scripts/States/Crouch.cs
C#
mit
2,429
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.applicationinsights.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** User assigned identity properties. */ @Immutable public class UserAssignedIdentity { @JsonIgnore private final ClientLogger logger = new ClientLogger(UserAssignedIdentity.class); /* * The principal ID of the assigned identity. */ @JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY) private UUID principalId; /* * The client ID of the assigned identity. */ @JsonProperty(value = "clientId", access = JsonProperty.Access.WRITE_ONLY) private UUID clientId; /** * Get the principalId property: The principal ID of the assigned identity. * * @return the principalId value. */ public UUID principalId() { return this.principalId; } /** * Get the clientId property: The client ID of the assigned identity. * * @return the clientId value. */ public UUID clientId() { return this.clientId; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
Azure/azure-sdk-for-java
sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/UserAssignedIdentity.java
Java
mit
1,557
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module('MetronicApp').controller('UsuariosCtrl', function ($scope, GetSv, $rootScope, PostSv,toaster) { $scope.usuarios = []; $scope.add = false; $scope.edit = false; $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers = function () { GetSv.getData("usuarios").then(function (data) { if (data.Error) { $scope.error = true; } else { $scope.usuarios = data; $scope.error = false; } }, function (e) { $scope.error = true; }); }; $scope.getUsers(); $scope.closeEdit = function () { $scope.a_editar = {}; $scope.edit = false; }; $scope.openEdit = function (item) { $scope.a_editar = item; $scope.edit = true; }; $scope.closeAdd = function () { $scope.add = false; }; $scope.openAdd = function (item) { $scope.a_editar = {}; $scope.add = true; }; $scope.sendUser = function (servlet, user) { PostSv.postData(servlet, {usuario: JSON.stringify(user)}).then(function (data) { if (data.Error) { toaster.pop('error', "Error", data.Error); } else { toaster.pop('success', "Exito", data.Exito); $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers(); $scope.add = false; $scope.edit = false; } }, function (e) { toaster.pop('error', "Error", "Error fatal"); } ); }; $scope.roles = $rootScope.roles; });
JoPaRoRo/Fleet
web/js/controllers/usuarios.js
JavaScript
mit
1,854
#include <vector> #include <memory> #include <iostream> using namespace std; shared_ptr<vector<int>> make() { return make_shared<vector<int>>(); } shared_ptr<vector<int>> read(shared_ptr<vector<int>> p) { cout << "Enter values: " << endl; int x; while (cin >> x) { p->push_back(x); } return p; } void print(shared_ptr<vector<int>> p) { for (int i : *p) { cout << i << " "; } } int main() { auto p = read(make()); print(p); return 0; }
mcshen99/learningCpp
learningCpp/primer12_7.cpp
C++
mit
458
/* * This file exports the configuration Express.js back to the application * so that it can be used in other parts of the product. */ var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); exports.setup = function(app, express) { app.set('views', path.join(__dirname + '../../public/views')); app.engine('html', require('ejs').renderFile); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ cookie: { maxAge: (24*3600*1000*30) }, store: new RedisStore({ host: 'localhost', port: 6379, db: 1, pass: '' }), secret: 'mylittlesecret', resave: false, saveUninitialized: false })); app.use(express.static(path.join(__dirname + '../../public'))); }
kurtbradd/facebook-music-recommender
config/express-config.js
JavaScript
mit
1,002
(function() { chai.should(); describe("Dropzone", function() { var getMockFile, xhr; getMockFile = function() { return { status: Dropzone.ADDED, accepted: true, name: "test file name", size: 123456, type: "text/html" }; }; xhr = null; beforeEach(function() { return xhr = sinon.useFakeXMLHttpRequest(); }); describe("Emitter", function() { var emitter; emitter = null; beforeEach(function() { return emitter = new Dropzone.prototype.Emitter(); }); it(".on() should return the object itself", function() { return (emitter.on("test", function() {})).should.equal(emitter); }); it(".on() should properly register listeners", function() { var callback, callback2; (emitter._callbacks === void 0).should.be["true"]; callback = function() {}; callback2 = function() {}; emitter.on("test", callback); emitter.on("test", callback2); emitter.on("test2", callback); emitter._callbacks.test.length.should.equal(2); emitter._callbacks.test[0].should.equal(callback); emitter._callbacks.test[1].should.equal(callback2); emitter._callbacks.test2.length.should.equal(1); return emitter._callbacks.test2[0].should.equal(callback); }); it(".emit() should return the object itself", function() { return emitter.emit('test').should.equal(emitter); }); it(".emit() should properly invoke all registered callbacks with arguments", function() { var callCount1, callCount12, callCount2, callback1, callback12, callback2; callCount1 = 0; callCount12 = 0; callCount2 = 0; callback1 = function(var1, var2) { callCount1++; var1.should.equal('callback1 var1'); return var2.should.equal('callback1 var2'); }; callback12 = function(var1, var2) { callCount12++; var1.should.equal('callback1 var1'); return var2.should.equal('callback1 var2'); }; callback2 = function(var1, var2) { callCount2++; var1.should.equal('callback2 var1'); return var2.should.equal('callback2 var2'); }; emitter.on("test1", callback1); emitter.on("test1", callback12); emitter.on("test2", callback2); callCount1.should.equal(0); callCount12.should.equal(0); callCount2.should.equal(0); emitter.emit("test1", "callback1 var1", "callback1 var2"); callCount1.should.equal(1); callCount12.should.equal(1); callCount2.should.equal(0); emitter.emit("test2", "callback2 var1", "callback2 var2"); callCount1.should.equal(1); callCount12.should.equal(1); callCount2.should.equal(1); emitter.emit("test1", "callback1 var1", "callback1 var2"); callCount1.should.equal(2); callCount12.should.equal(2); return callCount2.should.equal(1); }); return describe(".off()", function() { var callback1, callback2, callback3, callback4; callback1 = function() {}; callback2 = function() {}; callback3 = function() {}; callback4 = function() {}; beforeEach(function() { return emitter._callbacks = { 'test1': [callback1, callback2], 'test2': [callback3], 'test3': [callback1, callback4], 'test4': [] }; }); it("should work without any listeners", function() { var emt; emitter._callbacks = void 0; emt = emitter.off(); emitter._callbacks.should.eql({}); return emt.should.equal(emitter); }); it("should properly remove all event listeners", function() { var emt; emt = emitter.off(); emitter._callbacks.should.eql({}); return emt.should.equal(emitter); }); it("should properly remove all event listeners for specific event", function() { var emt; emitter.off("test1"); (emitter._callbacks["test1"] === void 0).should.be["true"]; emitter._callbacks["test2"].length.should.equal(1); emitter._callbacks["test3"].length.should.equal(2); emt = emitter.off("test2"); (emitter._callbacks["test2"] === void 0).should.be["true"]; return emt.should.equal(emitter); }); return it("should properly remove specific event listener", function() { var emt; emitter.off("test1", callback1); emitter._callbacks["test1"].length.should.equal(1); emitter._callbacks["test1"][0].should.equal(callback2); emitter._callbacks["test3"].length.should.equal(2); emt = emitter.off("test3", callback4); emitter._callbacks["test3"].length.should.equal(1); emitter._callbacks["test3"][0].should.equal(callback1); return emt.should.equal(emitter); }); }); }); describe("static functions", function() { describe("Dropzone.createElement()", function() { var element; element = Dropzone.createElement("<div class=\"test\"><span>Hallo</span></div>"); it("should properly create an element from a string", function() { return element.tagName.should.equal("DIV"); }); it("should properly add the correct class", function() { return element.classList.contains("test").should.be.ok; }); it("should properly create child elements", function() { return element.querySelector("span").tagName.should.equal("SPAN"); }); return it("should always return only one element", function() { element = Dropzone.createElement("<div></div><span></span>"); return element.tagName.should.equal("DIV"); }); }); describe("Dropzone.elementInside()", function() { var child1, child2, element; element = Dropzone.createElement("<div id=\"test\"><div class=\"child1\"><div class=\"child2\"></div></div></div>"); document.body.appendChild(element); child1 = element.querySelector(".child1"); child2 = element.querySelector(".child2"); after(function() { return document.body.removeChild(element); }); it("should return yes if elements are the same", function() { return Dropzone.elementInside(element, element).should.be.ok; }); it("should return yes if element is direct child", function() { return Dropzone.elementInside(child1, element).should.be.ok; }); it("should return yes if element is some child", function() { Dropzone.elementInside(child2, element).should.be.ok; return Dropzone.elementInside(child2, document.body).should.be.ok; }); return it("should return no unless element is some child", function() { Dropzone.elementInside(element, child1).should.not.be.ok; return Dropzone.elementInside(document.body, child1).should.not.be.ok; }); }); describe("Dropzone.optionsForElement()", function() { var element, testOptions; testOptions = { url: "/some/url", method: "put" }; before(function() { return Dropzone.options.testElement = testOptions; }); after(function() { return delete Dropzone.options.testElement; }); element = document.createElement("div"); it("should take options set in Dropzone.options from camelized id", function() { element.id = "test-element"; return Dropzone.optionsForElement(element).should.equal(testOptions); }); it("should return undefined if no options set", function() { element.id = "test-element2"; return expect(Dropzone.optionsForElement(element)).to.equal(void 0); }); it("should return undefined and not throw if it's a form with an input element of the name 'id'", function() { element = Dropzone.createElement("<form><input name=\"id\" /</form>"); return expect(Dropzone.optionsForElement(element)).to.equal(void 0); }); return it("should ignore input fields with the name='id'", function() { element = Dropzone.createElement("<form id=\"test-element\"><input type=\"hidden\" name=\"id\" value=\"fooo\" /></form>"); return Dropzone.optionsForElement(element).should.equal(testOptions); }); }); describe("Dropzone.forElement()", function() { var dropzone, element; element = document.createElement("div"); element.id = "some-test-element"; dropzone = null; before(function() { document.body.appendChild(element); return dropzone = new Dropzone(element, { url: "/test" }); }); after(function() { dropzone.disable(); return document.body.removeChild(element); }); it("should throw an exception if no dropzone attached", function() { return expect(function() { return Dropzone.forElement(document.createElement("div")); }).to["throw"]("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); }); it("should accept css selectors", function() { return expect(Dropzone.forElement("#some-test-element")).to.equal(dropzone); }); return it("should accept native elements", function() { return expect(Dropzone.forElement(element)).to.equal(dropzone); }); }); describe("Dropzone.discover()", function() { var element1, element2, element3; element1 = document.createElement("div"); element1.className = "dropzone"; element2 = element1.cloneNode(); element3 = element1.cloneNode(); element1.id = "test-element-1"; element2.id = "test-element-2"; element3.id = "test-element-3"; describe("specific options", function() { before(function() { Dropzone.options.testElement1 = { url: "test-url" }; Dropzone.options.testElement2 = false; document.body.appendChild(element1); document.body.appendChild(element2); return Dropzone.discover(); }); after(function() { document.body.removeChild(element1); return document.body.removeChild(element2); }); it("should find elements with a .dropzone class", function() { return element1.dropzone.should.be.ok; }); return it("should not create dropzones with disabled options", function() { return expect(element2.dropzone).to.not.be.ok; }); }); return describe("Dropzone.autoDiscover", function() { before(function() { Dropzone.options.testElement3 = { url: "test-url" }; return document.body.appendChild(element3); }); after(function() { return document.body.removeChild(element3); }); it("should create dropzones even if Dropzone.autoDiscover == false", function() { Dropzone.autoDiscover = false; Dropzone.discover(); return expect(element3.dropzone).to.be.ok; }); return it("should not automatically be called if Dropzone.autoDiscover == false", function() { Dropzone.autoDiscover = false; Dropzone.discover = function() { return expect(false).to.be.ok; }; return Dropzone._autoDiscoverFunction(); }); }); }); describe("Dropzone.isValidFile()", function() { it("should return true if called without acceptedFiles", function() { return Dropzone.isValidFile({ type: "some/type" }, null).should.be.ok; }); it("should properly validate if called with concrete mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html,image/jpeg,application/json"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate if called with base mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/*,image/*,application/*"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate if called with mixed mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/*,image/jpeg,application/*"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate even with spaces in between", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html , image/jpeg, application/json"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; }); return it("should properly validate extensions", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html , image/jpeg, .pdf ,.png"; Dropzone.isValidFile({ name: "somxsfsd", type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "somesdfsdf", type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "somesdfadfadf", type: "application/json" }, acceptedMimeTypes).should.not.be.ok; Dropzone.isValidFile({ name: "some-file file.pdf", type: "random/type" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "some-file.pdf file.gif", type: "random/type" }, acceptedMimeTypes).should.not.be.ok; return Dropzone.isValidFile({ name: "some-file file.png", type: "random/type" }, acceptedMimeTypes).should.be.ok; }); }); return describe("Dropzone.confirm", function() { beforeEach(function() { return sinon.stub(window, "confirm"); }); afterEach(function() { return window.confirm.restore(); }); it("should forward to window.confirm and call the callbacks accordingly", function() { var accepted, rejected; accepted = rejected = false; window.confirm.returns(true); Dropzone.confirm("test question", (function() { return accepted = true; }), (function() { return rejected = true; })); window.confirm.args[0][0].should.equal("test question"); accepted.should.equal(true); rejected.should.equal(false); accepted = rejected = false; window.confirm.returns(false); Dropzone.confirm("test question 2", (function() { return accepted = true; }), (function() { return rejected = true; })); window.confirm.args[1][0].should.equal("test question 2"); accepted.should.equal(false); return rejected.should.equal(true); }); return it("should not error if rejected is not provided", function() { var accepted, rejected; accepted = rejected = false; window.confirm.returns(false); Dropzone.confirm("test question", (function() { return accepted = true; })); window.confirm.args[0][0].should.equal("test question"); accepted.should.equal(false); return rejected.should.equal(false); }); }); }); describe("Dropzone.getElement() / getElements()", function() { var tmpElements; tmpElements = []; beforeEach(function() { tmpElements = []; tmpElements.push(Dropzone.createElement("<div class=\"tmptest\"></div>")); tmpElements.push(Dropzone.createElement("<div id=\"tmptest1\" class=\"random\"></div>")); tmpElements.push(Dropzone.createElement("<div class=\"random div\"></div>")); return tmpElements.forEach(function(el) { return document.body.appendChild(el); }); }); afterEach(function() { return tmpElements.forEach(function(el) { return document.body.removeChild(el); }); }); describe(".getElement()", function() { it("should accept a string", function() { var el; el = Dropzone.getElement(".tmptest"); el.should.equal(tmpElements[0]); el = Dropzone.getElement("#tmptest1"); return el.should.equal(tmpElements[1]); }); it("should accept a node", function() { var el; el = Dropzone.getElement(tmpElements[2]); return el.should.equal(tmpElements[2]); }); return it("should fail if invalid selector", function() { var errorMessage; errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."; expect(function() { return Dropzone.getElement("lblasdlfsfl", "clickable"); }).to["throw"](errorMessage); expect(function() { return Dropzone.getElement({ "lblasdlfsfl": "lblasdlfsfl" }, "clickable"); }).to["throw"](errorMessage); return expect(function() { return Dropzone.getElement(["lblasdlfsfl"], "clickable"); }).to["throw"](errorMessage); }); }); return describe(".getElements()", function() { it("should accept a list of strings", function() { var els; els = Dropzone.getElements([".tmptest", "#tmptest1"]); return els.should.eql([tmpElements[0], tmpElements[1]]); }); it("should accept a list of nodes", function() { var els; els = Dropzone.getElements([tmpElements[0], tmpElements[2]]); return els.should.eql([tmpElements[0], tmpElements[2]]); }); it("should accept a mixed list", function() { var els; els = Dropzone.getElements(["#tmptest1", tmpElements[2]]); return els.should.eql([tmpElements[1], tmpElements[2]]); }); it("should accept a string selector", function() { var els; els = Dropzone.getElements(".random"); return els.should.eql([tmpElements[1], tmpElements[2]]); }); it("should accept a single node", function() { var els; els = Dropzone.getElements(tmpElements[1]); return els.should.eql([tmpElements[1]]); }); return it("should fail if invalid selector", function() { var errorMessage; errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."; expect(function() { return Dropzone.getElements("lblasdlfsfl", "clickable"); }).to["throw"](errorMessage); return expect(function() { return Dropzone.getElements(["lblasdlfsfl"], "clickable"); }).to["throw"](errorMessage); }); }); }); describe("constructor()", function() { var dropzone; dropzone = null; afterEach(function() { if (dropzone != null) { return dropzone.destroy(); } }); it("should throw an exception if the element is invalid", function() { return expect(function() { return dropzone = new Dropzone("#invalid-element"); }).to["throw"]("Invalid dropzone element."); }); it("should throw an exception if assigned twice to the same element", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return expect(function() { return new Dropzone(element, { url: "url" }); }).to["throw"]("Dropzone already attached."); }); it("should throw an exception if both acceptedFiles and acceptedMimeTypes are specified", function() { var element; element = document.createElement("div"); return expect(function() { return dropzone = new Dropzone(element, { url: "test", acceptedFiles: "param", acceptedMimeTypes: "types" }); }).to["throw"]("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); }); it("should set itself as element.dropzone", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return element.dropzone.should.equal(dropzone); }); it("should add itself to Dropzone.instances", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return Dropzone.instances[Dropzone.instances.length - 1].should.equal(dropzone); }); it("should use the action attribute not the element with the name action", function() { var element; element = Dropzone.createElement("<form action=\"real-action\"><input type=\"hidden\" name=\"action\" value=\"wrong-action\" /></form>"); dropzone = new Dropzone(element); return dropzone.options.url.should.equal("real-action"); }); return describe("options", function() { var element, element2; element = null; element2 = null; beforeEach(function() { element = document.createElement("div"); element.id = "test-element"; element2 = document.createElement("div"); element2.id = "test-element2"; return Dropzone.options.testElement = { url: "/some/url", parallelUploads: 10 }; }); afterEach(function() { return delete Dropzone.options.testElement; }); it("should take the options set in Dropzone.options", function() { dropzone = new Dropzone(element); dropzone.options.url.should.equal("/some/url"); return dropzone.options.parallelUploads.should.equal(10); }); it("should prefer passed options over Dropzone.options", function() { dropzone = new Dropzone(element, { url: "/some/other/url" }); return dropzone.options.url.should.equal("/some/other/url"); }); it("should take the default options if nothing set in Dropzone.options", function() { dropzone = new Dropzone(element2, { url: "/some/url" }); return dropzone.options.parallelUploads.should.equal(2); }); it("should call the fallback function if forceFallback == true", function(done) { return dropzone = new Dropzone(element, { url: "/some/other/url", forceFallback: true, fallback: function() { return done(); } }); }); it("should set acceptedFiles if deprecated acceptedMimetypes option has been passed", function() { dropzone = new Dropzone(element, { url: "/some/other/url", acceptedMimeTypes: "my/type" }); return dropzone.options.acceptedFiles.should.equal("my/type"); }); return describe("options.clickable", function() { var clickableElement; clickableElement = null; dropzone = null; beforeEach(function() { clickableElement = document.createElement("div"); clickableElement.className = "some-clickable"; return document.body.appendChild(clickableElement); }); afterEach(function() { document.body.removeChild(clickableElement); if (dropzone != null) { return dropzone.destroy; } }); it("should use the default element if clickable == true", function() { dropzone = new Dropzone(element, { clickable: true }); return dropzone.clickableElements.should.eql([dropzone.element]); }); it("should lookup the element if clickable is a CSS selector", function() { dropzone = new Dropzone(element, { clickable: ".some-clickable" }); return dropzone.clickableElements.should.eql([clickableElement]); }); it("should simply use the provided element", function() { dropzone = new Dropzone(element, { clickable: clickableElement }); return dropzone.clickableElements.should.eql([clickableElement]); }); it("should accept multiple clickable elements", function() { dropzone = new Dropzone(element, { clickable: [document.body, ".some-clickable"] }); return dropzone.clickableElements.should.eql([document.body, clickableElement]); }); return it("should throw an exception if the element is invalid", function() { return expect(function() { return dropzone = new Dropzone(element, { clickable: ".some-invalid-clickable" }); }).to["throw"]("Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); }); }); }); }); describe("init()", function() { describe("clickable", function() { var dropzone, dropzones, name, _results; dropzones = { "using acceptedFiles": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptedFiles: "audio/*,video/*" }), "using acceptedMimeTypes": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptedMimeTypes: "audio/*,video/*" }) }; it("should not add an accept attribute if no acceptParameter", function() { var dropzone; dropzone = new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); return dropzone.hiddenFileInput.hasAttribute("accept").should.be["false"]; }); _results = []; for (name in dropzones) { dropzone = dropzones[name]; _results.push(describe(name, function() { return (function(dropzone) { it("should create a hidden file input if clickable", function() { dropzone.hiddenFileInput.should.be.ok; return dropzone.hiddenFileInput.tagName.should.equal("INPUT"); }); it("should use the acceptParameter", function() { return dropzone.hiddenFileInput.getAttribute("accept").should.equal("audio/*,video/*"); }); return it("should create a new input element when something is selected to reset the input field", function() { var event, hiddenFileInput, i, _i, _results1; _results1 = []; for (i = _i = 0; _i <= 3; i = ++_i) { hiddenFileInput = dropzone.hiddenFileInput; event = document.createEvent("HTMLEvents"); event.initEvent("change", true, true); hiddenFileInput.dispatchEvent(event); dropzone.hiddenFileInput.should.not.equal(hiddenFileInput); _results1.push(Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok); } return _results1; }); })(dropzone); })); } return _results; }); it("should create a .dz-message element", function() { var dropzone, element; element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>"); dropzone = new Dropzone(element, { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); return element.querySelector(".dz-message").should.be["instanceof"](Element); }); return it("should not create a .dz-message element if there already is one", function() { var dropzone, element, msg; element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>"); msg = Dropzone.createElement("<div class=\"dz-message\">TEST</div>"); element.appendChild(msg); dropzone = new Dropzone(element, { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); element.querySelector(".dz-message").should.equal(msg); return element.querySelectorAll(".dz-message").length.should.equal(1); }); }); describe("options", function() { var dropzone, element; element = null; dropzone = null; beforeEach(function() { element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", maxFiles: 3 }); }); return describe("file specific", function() { var file; file = null; beforeEach(function() { file = { name: "test name", size: 2 * 1024 * 1024, width: 200, height: 100 }; return dropzone.options.addedfile.call(dropzone, file); }); describe(".addedFile()", function() { return it("should properly create the previewElement", function() { file.previewElement.should.be["instanceof"](Element); file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql("test name"); return file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql("<strong>2.1</strong> MB"); }); }); describe(".error()", function() { it("should properly insert the error", function() { dropzone.options.error.call(dropzone, file, "test message"); return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message"); }); return it("should properly insert the error when provided with an object containing the error", function() { dropzone.options.error.call(dropzone, file, { error: "test message" }); return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message"); }); }); describe(".thumbnail()", function() { return it("should properly insert the error", function() { var thumbnail, transparentGif; transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; dropzone.options.thumbnail.call(dropzone, file, transparentGif); thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]"); thumbnail.src.should.eql(transparentGif); return thumbnail.alt.should.eql("test name"); }); }); describe(".uploadprogress()", function() { return it("should properly set the width", function() { dropzone.options.uploadprogress.call(dropzone, file, 0); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("0%"); dropzone.options.uploadprogress.call(dropzone, file, 80); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("80%"); dropzone.options.uploadprogress.call(dropzone, file, 90); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("90%"); dropzone.options.uploadprogress.call(dropzone, file, 100); return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("100%"); }); }); return describe(".resize()", function() { describe("with default thumbnail settings", function() { return it("should properly return target dimensions", function() { var info; info = dropzone.options.resize.call(dropzone, file); info.optWidth.should.eql(120); return info.optHeight.should.eql(120); }); }); return describe("with null thumbnail settings", function() { return it("should properly return target dimensions", function() { var i, info, setting, testSettings, _i, _len, _results; testSettings = [[null, null], [null, 150], [150, null]]; _results = []; for (i = _i = 0, _len = testSettings.length; _i < _len; i = ++_i) { setting = testSettings[i]; dropzone.options.thumbnailWidth = setting[0]; dropzone.options.thumbnailHeight = setting[1]; info = dropzone.options.resize.call(dropzone, file); if (i === 0) { info.optWidth.should.eql(200); info.optHeight.should.eql(100); } if (i === 1) { info.optWidth.should.eql(300); info.optHeight.should.eql(150); } if (i === 2) { info.optWidth.should.eql(150); _results.push(info.optHeight.should.eql(75)); } else { _results.push(void 0); } } return _results; }); }); }); }); }); describe("instance", function() { var dropzone, element, requests; element = null; dropzone = null; requests = null; beforeEach(function() { requests = []; xhr.onCreate = function(xhr) { return requests.push(xhr); }; element = Dropzone.createElement("<div></div>"); document.body.appendChild(element); return dropzone = new Dropzone(element, { maxFilesize: 4, maxFiles: 100, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: function() {} }); }); afterEach(function() { document.body.removeChild(element); dropzone.destroy(); return xhr.restore(); }); describe(".accept()", function() { it("should pass if the filesize is OK", function() { return dropzone.accept({ size: 2 * 1024 * 1024, type: "audio/mp3" }, function(err) { return expect(err).to.be.undefined; }); }); it("shouldn't pass if the filesize is too big", function() { return dropzone.accept({ size: 10 * 1024 * 1024, type: "audio/mp3" }, function(err) { return err.should.eql("File is too big (10MiB). Max filesize: 4MiB."); }); }); it("should properly accept files which mime types are listed in acceptedFiles", function() { dropzone.accept({ type: "audio/mp3" }, function(err) { return expect(err).to.be.undefined; }); dropzone.accept({ type: "image/png" }, function(err) { return expect(err).to.be.undefined; }); return dropzone.accept({ type: "audio/wav" }, function(err) { return expect(err).to.be.undefined; }); }); it("should properly reject files when the mime type isn't listed in acceptedFiles", function() { return dropzone.accept({ type: "image/jpeg" }, function(err) { return err.should.eql("You can't upload files of this type."); }); }); it("should fail if maxFiles has been exceeded and call the event maxfilesexceeded", function() { var called, file; sinon.stub(dropzone, "getAcceptedFiles"); file = { type: "audio/mp3" }; dropzone.getAcceptedFiles.returns({ length: 99 }); dropzone.options.dictMaxFilesExceeded = "You can only upload {{maxFiles}} files."; called = false; dropzone.on("maxfilesexceeded", function(lfile) { lfile.should.equal(file); return called = true; }); dropzone.accept(file, function(err) { return expect(err).to.be.undefined; }); called.should.not.be.ok; dropzone.getAcceptedFiles.returns({ length: 100 }); dropzone.accept(file, function(err) { return expect(err).to.equal("You can only upload 100 files."); }); called.should.be.ok; return dropzone.getAcceptedFiles.restore(); }); return it("should properly handle if maxFiles is 0", function() { var called, file; file = { type: "audio/mp3" }; dropzone.options.maxFiles = 0; called = false; dropzone.on("maxfilesexceeded", function(lfile) { lfile.should.equal(file); return called = true; }); dropzone.accept(file, function(err) { return expect(err).to.equal("You can not upload any more files."); }); return called.should.be.ok; }); }); describe(".removeFile()", function() { return it("should abort uploading if file is currently being uploaded", function(done) { var mockFile; mockFile = getMockFile(); dropzone.uploadFile = function(file) {}; dropzone.accept = function(file, done) { return done(); }; sinon.stub(dropzone, "cancelUpload"); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.equal(Dropzone.UPLOADING); dropzone.getUploadingFiles()[0].should.equal(mockFile); dropzone.cancelUpload.callCount.should.equal(0); dropzone.removeFile(mockFile); dropzone.cancelUpload.callCount.should.equal(1); return done(); }, 10); }); }); describe(".cancelUpload()", function() { it("should properly cancel upload if file currently uploading", function(done) { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.equal(Dropzone.UPLOADING); dropzone.getUploadingFiles()[0].should.equal(mockFile); dropzone.cancelUpload(mockFile); mockFile.status.should.equal(Dropzone.CANCELED); dropzone.getUploadingFiles().length.should.equal(0); dropzone.getQueuedFiles().length.should.equal(0); return done(); }, 10); }); it("should properly cancel the upload if file is not yet uploading", function() { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 0; dropzone.addFile(mockFile); mockFile.status.should.equal(Dropzone.QUEUED); dropzone.getQueuedFiles()[0].should.equal(mockFile); dropzone.cancelUpload(mockFile); mockFile.status.should.equal(Dropzone.CANCELED); dropzone.getQueuedFiles().length.should.equal(0); return dropzone.getUploadingFiles().length.should.equal(0); }); it("should call processQueue()", function(done) { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 0; sinon.spy(dropzone, "processQueue"); dropzone.addFile(mockFile); return setTimeout(function() { dropzone.processQueue.callCount.should.equal(1); dropzone.cancelUpload(mockFile); dropzone.processQueue.callCount.should.equal(2); return done(); }, 10); }); return it("should properly cancel all files with the same XHR if uploadMultiple is true", function(done) { var mock1, mock2, mock3; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.uploadMultiple = true; dropzone.options.parallelUploads = 3; sinon.spy(dropzone, "processFiles"); dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); return setTimeout(function() { var _ref; dropzone.processFiles.callCount.should.equal(1); sinon.spy(mock1.xhr, "abort"); dropzone.cancelUpload(mock1); expect((mock1.xhr === (_ref = mock2.xhr) && _ref === mock3.xhr)).to.be.ok; mock1.status.should.equal(Dropzone.CANCELED); mock2.status.should.equal(Dropzone.CANCELED); mock3.status.should.equal(Dropzone.CANCELED); mock1.xhr.abort.callCount.should.equal(1); return done(); }, 10); }); }); describe(".disable()", function() { return it("should properly cancel all pending uploads", function(done) { dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 1; dropzone.addFile(getMockFile()); dropzone.addFile(getMockFile()); return setTimeout(function() { dropzone.getUploadingFiles().length.should.equal(1); dropzone.getQueuedFiles().length.should.equal(1); dropzone.files.length.should.equal(2); sinon.spy(requests[0], "abort"); requests[0].abort.callCount.should.equal(0); dropzone.disable(); requests[0].abort.callCount.should.equal(1); dropzone.getUploadingFiles().length.should.equal(0); dropzone.getQueuedFiles().length.should.equal(0); dropzone.files.length.should.equal(2); dropzone.files[0].status.should.equal(Dropzone.CANCELED); dropzone.files[1].status.should.equal(Dropzone.CANCELED); return done(); }, 10); }); }); describe(".destroy()", function() { it("should properly cancel all pending uploads and remove all file references", function(done) { dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 1; dropzone.addFile(getMockFile()); dropzone.addFile(getMockFile()); return setTimeout(function() { dropzone.getUploadingFiles().length.should.equal(1); dropzone.getQueuedFiles().length.should.equal(1); dropzone.files.length.should.equal(2); sinon.spy(dropzone, "disable"); dropzone.destroy(); dropzone.disable.callCount.should.equal(1); element.should.not.have.property("dropzone"); return done(); }, 10); }); it("should be able to create instance of dropzone on the same element after destroy", function() { dropzone.destroy(); return (function() { return new Dropzone(element, { maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: function() {} }); }).should.not["throw"](Error); }); return it("should remove itself from Dropzone.instances", function() { (Dropzone.instances.indexOf(dropzone) !== -1).should.be.ok; dropzone.destroy(); return (Dropzone.instances.indexOf(dropzone) === -1).should.be.ok; }); }); describe(".filesize()", function() { it("should convert to KiloBytes, etc..", function() { dropzone.options.filesizeBase.should.eql(1000); dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>2</strong> MB"); dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2.1</strong> MB"); dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql("<strong>2</strong> GB"); dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql("<strong>2.1</strong> GB"); dropzone.filesize(2.5111 * 1000 * 1000 * 1000).should.eql("<strong>2.5</strong> GB"); dropzone.filesize(1.1 * 1000).should.eql("<strong>1.1</strong> KB"); return dropzone.filesize(999 * 1000).should.eql("<strong>1</strong> MB"); }); return it("should convert to KibiBytes, etc.. when the filesizeBase is changed to 1024", function() { dropzone.options.filesizeBase = 1024; dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2</strong> MB"); return dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>1.9</strong> MB"); }); }); describe("._updateMaxFilesReachedClass()", function() { it("should properly add the dz-max-files-reached class", function() { dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone.options.maxFiles = 10; dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; dropzone._updateMaxFilesReachedClass(); return dropzone.element.classList.contains("dz-max-files-reached").should.be.ok; }); it("should fire the 'maxfilesreached' event when appropriate", function() { var spy; spy = sinon.spy(); dropzone.on("maxfilesreached", function() { return spy(); }); dropzone.getAcceptedFiles = function() { return { length: 9 }; }; dropzone.options.maxFiles = 10; dropzone._updateMaxFilesReachedClass(); spy.should.not.have.been.called; dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone._updateMaxFilesReachedClass(); spy.should.have.been.called; dropzone.getAcceptedFiles = function() { return { length: 11 }; }; dropzone._updateMaxFilesReachedClass(); return spy.should.have.been.calledOnce; }); return it("should properly remove the dz-max-files-reached class", function() { dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone.options.maxFiles = 10; dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; dropzone._updateMaxFilesReachedClass(); dropzone.element.classList.contains("dz-max-files-reached").should.be.ok; dropzone.getAcceptedFiles = function() { return { length: 9 }; }; dropzone._updateMaxFilesReachedClass(); return dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; }); }); return describe("events", function() { return describe("progress updates", function() { return it("should properly emit a totaluploadprogress event", function(done) { var totalProgressExpectation, _called; dropzone.files = [ { size: 1990, accepted: true, status: Dropzone.UPLOADING, upload: { progress: 20, total: 2000, bytesSent: 400 } }, { size: 1990, accepted: true, status: Dropzone.UPLOADING, upload: { progress: 10, total: 2000, bytesSent: 200 } } ]; _called = 0; dropzone.on("totaluploadprogress", function(progress) { progress.should.equal(totalProgressExpectation); if (++_called === 3) { return done(); } }); totalProgressExpectation = 15; dropzone.emit("uploadprogress", {}); totalProgressExpectation = 97.5; dropzone.files[0].upload.bytesSent = 2000; dropzone.files[1].upload.bytesSent = 1900; dropzone.emit("uploadprogress", {}); totalProgressExpectation = 100; dropzone.files[0].upload.bytesSent = 2000; dropzone.files[1].upload.bytesSent = 2000; dropzone.emit("uploadprogress", {}); dropzone.files[0].status = Dropzone.CANCELED; return dropzone.files[1].status = Dropzone.CANCELED; }); }); }); }); describe("helper function", function() { var dropzone, element; element = null; dropzone = null; beforeEach(function() { element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { url: "url" }); }); describe("getExistingFallback()", function() { it("should return undefined if no fallback", function() { return expect(dropzone.getExistingFallback()).to.equal(void 0); }); it("should only return the fallback element if it contains exactly fallback", function() { element.appendChild(Dropzone.createElement("<form class=\"fallbacks\"></form>")); element.appendChild(Dropzone.createElement("<form class=\"sfallback\"></form>")); return expect(dropzone.getExistingFallback()).to.equal(void 0); }); it("should return divs as fallback", function() { var fallback; fallback = Dropzone.createElement("<form class=\" abc fallback test \"></form>"); element.appendChild(fallback); return fallback.should.equal(dropzone.getExistingFallback()); }); return it("should return forms as fallback", function() { var fallback; fallback = Dropzone.createElement("<div class=\" abc fallback test \"></div>"); element.appendChild(fallback); return fallback.should.equal(dropzone.getExistingFallback()); }); }); describe("getFallbackForm()", function() { it("should use the paramName without [0] if uploadMultiple is false", function() { var fallback, fileInput; dropzone.options.uploadMultiple = false; dropzone.options.paramName = "myFile"; fallback = dropzone.getFallbackForm(); fileInput = fallback.querySelector("input[type=file]"); return fileInput.name.should.equal("myFile"); }); return it("should properly add [0] to the file name if uploadMultiple is true", function() { var fallback, fileInput; dropzone.options.uploadMultiple = true; dropzone.options.paramName = "myFile"; fallback = dropzone.getFallbackForm(); fileInput = fallback.querySelector("input[type=file]"); return fileInput.name.should.equal("myFile[0]"); }); }); describe("getAcceptedFiles() / getRejectedFiles()", function() { var mock1, mock2, mock3, mock4; mock1 = mock2 = mock3 = mock4 = null; beforeEach(function() { mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, done) { if (file === mock1 || file === mock3) { return done(); } else { return done("error"); } }; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); return dropzone.addFile(mock4); }); it("getAcceptedFiles() should only return accepted files", function() { return dropzone.getAcceptedFiles().should.eql([mock1, mock3]); }); return it("getRejectedFiles() should only return rejected files", function() { return dropzone.getRejectedFiles().should.eql([mock2, mock4]); }); }); describe("getQueuedFiles()", function() { return it("should return all files with the status Dropzone.QUEUED", function() { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, done) { return file.done = done; }; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getQueuedFiles().should.eql([]); mock1.done(); mock3.done(); dropzone.getQueuedFiles().should.eql([mock1, mock3]); mock1.status.should.equal(Dropzone.QUEUED); mock3.status.should.equal(Dropzone.QUEUED); mock2.status.should.equal(Dropzone.ADDED); return mock4.status.should.equal(Dropzone.ADDED); }); }); describe("getUploadingFiles()", function() { return it("should return all files with the status Dropzone.UPLOADING", function(done) { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getUploadingFiles().should.eql([]); mock1.done(); mock3.done(); return setTimeout((function() { dropzone.getUploadingFiles().should.eql([mock1, mock3]); mock1.status.should.equal(Dropzone.UPLOADING); mock3.status.should.equal(Dropzone.UPLOADING); mock2.status.should.equal(Dropzone.ADDED); mock4.status.should.equal(Dropzone.ADDED); return done(); }), 10); }); }); describe("getActiveFiles()", function() { return it("should return all files with the status Dropzone.UPLOADING or Dropzone.QUEUED", function(done) { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.options.parallelUploads = 2; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getActiveFiles().should.eql([]); mock1.done(); mock3.done(); mock4.done(); return setTimeout((function() { dropzone.getActiveFiles().should.eql([mock1, mock3, mock4]); mock1.status.should.equal(Dropzone.UPLOADING); mock3.status.should.equal(Dropzone.UPLOADING); mock2.status.should.equal(Dropzone.ADDED); mock4.status.should.equal(Dropzone.QUEUED); return done(); }), 10); }); }); return describe("getFilesWithStatus()", function() { return it("should return all files with provided status", function() { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock1, mock2, mock3, mock4]); mock1.status = Dropzone.UPLOADING; mock3.status = Dropzone.QUEUED; mock4.status = Dropzone.QUEUED; dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock2]); dropzone.getFilesWithStatus(Dropzone.UPLOADING).should.eql([mock1]); return dropzone.getFilesWithStatus(Dropzone.QUEUED).should.eql([mock3, mock4]); }); }); }); return describe("file handling", function() { var dropzone, mockFile; mockFile = null; dropzone = null; beforeEach(function() { var element; mockFile = getMockFile(); element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { url: "/the/url" }); }); afterEach(function() { return dropzone.destroy(); }); describe("addFile()", function() { it("should properly set the status of the file", function() { var doneFunction; doneFunction = null; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); mockFile.status.should.eql(Dropzone.QUEUED); mockFile = getMockFile(); dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction("error"); return mockFile.status.should.eql(Dropzone.ERROR); }); it("should properly set the status of the file if autoProcessQueue is false and not call processQueue", function(done) { var doneFunction; doneFunction = null; dropzone.options.autoProcessQueue = false; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); sinon.stub(dropzone, "processQueue"); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); mockFile.status.should.eql(Dropzone.QUEUED); dropzone.processQueue.callCount.should.equal(0); return setTimeout((function() { dropzone.processQueue.callCount.should.equal(0); return done(); }), 10); }); it("should not add the file to the queue if autoQueue is false", function() { var doneFunction; doneFunction = null; dropzone.options.autoQueue = false; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); return mockFile.status.should.eql(Dropzone.ADDED); }); it("should create a remove link if configured to do so", function() { dropzone.options.addRemoveLinks = true; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; sinon.stub(dropzone, "processQueue"); dropzone.addFile(mockFile); return dropzone.files[0].previewElement.querySelector("a[data-dz-remove].dz-remove").should.be.ok; }); it("should attach an event handler to data-dz-remove links", function() { var event, file, removeLink1, removeLink2; dropzone.options.previewTemplate = "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span>✘</span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n <a class=\"link1\" data-dz-remove></a>\n <a class=\"link2\" data-dz-remove></a>\n</div>"; sinon.stub(dropzone, "processQueue"); dropzone.addFile(mockFile); file = dropzone.files[0]; removeLink1 = file.previewElement.querySelector("a[data-dz-remove].link1"); removeLink2 = file.previewElement.querySelector("a[data-dz-remove].link2"); sinon.stub(dropzone, "removeFile"); event = document.createEvent("HTMLEvents"); event.initEvent("click", true, true); removeLink1.dispatchEvent(event); dropzone.removeFile.callCount.should.eql(1); event = document.createEvent("HTMLEvents"); event.initEvent("click", true, true); removeLink2.dispatchEvent(event); return dropzone.removeFile.callCount.should.eql(2); }); return describe("thumbnails", function() { it("should properly queue the thumbnail creation", function(done) { var ct_callback, ct_file, doneFunction, mock1, mock2, mock3; doneFunction = null; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock1.type = "image/jpg"; mock2.type = "image/jpg"; mock3.type = "image/jpg"; dropzone.on("thumbnail", function() { return console.log("HII"); }); ct_file = ct_callback = null; dropzone.createThumbnail = function(file, callback) { ct_file = file; return ct_callback = callback; }; sinon.spy(dropzone, "createThumbnail"); dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.files.length.should.eql(3); return setTimeout((function() { dropzone.createThumbnail.callCount.should.eql(1); mock1.should.equal(ct_file); ct_callback(); dropzone.createThumbnail.callCount.should.eql(2); mock2.should.equal(ct_file); ct_callback(); dropzone.createThumbnail.callCount.should.eql(3); mock3.should.equal(ct_file); return done(); }), 10); }); return describe("when file is SVG", function() { return it("should use the SVG image itself", function(done) { var blob, createBlob; createBlob = function(data, type) { var BlobBuilder, builder, e; try { return new Blob([data], { type: type }); } catch (_error) { e = _error; BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; builder = new BlobBuilder(); builder.append(data.buffer || data); return builder.getBlob(type); } }; blob = createBlob('foo', 'image/svg+xml'); dropzone.on("thumbnail", function(file, dataURI) { var fileReader; file.should.equal(blob); fileReader = new FileReader; fileReader.onload = function() { fileReader.result.should.equal(dataURI); return done(); }; return fileReader.readAsDataURL(file); }); return dropzone.createThumbnail(blob); }); }); }); }); describe("enqueueFile()", function() { it("should be wrapped by enqueueFiles()", function() { var mock1, mock2, mock3; sinon.stub(dropzone, "enqueueFile"); mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); dropzone.enqueueFiles([mock1, mock2, mock3]); dropzone.enqueueFile.callCount.should.equal(3); dropzone.enqueueFile.args[0][0].should.equal(mock1); dropzone.enqueueFile.args[1][0].should.equal(mock2); return dropzone.enqueueFile.args[2][0].should.equal(mock3); }); it("should fail if the file has already been processed", function() { mockFile.status = Dropzone.ERROR; expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); mockFile.status = Dropzone.COMPLETE; expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); mockFile.status = Dropzone.UPLOADING; return expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); }); return it("should set the status to QUEUED and call processQueue asynchronously if everything's ok", function(done) { mockFile.status = Dropzone.ADDED; sinon.stub(dropzone, "processQueue"); dropzone.processQueue.callCount.should.equal(0); dropzone.enqueueFile(mockFile); mockFile.status.should.equal(Dropzone.QUEUED); dropzone.processQueue.callCount.should.equal(0); return setTimeout(function() { dropzone.processQueue.callCount.should.equal(1); return done(); }, 10); }); }); describe("uploadFiles()", function() { var requests; requests = null; beforeEach(function() { requests = []; return xhr.onCreate = function(xhr) { return requests.push(xhr); }; }); afterEach(function() { return xhr.restore(); }); it("should be wrapped by uploadFile()", function() { sinon.stub(dropzone, "uploadFiles"); dropzone.uploadFile(mockFile); dropzone.uploadFiles.callCount.should.equal(1); return dropzone.uploadFiles.calledWith([mockFile]).should.be.ok; }); it("should use url options if strings", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { expect(requests.length).to.equal(1); expect(requests[0].url).to.equal(dropzone.options.url); expect(requests[0].method).to.equal(dropzone.options.method); return done(); }, 10); }); it("should call url options if functions", function(done) { var method, url; method = "PUT"; url = "/custom/upload/url"; dropzone.options.method = sinon.stub().returns(method); dropzone.options.url = sinon.stub().returns(url); dropzone.addFile(mockFile); return setTimeout(function() { dropzone.options.method.callCount.should.equal(1); dropzone.options.url.callCount.should.equal(1); sinon.assert.calledWith(dropzone.options.method, [mockFile]); sinon.assert.calledWith(dropzone.options.url, [mockFile]); expect(requests.length).to.equal(1); expect(requests[0].url).to.equal(url); expect(requests[0].method).to.equal(method); return done(); }, 10); }); it("should ignore the onreadystate callback if readyState != 4", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].status = 200; requests[0].readyState = 3; requests[0].onload(); mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].readyState = 4; requests[0].onload(); mockFile.status.should.eql(Dropzone.SUCCESS); return done(); }, 10); }); it("should emit error and errormultiple when response was not OK", function(done) { var complete, completemultiple, error, errormultiple; dropzone.options.uploadMultiple = true; error = false; errormultiple = false; complete = false; completemultiple = false; dropzone.on("error", function() { return error = true; }); dropzone.on("errormultiple", function() { return errormultiple = true; }); dropzone.on("complete", function() { return complete = true; }); dropzone.on("completemultiple", function() { return completemultiple = true; }); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].status = 400; requests[0].readyState = 4; requests[0].onload(); expect((((true === error && error === errormultiple) && errormultiple === complete) && complete === completemultiple)).to.be.ok; return done(); }, 10); }); it("should include hidden files in the form and unchecked checkboxes and radiobuttons should be excluded", function(done) { var element, formData, mock1; element = Dropzone.createElement("<form action=\"/the/url\">\n <input type=\"hidden\" name=\"test\" value=\"hidden\" />\n <input type=\"checkbox\" name=\"unchecked\" value=\"1\" />\n <input type=\"checkbox\" name=\"checked\" value=\"value1\" checked=\"checked\" />\n <input type=\"radio\" value=\"radiovalue1\" name=\"radio1\" />\n <input type=\"radio\" value=\"radiovalue2\" name=\"radio1\" checked=\"checked\" />\n <select name=\"select\"><option value=\"1\">1</option><option value=\"2\" selected>2</option></select>\n</form>"); dropzone = new Dropzone(element, { url: "/the/url" }); formData = null; dropzone.on("sending", function(file, xhr, tformData) { formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); dropzone.addFile(mock1); return setTimeout(function() { formData.append.callCount.should.equal(5); formData.append.args[0][0].should.eql("test"); formData.append.args[0][1].should.eql("hidden"); formData.append.args[1][0].should.eql("checked"); formData.append.args[1][1].should.eql("value1"); formData.append.args[2][0].should.eql("radio1"); formData.append.args[2][1].should.eql("radiovalue2"); formData.append.args[3][0].should.eql("select"); formData.append.args[3][1].should.eql("2"); formData.append.args[4][0].should.eql("file"); formData.append.args[4][1].should.equal(mock1); return done(); }, 10); }); it("should all values of a select that has the multiple attribute", function(done) { var element, formData, mock1; element = Dropzone.createElement("<form action=\"/the/url\">\n <select name=\"select\" multiple>\n <option value=\"value1\">1</option>\n <option value=\"value2\" selected>2</option>\n <option value=\"value3\">3</option>\n <option value=\"value4\" selected>4</option>\n </select>\n</form>"); dropzone = new Dropzone(element, { url: "/the/url" }); formData = null; dropzone.on("sending", function(file, xhr, tformData) { formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); dropzone.addFile(mock1); return setTimeout(function() { formData.append.callCount.should.equal(3); formData.append.args[0][0].should.eql("select"); formData.append.args[0][1].should.eql("value2"); formData.append.args[1][0].should.eql("select"); formData.append.args[1][1].should.eql("value4"); formData.append.args[2][0].should.eql("file"); formData.append.args[2][1].should.equal(mock1); return done(); }, 10); }); describe("settings()", function() { it("should correctly set `withCredentials` on the xhr object", function() { dropzone.uploadFile(mockFile); requests.length.should.eql(1); requests[0].withCredentials.should.eql(false); dropzone.options.withCredentials = true; dropzone.uploadFile(mockFile); requests.length.should.eql(2); return requests[1].withCredentials.should.eql(true); }); it("should correctly set headers on the xhr object", function() { dropzone.options.headers = { "Foo-Header": "foobar" }; dropzone.uploadFile(mockFile); requests[0].requestHeaders["Foo-Header"].should.eql('foobar'); return (requests[0].requestHeaders["Accept"] === void 0).should.be["false"]; }); it("should correctly override headers on the xhr object", function() { dropzone.options.overrideDefaultHeaders = true; dropzone.options.headers = { "Foo-Header": "foobar" }; dropzone.uploadFile(mockFile); return (requests[0].requestHeaders["Accept"] === void 0).should.be["true"]; }); it("should properly use the paramName without [n] as file upload if uploadMultiple is false", function(done) { var formData, mock1, mock2, sendingCount; dropzone.options.uploadMultiple = false; dropzone.options.paramName = "myName"; formData = []; sendingCount = 0; dropzone.on("sending", function(files, xhr, tformData) { sendingCount++; formData.push(tformData); return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); mock2 = getMockFile(); dropzone.addFile(mock1); dropzone.addFile(mock2); return setTimeout(function() { sendingCount.should.equal(2); formData.length.should.equal(2); formData[0].append.callCount.should.equal(1); formData[1].append.callCount.should.equal(1); formData[0].append.args[0][0].should.eql("myName"); formData[0].append.args[0][0].should.eql("myName"); return done(); }, 10); }); return it("should properly use the paramName with [n] as file upload if uploadMultiple is true", function(done) { var formData, mock1, mock2, sendingCount, sendingMultipleCount; dropzone.options.uploadMultiple = true; dropzone.options.paramName = "myName"; formData = null; sendingMultipleCount = 0; sendingCount = 0; dropzone.on("sending", function(file, xhr, tformData) { return sendingCount++; }); dropzone.on("sendingmultiple", function(files, xhr, tformData) { sendingMultipleCount++; formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); mock2 = getMockFile(); dropzone.addFile(mock1); dropzone.addFile(mock2); return setTimeout(function() { sendingCount.should.equal(2); sendingMultipleCount.should.equal(1); dropzone.uploadFiles([mock1, mock2]); formData.append.callCount.should.equal(2); formData.append.args[0][0].should.eql("myName[0]"); formData.append.args[1][0].should.eql("myName[1]"); return done(); }, 10); }); }); return describe("should properly set status of file", function() { return it("should correctly set `withCredentials` on the xhr object", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests.length.should.equal(1); requests[0].status = 400; requests[0].readyState = 4; requests[0].onload(); mockFile.status.should.eql(Dropzone.ERROR); mockFile = getMockFile(); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests.length.should.equal(2); requests[1].status = 200; requests[1].readyState = 4; requests[1].onload(); mockFile.status.should.eql(Dropzone.SUCCESS); return done(); }, 10); }, 10); }); }); }); return describe("complete file", function() { return it("should properly emit the queuecomplete event when the complete queue is finished", function(done) { var completedFiles, mock1, mock2, mock3; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock1.status = Dropzone.ADDED; mock2.status = Dropzone.ADDED; mock3.status = Dropzone.ADDED; mock1.name = "mock1"; mock2.name = "mock2"; mock3.name = "mock3"; dropzone.uploadFiles = function(files) { return setTimeout(((function(_this) { return function() { return _this._finished(files, null, null); }; })(this)), 1); }; completedFiles = 0; dropzone.on("complete", function(file) { return completedFiles++; }); dropzone.on("queuecomplete", function() { completedFiles.should.equal(3); return done(); }); dropzone.addFile(mock1); dropzone.addFile(mock2); return dropzone.addFile(mock3); }); }); }); }); }).call(this);
webfatorial/dropzone
test/test.js
JavaScript
mit
82,314
/** * generated by Xtext */ package dk.itu.smdp.group2.ui.outline; import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider; /** * Customization of the default outline structure. * * see http://www.eclipse.org/Xtext/documentation.html#outline */ @SuppressWarnings("all") public class QuestionaireOutlineTreeProvider extends DefaultOutlineTreeProvider { }
rasmusgreve/questionaire
dk.itu.smdp.group2.questionaire.ui/xtend-gen/dk/itu/smdp/group2/ui/outline/QuestionaireOutlineTreeProvider.java
Java
mit
382
<?php /* * ghz.me url shortener * when a long url hz. * * (c) 2014 Sam Thompson <contact@samt.us> * License: MIT */ define('ROOT_PATH', __DIR__ . '/'); require ROOT_PATH . 'loader.php'; $app = new Ghz\App(); // Handle our two cases: // - Redirect (when requestiong anything except BASEPATH) // - Save URL when posted here. $app->doRedirect(); $app->savePostedUrl(); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>GHz url shortener</title> <link rel="stylesheet" href="_assets/style.css"> <?php if (defined('GA_TRACKING')) : ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '<?php echo GA_TRACKING; ?>', 'auto'); ga('send', 'pageview'); </script> <?php endif; ?> </head> <body> <div class="main"> <h1> <a href="/">Ghz</a> </h1> <p class="subhead">url shortener</p> <form action="" method="post"> <div class="error<?php if ($app->isFailure()) : ?> visible<?php endif; ?>"> please enter a valid url </div> <div class="success<?php if ($app->isSuccess()) : ?> visible<?php endif; ?>"> created! </div> <div> <input placeholder="paste or enter a url and press enter" name="url" type="text" value="<?php echo $app->getGeneratedUrl(); ?>"> </div> </form> </div> <div class="bottom-left"> &copy; <?php echo date('Y'); ?> Ghz.me </div> <div class="bottom-right"> &nbsp; </div> <!-- fork me banner --> <a href="https://github.com/samt/ghz"> <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"> </a> <script type="text/javascript" src="_assets/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="_assets/main.js"></script> </body> </html>
samt/ghz
index.php
PHP
mit
2,503
namespace LadderLogic.Controller.State { using Surface; public class CursorState : State { public CursorState () : base(StateType.CursorState) { } #region implemented abstract members of State public override bool Handle (State previous, Segment prevSegment, Segment newSegment, bool left) { base.Handle (previous, prevSegment, newSegment, left); return true; } #endregion } }
cpipero/ArduinoLadder
Controller/State/CursorState.cs
C#
mit
411
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_12_01 module Models # # A load balancer probe. # class Probe < SubResource include MsRestAzure # @return [Array<SubResource>] The load balancer rules that use this # probe. attr_accessor :load_balancing_rules # @return [ProbeProtocol] The protocol of the end point. If 'Tcp' is # specified, a received ACK is required for the probe to be successful. # If 'Http' or 'Https' is specified, a 200 OK response from the specifies # URI is required for the probe to be successful. Possible values # include: 'Http', 'Tcp', 'Https' attr_accessor :protocol # @return [Integer] The port for communicating the probe. Possible values # range from 1 to 65535, inclusive. attr_accessor :port # @return [Integer] The interval, in seconds, for how frequently to probe # the endpoint for health status. Typically, the interval is slightly # less than half the allocated timeout period (in seconds) which allows # two full probes before taking the instance out of rotation. The default # value is 15, the minimum value is 5. attr_accessor :interval_in_seconds # @return [Integer] The number of probes where if no response, will # result in stopping further traffic from being delivered to the # endpoint. This values allows endpoints to be taken out of rotation # faster or slower than the typical times used in Azure. attr_accessor :number_of_probes # @return [String] The URI used for requesting health status from the VM. # Path is required if a protocol is set to http. Otherwise, it is not # allowed. There is no default value. attr_accessor :request_path # @return [ProvisioningState] The provisioning state of the probe # resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', # 'Failed' attr_accessor :provisioning_state # @return [String] The name of the resource that is unique within the set # of probes used by the load balancer. This name can be used to access # the resource. attr_accessor :name # @return [String] A unique read-only string that changes whenever the # resource is updated. attr_accessor :etag # @return [String] Type of the resource. attr_accessor :type # # Mapper for Probe class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Probe', type: { name: 'Composite', class_name: 'Probe', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, load_balancing_rules: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.loadBalancingRules', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SubResourceElementType', type: { name: 'Composite', class_name: 'SubResource' } } } }, protocol: { client_side_validation: true, required: true, serialized_name: 'properties.protocol', type: { name: 'String' } }, port: { client_side_validation: true, required: true, serialized_name: 'properties.port', type: { name: 'Number' } }, interval_in_seconds: { client_side_validation: true, required: false, serialized_name: 'properties.intervalInSeconds', type: { name: 'Number' } }, number_of_probes: { client_side_validation: true, required: false, serialized_name: 'properties.numberOfProbes', type: { name: 'Number' } }, request_path: { client_side_validation: true, required: false, serialized_name: 'properties.requestPath', type: { name: 'String' } }, provisioning_state: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.provisioningState', type: { name: 'String' } }, name: { client_side_validation: true, required: false, serialized_name: 'name', type: { name: 'String' } }, etag: { client_side_validation: true, required: false, read_only: true, serialized_name: 'etag', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2019-12-01/generated/azure_mgmt_network/models/probe.rb
Ruby
mit
6,258
<?php namespace Juice\UploadBundle\Form\Type; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class BaseFileType extends AbstractUploadType { public function buildView(FormView $view, FormInterface $form, array $options) { $this->addVars($view, $options); } public function getName() { return 'juice_upload_file_type'; } }
dakkor71/UploadBundle
Form/Type/BaseFileType.php
PHP
mit
462
<?php namespace TFE\LibrairieBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class AccompagnementModifierType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) {} /** * @return string */ public function getName() { return 'tfe_librairiebundle_accompagnement_modifier'; } /** * @return AccompagnementType */ public function getParent() { return new AccompagnementType(); } }
durandludovic/tfe
src/TFE/LibrairieBundle/Form/AccompagnementModifierType.php
PHP
mit
647
using Dufry.Comissoes.Domain.Validation; namespace Dufry.Comissoes.Domain.Interfaces.Validation { public interface IValidation<in TEntity> { ValidationResult Valid(TEntity entity); } }
robertohermes/Comissoes
Dufry.Comissoes.Domain/Interfaces/Validation/IValidation.cs
C#
mit
208
import {HttpClient} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Observable, ReplaySubject, throwError} from 'rxjs'; import {map, tap, switchMap} from 'rxjs/operators'; import {SocketService} from './sockets'; import {StorageService} from './storage'; @Injectable({ providedIn: 'root' }) export class AuthService { private session: string; private userInfo: any; private authEvents: ReplaySubject<{User: any, Session: string}>; constructor( private _http: HttpClient, private _storage: StorageService, private _sockets: SocketService, ) { this.authEvents = new ReplaySubject<{User: any, Session: string}>(1); } private nuke() { this._storage.clear(); this.session = undefined; this.userInfo = undefined; this._sockets.leave(); } getSession() { return this.session; } getUser() { return this.userInfo; } hasAccess(): boolean { return !!this.userInfo; } observe(): Observable<{User: any, Session: string}> { return this.authEvents; } identify() { this._http.get<{Data: any}>(`/api/auth/`) .pipe( map(res => res.Data) ) .subscribe( data => { this.session = data.Session.Key; this.userInfo = data.User; this._sockets.join(data.Session.Key); this.authEvents.next({User: data.User, Session: data.Session.Key}); }, err => console.error(err) ); } logIn(creds): Observable<any> { if (!creds || !creds.Username || !creds.Password) { return throwError('Need login creds'); } return this._http.post<{Data: any}>('/api/login', creds) .pipe( map(res => res.Data), tap(data => { this.session = data.Session; this.userInfo = data.User; this._sockets.join(data.Session); this.authEvents.next(data); }) ); } signUp(creds): Observable<any> { if (!creds || !creds.Username || !creds.Email || !creds.Password) { return throwError('Need signup creds'); } return this._http.post('/api/signup', creds, {responseType: 'text' as 'text'}) .pipe( switchMap(_ => this.logIn(creds)) ); } expireSocket() { this.userInfo = null; this.session = null; this.authEvents.next(null); } logOut(): Observable<any> { return this._http.post('/api/logOut', null) .pipe( tap( res => this.nuke(), err => this.nuke(), () => this.authEvents.next(null) ) ); } }
swimmadude66/YTRadio
src/client/services/auth.ts
TypeScript
mit
2,997
package com.lightspeedhq.ecom; import com.lightspeedhq.ecom.domain.LightspeedEComError; import feign.FeignException; import lombok.Getter; /** * * @author stevensnoeijen */ public class LightspeedEComErrorException extends FeignException { @Getter private LightspeedEComError error; public LightspeedEComErrorException(String message, LightspeedEComError error) { super(message); this.error = error; } @Override public String toString() { return error.toString(); } }
Falkplan/lightspeedecom-api
lightspeedecom-api/src/main/java/com/lightspeedhq/ecom/LightspeedEComErrorException.java
Java
mit
528
<?xml version="1.0" ?><!DOCTYPE TS><TS language="eu_ES" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About POPCoin</source> <translation>POPCoin-i buruz</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;POPCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;POPCoin&lt;/b&gt; bertsioa</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>POPCoin</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Helbide-liburua</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Klik bikoitza helbidea edo etiketa editatzeko</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Sortu helbide berria</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiatu hautatutako helbidea sistemaren arbelera</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your POPCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Erakutsi &amp;QR kodea</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Ezabatu</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your POPCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Esportatu Helbide-liburuaren datuak</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Komaz bereizitako artxiboa (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Errorea esportatzean</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ezin idatzi %1 artxiboan.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiketa</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Helbidea</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(etiketarik ez)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Sartu pasahitza</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Pasahitz berria</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Errepikatu pasahitz berria</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Sartu zorrorako pasahitz berria.&lt;br/&gt; Mesedez erabili &lt;b&gt;gutxienez ausazko 10 karaktere&lt;/b&gt;, edo &lt;b&gt;gutxienez zortzi hitz&lt;/b&gt; pasahitza osatzeko.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Enkriptatu zorroa</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Eragiketa honek zorroaren pasahitza behar du zorroa desblokeatzeko.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desblokeatu zorroa</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Eragiketa honek zure zorroaren pasahitza behar du, zorroa desenkriptatzeko.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desenkriptatu zorroa</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Aldatu pasahitza</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Sartu zorroaren pasahitz zaharra eta berria.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Berretsi zorroaren enkriptazioa</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR POPCOIN&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Zorroa enkriptatuta</translation> </message> <message> <location line="-56"/> <source>POPCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your popcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Zorroaren enkriptazioak huts egin du</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Zorroaren enkriptazioak huts egin du barne-errore baten ondorioz. Zure zorroa ez da enkriptatu.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Eman dituzun pasahitzak ez datoz bat.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Zorroaren desblokeoak huts egin du</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Zorroa desenkriptatzeko sartutako pasahitza okerra da.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Zorroaren desenkriptazioak huts egin du</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sarearekin sinkronizatzen...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Gainbegiratu</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Ikusi zorroaren begirada orokorra</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakzioak</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Ikusi transakzioen historia</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editatu gordetako helbide eta etiketen zerrenda</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Erakutsi ordainketak jasotzeko helbideen zerrenda</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Irten</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Irten aplikaziotik</translation> </message> <message> <location line="+4"/> <source>Show information about POPCoin</source> <translation>Erakutsi POPCoin-i buruzko informazioa</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Qt-ari buruz</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Erakutsi POPCoin-i buruzko informazioa</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Aukerak...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Aldatu zorroa enkriptatzeko erabilitako pasahitza</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your POPCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified POPCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Artxiboa</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Ezarpenak</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Laguntza</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Fitxen tresna-barra</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>POPCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to POPCoin network</source> <translation><numerusform>Konexio aktibo %n POPCoin-en sarera</numerusform><numerusform>%n konexio aktibo POPCoin-en sarera</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Egunean</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Eguneratzen...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Bidalitako transakzioa</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Sarrerako transakzioa</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid POPCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Zorroa &lt;b&gt;enkriptatuta&lt;/b&gt; eta &lt;b&gt;desblokeatuta&lt;/b&gt; dago une honetan</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Zorroa &lt;b&gt;enkriptatuta&lt;/b&gt; eta &lt;b&gt;blokeatuta&lt;/b&gt; dago une honetan</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. POPCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editatu helbidea</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiketa</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Helbide-liburuko sarrera honekin lotutako etiketa</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Helbidea</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Helbide-liburuko sarrera honekin lotutako helbidea. Bidaltzeko helbideeta soilik alda daiteke.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Jasotzeko helbide berria</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Bidaltzeko helbide berria</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editatu jasotzeko helbidea</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editatu bidaltzeko helbidea</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Sartu berri den helbidea, &quot;%1&quot;, helbide-liburuan dago jadanik.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid POPCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Ezin desblokeatu zorroa.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Gako berriaren sorrerak huts egin du.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>POPCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Aukerak</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start POPCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start POPCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the POPCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the POPCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting POPCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show POPCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting POPCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Inprimakia</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the POPCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldoa:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Konfirmatu gabe:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Azken transakzioak&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Zure uneko saldoa</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Oraindik konfirmatu gabe daudenez, uneko saldoab kontatu gabe dagoen transakzio kopurua</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start popcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Kopurua</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>&amp;Etiketa:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mezua</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Gorde honela...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the POPCoin-Qt help message to get a list with possible POPCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>POPCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>POPCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the POPCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the POPCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Bidali txanponak</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Bidali hainbat jasotzaileri batera</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldoa:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Berretsi bidaltzeko ekintza</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; honi: %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Berretsi txanponak bidaltzea</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ziur zaude %1 bidali nahi duzula?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>eta</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Ordaintzeko kopurua 0 baino handiagoa izan behar du.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Inprimakia</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>K&amp;opurua:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Ordaindu &amp;honi:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Sartu etiketa bat helbide honetarako, eta gehitu zure helbide-liburuan</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etiketa:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Itsatsi helbidea arbeletik</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Ezabatu jasotzaile hau</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a POPCoin address (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation>Sartu Bitocin helbide bat (adb.: sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK) </translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Itsatsi helbidea arbeletik</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a POPCoin address (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation>Sartu Bitocin helbide bat (adb.: sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK) </translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter POPCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Zabalik %1 arte</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/konfirmatu gabe</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 konfirmazioak</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Kopurua</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ez da arrakastaz emititu oraindik</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>ezezaguna</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transakzioaren xehetasunak</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Panel honek transakzioaren deskribapen xehea erakusten du</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Mota</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Helbidea</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Kopurua</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Zabalik %1 arte</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 konfirmazio)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Konfirmatuta (%1 konfirmazio)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Bloke hau ez du beste inongo nodorik jaso, eta seguruenik ez da onartuko!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Sortua, baina ez onartua</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Jasoa honekin: </translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Honi bidalia: </translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Ordainketa zeure buruari</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Bildua</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transakzioaren egoera. Pasatu sagua gainetik konfirmazio kopurua ikusteko.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Transakzioa jasotako data eta ordua.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Transakzio mota.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Transakzioaren xede-helbidea.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Saldoan kendu edo gehitutako kopurua.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Denak</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Gaur</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Aste honetan</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Hil honetan</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Azken hilean</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Aurten</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Muga...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Jasota honekin: </translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Hona bidalia: </translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Zeure buruari</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Bildua</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Beste</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Sartu bilatzeko helbide edo etiketa</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Kopuru minimoa</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopiatu helbidea</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopiatu etiketa</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Transakzioaren xehetasunak</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Komaz bereizitako artxiboa (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Mota</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiketa</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Helbidea</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Kopurua</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Errorea esportatzean</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ezin idatzi %1 artxiboan.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>POPCoin version</source> <translation>Botcoin bertsioa</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or popcoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Komandoen lista</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Laguntza komando batean</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Aukerak</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: popcoin.conf)</source> <translation>Ezarpen fitxategia aukeratu (berezkoa: popcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: popcoind.pid)</source> <translation>pid fitxategia aukeratu (berezkoa: popcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9247 or testnet: 19247)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9347 or testnet: 19347)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=popcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;POPCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. POPCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong POPCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the POPCoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Laguntza mezu hau</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart POPCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. POPCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Birbilatzen...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Zamaketa amaitua</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
popcointeam/popcoin
src/qt/locale/bitcoin_eu_ES.ts
TypeScript
mit
99,892
import sys tagging_filepath = sys.argv[1] following_filepath = sys.argv[2] delim = '\t' if len(sys.argv) > 3: delim = sys.argv[3] graph = {} for line in open(tagging_filepath): entry = line.rstrip().split('\t') src = entry[0] dst = entry[1] if not src in graph: graph[src] = {} graph[src][dst] = 0 for line in open(following_filepath): entry = line.rstrip().split('\t') src = entry[0] dst = entry[1] if src in graph and dst in graph[src]: graph[src][dst] += 1 if dst in graph and src in graph[dst]: graph[dst][src] += 2 w_dir = 0 wo_dir = 0 count = 0.0 for src in graph: for dst in graph[src]: val = graph[src][dst] count += 1 if val in [1,3]: w_dir += 1 if val in [1,2,3]: wo_dir += 1 print "%s\t%s" % (w_dir/count, wo_dir/count)
yamaguchiyuto/icwsm15
tag_follow_disagreement.py
Python
mit
857
/* * The Plaid API * * The Plaid REST API. Please see https://plaid.com/docs/api for more details. * * API version: 2020-09-14_1.78.0 */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package plaid import ( "encoding/json" ) // WalletTransactionExecuteResponse WalletTransactionExecuteResponse defines the response schema for `/wallet/transaction/execute` type WalletTransactionExecuteResponse struct { // A unique ID identifying the transaction TransactionId string `json:"transaction_id"` Status WalletTransactionStatus `json:"status"` // A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive. RequestId string `json:"request_id"` AdditionalProperties map[string]interface{} } type _WalletTransactionExecuteResponse WalletTransactionExecuteResponse // NewWalletTransactionExecuteResponse instantiates a new WalletTransactionExecuteResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWalletTransactionExecuteResponse(transactionId string, status WalletTransactionStatus, requestId string) *WalletTransactionExecuteResponse { this := WalletTransactionExecuteResponse{} this.TransactionId = transactionId this.Status = status this.RequestId = requestId return &this } // NewWalletTransactionExecuteResponseWithDefaults instantiates a new WalletTransactionExecuteResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWalletTransactionExecuteResponseWithDefaults() *WalletTransactionExecuteResponse { this := WalletTransactionExecuteResponse{} return &this } // GetTransactionId returns the TransactionId field value func (o *WalletTransactionExecuteResponse) GetTransactionId() string { if o == nil { var ret string return ret } return o.TransactionId } // GetTransactionIdOk returns a tuple with the TransactionId field value // and a boolean to check if the value has been set. func (o *WalletTransactionExecuteResponse) GetTransactionIdOk() (*string, bool) { if o == nil { return nil, false } return &o.TransactionId, true } // SetTransactionId sets field value func (o *WalletTransactionExecuteResponse) SetTransactionId(v string) { o.TransactionId = v } // GetStatus returns the Status field value func (o *WalletTransactionExecuteResponse) GetStatus() WalletTransactionStatus { if o == nil { var ret WalletTransactionStatus return ret } return o.Status } // GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. func (o *WalletTransactionExecuteResponse) GetStatusOk() (*WalletTransactionStatus, bool) { if o == nil { return nil, false } return &o.Status, true } // SetStatus sets field value func (o *WalletTransactionExecuteResponse) SetStatus(v WalletTransactionStatus) { o.Status = v } // GetRequestId returns the RequestId field value func (o *WalletTransactionExecuteResponse) GetRequestId() string { if o == nil { var ret string return ret } return o.RequestId } // GetRequestIdOk returns a tuple with the RequestId field value // and a boolean to check if the value has been set. func (o *WalletTransactionExecuteResponse) GetRequestIdOk() (*string, bool) { if o == nil { return nil, false } return &o.RequestId, true } // SetRequestId sets field value func (o *WalletTransactionExecuteResponse) SetRequestId(v string) { o.RequestId = v } func (o WalletTransactionExecuteResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["transaction_id"] = o.TransactionId } if true { toSerialize["status"] = o.Status } if true { toSerialize["request_id"] = o.RequestId } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *WalletTransactionExecuteResponse) UnmarshalJSON(bytes []byte) (err error) { varWalletTransactionExecuteResponse := _WalletTransactionExecuteResponse{} if err = json.Unmarshal(bytes, &varWalletTransactionExecuteResponse); err == nil { *o = WalletTransactionExecuteResponse(varWalletTransactionExecuteResponse) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "transaction_id") delete(additionalProperties, "status") delete(additionalProperties, "request_id") o.AdditionalProperties = additionalProperties } return err } type NullableWalletTransactionExecuteResponse struct { value *WalletTransactionExecuteResponse isSet bool } func (v NullableWalletTransactionExecuteResponse) Get() *WalletTransactionExecuteResponse { return v.value } func (v *NullableWalletTransactionExecuteResponse) Set(val *WalletTransactionExecuteResponse) { v.value = val v.isSet = true } func (v NullableWalletTransactionExecuteResponse) IsSet() bool { return v.isSet } func (v *NullableWalletTransactionExecuteResponse) Unset() { v.value = nil v.isSet = false } func NewNullableWalletTransactionExecuteResponse(val *WalletTransactionExecuteResponse) *NullableWalletTransactionExecuteResponse { return &NullableWalletTransactionExecuteResponse{value: val, isSet: true} } func (v NullableWalletTransactionExecuteResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWalletTransactionExecuteResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/plaid-go
plaid/model_wallet_transaction_execute_response.go
GO
mit
5,790
chrome.app.runtime.onLaunched.addListener(function(){ chrome.app.window.create('index.html', { bounds: { width: Math.round(window.screen.availWidth - 100), height: Math.round(window.screen.availHeight - 100) } }); });
pioul/Minimalist-Markdown-Editor-for-Chrome
src/js/background.js
JavaScript
mit
230
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require "yaml" shared_examples "a bullet" do let(:capacity) { 2 } subject do described_class.new(:machines => machines, :guns => capacity) end describe :fire do it "spawns correct number of threads" do bullets = ["first", "second"] subject.specs = bullets Parallel.expects(:map).with(bullets, :in_threads => capacity) subject.fire end it "executes loaded specs" do bullets = ["first", "second"] subject.specs = bullets Bullet::BulletClient.any_instance.stubs(:execute).returns("hello") subject.fire.should == ["hello"] * bullets.length end it "unloads after fire" do bullets = ["first", "second"] subject.specs = bullets Bullet::BulletClient.any_instance.stubs(:execute).returns(true) subject.fire subject.specs.should have(0).bullets end end end describe Bullet::BulletClient do subject { Bullet::BulletClient.new() } describe :unload do it "drops all collected specs and plan_list" do subject.plan_list = {"hello" => 1} subject.specs = ["test"] subject.unload subject.specs.should have(0).spec end end describe :load do it "collect plans" do subject.load("dummy_bullet.yml") subject.plan_list.should eq({"github" => { "user" => {"register" => 10}, "admin" => {"create_user" => 20} }}) end end describe :aim do it "choose target as the plan" do subject.aim("plan") subject.plan.should == "plan" end end describe :prepare do it "calculates path to specs" do subject.plan_list = {"normal" => {"user" => {"signin" => 1, "register" => 2}}} subject.plan = "normal" expected = ["user_signin", "user_register", "user_register"] subject.prepare (subject.specs.flatten - expected).should be_empty end it "distribute specs to machines" do subject.plan_list = {"normal" => {"user" => {"signin" => 1, "register" => 2}}} subject.plan = "normal" subject.machines = 2 subject.prepare subject.specs.should have(2).sets end end describe :ready? do it "verifies that specs exists" do subject.specs = [["hello"]] subject.ready?.should be_true end end describe :use do it "accept the path as look up path" do subject.use("hello") subject.spec_path.should == "hello" end end context "with threads" do it_behaves_like "a bullet" do let(:machines) { 2 } end end context "with processes" do it_behaves_like "a bullet" do let(:machines) { 2 } end end end
dqminh/bullet
spec/bullet_spec.rb
Ruby
mit
2,702
#!/usr/bin/env python # # Copyright 2010 Facebook # # 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. """Python client library for the Facebook Platform. This client library is designed to support the Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication. Read more about the Graph API at http://developers.facebook.com/docs/api. You can download the Facebook JavaScript SDK at http://github.com/facebook/connect-js/. If your application is using Google AppEngine's webapp framework, your usage of this module might look like this: user = facebook.get_user_from_cookie(self.request.cookies, key, secret) if user: graph = facebook.GraphAPI(user["access_token"]) profile = graph.get_object("me") friends = graph.get_connections("me", "friends") """ import cgi import time import urllib import urllib2 import httplib import hashlib import hmac import base64 import logging import socket # Find a JSON parser try: import simplejson as json except ImportError: try: from django.utils import simplejson as json except ImportError: import json _parse_json = json.loads # Find a query string parser try: from urlparse import parse_qs except ImportError: from cgi import parse_qs class GraphAPI(object): """A client for the Facebook Graph API. See http://developers.facebook.com/docs/api for complete documentation for the API. The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at http://developers.facebook.com/docs/reference/api/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See http://developers.facebook.com/docs/authentication/ for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__(self, access_token=None, timeout=None): self.access_token = access_token self.timeout = timeout def get_object(self, id, **args): """Fetchs the given object from the graph.""" return self.request(id, args) def get_objects(self, ids, **args): """Fetchs all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request("", args) def get_connections(self, id, connection_name, **args): """Fetchs the connections for given object.""" return self.request(id + "/" + connection_name, args) def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on a the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") See http://developers.facebook.com/docs/api#publishing for all of the supported writeable objects. Certain write operations require extended permissions. For example, publishing to a user's feed requires the "publish_actions" permission. See http://developers.facebook.com/docs/publishing/ for details about publishing permissions. """ assert self.access_token, "Write operations require an access token" return self.request(parent_object + "/" + connection_name, post_args=data) def put_wall_post(self, message, attachment={}, profile_id="me"): """Writes a wall post to the given profile's wall. We default to writing to the authenticated user's wall if no profile_id is specified. attachment adds a structured attachment to the status message being posted to the Wall. It should be a dictionary of the form: {"name": "Link name" "link": "http://www.example.com/", "caption": "{*actor*} posted a new review", "description": "This is a longer description of the attachment", "picture": "http://www.example.com/thumbnail.jpg"} """ return self.put_object(profile_id, "feed", message=message, **attachment) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" self.request(id, post_args={"method": "delete"}) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" conn = httplib.HTTPSConnection('graph.facebook.com') url = '/%s_%s?%s' % ( request_id, user_id, urllib.urlencode({'access_token': self.access_token}), ) conn.request('DELETE', url) response = conn.getresponse() data = response.read() response = _parse_json(data) # Raise an error if we got one, but don't not if Facebook just # gave us a Bool value if (response and isinstance(response, dict) and response.get("error")): raise GraphAPIError(response) conn.close() def put_photo(self, image, message=None, album_id=None, **kwargs): """Uploads an image using multipart/form-data. image=File like object for the image message=Caption for your image album_id=None posts to /me/photos which uses or creates and uses an album for your application. """ object_id = album_id or "me" #it would have been nice to reuse self.request; #but multipart is messy in urllib post_args = { 'access_token': self.access_token, 'source': image, 'message': message, } post_args.update(kwargs) content_type, body = self._encode_multipart_form(post_args) req = urllib2.Request(("https://graph.facebook.com/%s/photos" % object_id), data=body) req.add_header('Content-Type', content_type) try: data = urllib2.urlopen(req).read() #For Python 3 use this: #except urllib2.HTTPError as e: except urllib2.HTTPError, e: data = e.read() # Facebook sends OAuth errors as 400, and urllib2 # throws an exception, we want a GraphAPIError try: response = _parse_json(data) # Raise an error if we got one, but don't not if Facebook just # gave us a Bool value if (response and isinstance(response, dict) and response.get("error")): raise GraphAPIError(response) except ValueError: response = data return response # based on: http://code.activestate.com/recipes/146306/ def _encode_multipart_form(self, fields): """Encode files as 'multipart/form-data'. Fields are a dict of form name-> value. For files, value should be a file object. Other file-like objects might work and a fake name will be chosen. Returns (content_type, body) ready for httplib.HTTP instance. """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields.items(): logging.debug("Encoding %s, (%s)%s" % (key, type(value), value)) if not value: continue L.append('--' + BOUNDARY) if hasattr(value, 'read') and callable(value.read): filename = getattr(value, 'name', '%s.jpg' % key) L.append(('Content-Disposition: form-data;' 'name="%s";' 'filename="%s"') % (key, filename)) L.append('Content-Type: image/jpeg') value = value.read() logging.debug(type(value)) else: L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') if isinstance(value, unicode): logging.debug("Convert to ascii") value = value.encode('ascii') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def request(self, path, args=None, post_args=None): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) try: file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" + urllib.urlencode(args), post_data, timeout=self.timeout) except urllib2.HTTPError, e: response = _parse_json(e.read()) raise GraphAPIError(response) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" + urllib.urlencode(args), post_data) try: fileInfo = file.info() if fileInfo.maintype == 'text': response = _parse_json(file.read()) elif fileInfo.maintype == 'image': mimetype = fileInfo['content-type'] response = { "data": file.read(), "mime-type": mimetype, "url": file.url, } else: raise GraphAPIError('Maintype was not text or image') finally: file.close() if response and isinstance(response, dict) and response.get("error"): raise GraphAPIError(response["error"]["type"], response["error"]["message"]) return response def fql(self, query, args=None, post_args=None): """FQL query. Example query: "SELECT affiliations FROM user WHERE uid = me()" """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) """Check if query is a dict and use the multiquery method else use single query """ if not isinstance(query, basestring): args["queries"] = query fql_method = 'fql.multiquery' else: args["query"] = query fql_method = 'fql.query' args["format"] = "json" try: file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data, timeout=self.timeout) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data) try: content = file.read() response = _parse_json(content) #Return a list if success, return a dictionary if failed if type(response) is dict and "error_code" in response: raise GraphAPIError(response) except Exception, e: raise e finally: file.close() return response def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/roadmap/offline-access-removal/ #extend_token> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } response = urllib.urlopen("https://graph.facebook.com/oauth/" "access_token?" + urllib.urlencode(args)).read() query_str = parse_qs(response) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] return result else: response = json.loads(response) raise GraphAPIError(response) class GraphAPIError(Exception): def __init__(self, result): #Exception.__init__(self, message) #self.type = type self.result = result try: self.type = result["error_code"] except: self.type = "" # OAuth 2.0 Draft 10 try: self.message = result["error_description"] except: # OAuth 2.0 Draft 00 try: self.message = result["error"]["message"] except: # REST server style try: self.message = result["error_msg"] except: self.message = result Exception.__init__(self, self.message) def get_user_from_cookie(cookies, app_id, app_secret): """Parses the cookie set by the official Facebook JavaScript SDK. cookies should be a dictionary-like object mapping cookie names to cookie values. If the user is logged in via Facebook, we return a dictionary with the keys "uid" and "access_token". The former is the user's Facebook ID, and the latter can be used to make authenticated requests to the Graph API. If the user is not logged in, we return None. Download the official Facebook JavaScript SDK at http://github.com/facebook/connect-js/. Read more about Facebook authentication at http://developers.facebook.com/docs/authentication/. """ cookie = cookies.get("fbsr_" + app_id, "") if not cookie: return None parsed_request = parse_signed_request(cookie, app_secret) if not parsed_request: return None try: result = get_access_token_from_code(parsed_request["code"], "", app_id, app_secret) except GraphAPIError: return None result["uid"] = parsed_request["user_id"] return result def parse_signed_request(signed_request, app_secret): """ Return dictionary with signed request data. We return a dictionary containing the information in the signed_request. This includes a user_id if the user has authorised your application, as well as any information requested. If the signed_request is malformed or corrupted, False is returned. """ try: encoded_sig, payload = map(str, signed_request.split('.', 1)) sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)) data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4)) except IndexError: # Signed request was malformed. return False except TypeError: # Signed request had a corrupted payload. return False data = _parse_json(data) if data.get('algorithm', '').upper() != 'HMAC-SHA256': return False # HMAC can only handle ascii (byte) strings # http://bugs.python.org/issue5285 app_secret = app_secret.encode('ascii') payload = payload.encode('ascii') expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest() if sig != expected_sig: return False return data def auth_url(app_id, canvas_url, perms=None, **kwargs): url = "https://www.facebook.com/dialog/oauth?" kvps = {'client_id': app_id, 'redirect_uri': canvas_url} if perms: kvps['scope'] = ",".join(perms) kvps.update(kwargs) return url + urllib.urlencode(kvps) def get_access_token_from_code(code, redirect_uri, app_id, app_secret): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } # We would use GraphAPI.request() here, except for that the fact # that the response is a key-value pair, and not JSON. response = urllib.urlopen("https://graph.facebook.com/oauth/access_token" + "?" + urllib.urlencode(args)).read() query_str = parse_qs(response) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] return result else: response = json.loads(response) raise GraphAPIError(response) def get_app_access_token(app_id, app_secret): """Get the access_token for the app. This token can be used for insights and creating test users. app_id = retrieved from the developer page app_secret = retrieved from the developer page Returns the application access_token. """ # Get an app access token args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} file = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)) try: result = file.read().split("=")[1] finally: file.close() return result
Agnishom/ascii-art-007
facebook.py
Python
mit
20,087
FactoryGirl.define do factory :transaction do |t| t.description "Test transaction" t.association :account_from, :factory => :foo_account t.association :account_to, :factory => :foo_account t.amount 10.00 end factory :invoice_payment, :parent => :transaction do auxilliary_model :factory => :invoice end end
logicleague/double_booked
spec/factories/transaction_factory.rb
Ruby
mit
340
require 'moosex/types' require 'moosex/attribute/modifiers' module MooseX class Attribute include MooseX::Types attr_reader :attr_symbol, :methods, :attribute_map def is ; @attribute_map[:is] ; end def writter ; @attribute_map[:writter] ; end def reader ; @attribute_map[:reader] ; end def override ; @attribute_map[:override] ; end def doc ; @attribute_map[:doc] ; end def default ; @attribute_map[:default] ; end @@LIST_OF_PARAMETERS = [ :is, #MooseX::AttributeModifiers::Is ], :isa, #MooseX::AttributeModifiers::Isa ], :default, #MooseX::AttributeModifiers::Default ], :required, #MooseX::AttributeModifiers::Required ], :predicate, #MooseX::AttributeModifiers::Predicate], :clearer, #MooseX::AttributeModifiers::Clearer ], :traits, #MooseX::AttributeModifiers::Traits ], :handles, #MooseX::AttributeModifiers::Handles ], :lazy, #MooseX::AttributeModifiers::Lazy ], :reader, #MooseX::AttributeModifiers::Reader ], :writter, #MooseX::AttributeModifiers::Writter ], :builder, #MooseX::AttributeModifiers::Builder ], :init_arg, #MooseX::AttributeModifiers::Init_arg ], :trigger, #MooseX::AttributeModifiers::Trigger ], :coerce, #MooseX::AttributeModifiers::Coerce ], :weak, #MooseX::AttributeModifiers::Weak ], :doc, #MooseX::AttributeModifiers::Doc ], :override, #MooseX::AttributeModifiers::Override ], ] def initialize(attr_symbol, options ,klass) @attr_symbol = attr_symbol @attribute_map = {} init_internal_modifiers(options.clone, klass.__moosex__meta.plugins, klass) end def init_internal_modifiers(options, plugins, klass) list = @@LIST_OF_PARAMETERS.map do |parameter| MooseX::AttributeModifiers::const_get(parameter.capitalize).new(self) end list.each do |plugin| plugin.prepare(options) end plugins.sort.uniq.each do |plugin_klass| begin plugin_klass.new(self).prepare(options) rescue => e raise "Unexpected Error in #{klass} #{plugin_klass} #{@attr_symbol}: #{e}" end end list.each do |plugin| plugin.process(options) end generate_all_methods plugins.sort.uniq.each do |plugin_klass| begin plugin_klass.new(self).process(options) rescue NameError => e next rescue => e raise "Unexpected Error in #{klass} #{plugin_klass} #{@attr_symbol}: #{e}" end end MooseX.warn "Unused attributes #{options} for attribute #{@attr_symbol} @ #{klass} #{klass.class}",caller() if ! options.empty? end def generate_all_methods @methods = {} if @attribute_map[:reader] @methods[@attribute_map[:reader]] = generate_reader end if @attribute_map[:writter] @methods[@attribute_map[:writter]] = generate_writter end inst_variable_name = "@#{@attr_symbol}".to_sym if @attribute_map[:predicate] @methods[@attribute_map[:predicate]] = ->(this) do this.instance_variable_defined? inst_variable_name end end if @attribute_map[:clearer] @methods[@attribute_map[:clearer]] = ->(this) do if this.instance_variable_defined? inst_variable_name this.remove_instance_variable inst_variable_name end end end generate_handles @attr_symbol end def generate_handles(attr_symbol) delegator = ->(this) { this.__send__(attr_symbol) } @attribute_map[:handles].each_pair do | method, target_method | if target_method.is_a? Array original_method, currying = target_method @methods[method] = generate_handles_with_currying(delegator, original_method, currying) else @methods[method] = Proc.new do |this, *args, &proc| delegator.call(this).__send__(target_method, *args, &proc) end end end end def generate_handles_with_currying(delegator, original_method, currying) Proc.new do |this, *args, &proc| a1 = [ currying ] if currying.is_a?Proc a1 = currying[] elsif currying.is_a? Array a1 = currying.map{|c| (c.is_a?(Proc)) ? c[] : c } end delegator.call(this).__send__(original_method, *a1, *args, &proc) end end def init(object, args) value = nil value_from_default = false if args.has_key? @attribute_map[:init_arg] value = args.delete(@attribute_map[:init_arg]) elsif @attribute_map[:default] value = @attribute_map[:default].call value_from_default = true elsif @attribute_map[:required] raise InvalidAttributeError, "attr \"#{@attr_symbol}\" is required" else return end value = @attribute_map[:coerce].call(value) begin @attribute_map[:isa].call( value ) rescue MooseX::Types::TypeCheckError => e raise MooseX::Types::TypeCheckError, "isa check for field #{attr_symbol}: #{e}" end unless value_from_default @attribute_map[:trigger].call(object, value) end value = @attribute_map[:traits].call(value) inst_variable_name = "@#{@attr_symbol}".to_sym object.instance_variable_set inst_variable_name, value end def generate_reader inst_variable_name = "@#{@attr_symbol}".to_sym builder = @attribute_map[:builder] before_get = ->(object) { } if @attribute_map[:lazy] type_check = protect_isa(@attribute_map[:isa], "isa check for #{inst_variable_name} from builder") coerce = @attribute_map[:coerce] trigger = @attribute_map[:trigger] traits = @attribute_map[:traits] before_get = ->(object) do return if object.instance_variable_defined? inst_variable_name value = builder.call(object) value = coerce.call(value) type_check.call( value ) trigger.call(object, value) value = traits.call(value) object.instance_variable_set(inst_variable_name, value) end end ->(this) do before_get.call(this) this.instance_variable_get inst_variable_name end end def protect_isa(type_check, message) ->(value) do begin type_check.call( value ) rescue MooseX::Types::TypeCheckError => e raise MooseX::Types::TypeCheckError, "#{message}: #{e}" end end end def generate_writter writter_name = @attribute_map[:writter] inst_variable_name = "@#{@attr_symbol}".to_sym coerce = @attribute_map[:coerce] type_check = protect_isa(@attribute_map[:isa], "isa check for #{writter_name}") trigger = @attribute_map[:trigger] traits = @attribute_map[:traits] ->(this, value) do value = coerce.call(value) type_check.call( value ) trigger.call(this,value) value = traits.call(value) this.instance_variable_set inst_variable_name, value end end end end
peczenyj/MooseX
lib/moosex/attribute.rb
Ruby
mit
7,509
/* * Copyright (c) 2011-2016, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.filter.binary; import boofcv.struct.ConnectRule; import boofcv.struct.image.GrayS32; import boofcv.struct.image.GrayU8; import georegression.struct.point.Point2D_I32; import sapphire.app.SapphireObject; import org.ddogleg.struct.FastQueue; import java.util.List; /** * Used to trace the external and internal contours around objects for {@link LinearContourLabelChang2004}. As it * is tracing an object it will modify the binary image by labeling. The input binary image is assumed to have * a 1-pixel border that needs to be compensated for. * * @author Peter Abeles */ public class ContourTracer implements SapphireObject { // which connectivity rule is being used. 4 and 8 supported private ConnectRule rule; private int ruleN; // storage for contour points. private FastQueue<Point2D_I32> storagePoints; // binary image being traced private GrayU8 binary; // label image being marked private GrayS32 labeled; // storage for contour private List<Point2D_I32> contour; // coordinate of pixel being examined (x,y) private int x,y; // label of the object being traced private int label; // direction it moved in private int dir; // index of the pixel in the image's internal array private int indexBinary; private int indexLabel; // the pixel index offset to each neighbor private int offsetsBinary[]; private int offsetsLabeled[]; // lookup table for which direction it should search next given the direction it traveled into the current pixel private int nextDirection[]; /** * Specifies connectivity rule * * @param rule Specifies 4 or 8 as connectivity rule */ public ContourTracer( ConnectRule rule ) { this.rule = rule; if( ConnectRule.EIGHT == rule ) { // start the next search +2 away from the square it came from // the square it came from is the opposite from the previous 'dir' nextDirection = new int[8]; for( int i = 0; i < 8; i++ ) nextDirection[i] = ((i+4)%8 + 2)%8; ruleN = 8; } else if( ConnectRule.FOUR == rule ) { nextDirection = new int[4]; for( int i = 0; i < 4; i++ ) nextDirection[i] = ((i+2)%4 + 1)%4; ruleN = 4; } else { throw new IllegalArgumentException("Connectivity rule must be 4 or 8 not "+rule); } offsetsBinary = new int[ruleN]; offsetsLabeled = new int[ruleN]; } /** * * @param binary Binary image with a border of zeros added to the outside. * @param labeled Labeled image. Size is the same as the original binary image without border. * @param storagePoints */ public void setInputs(GrayU8 binary , GrayS32 labeled , FastQueue<Point2D_I32> storagePoints ) { this.binary = binary; this.labeled = labeled; this.storagePoints = storagePoints; if( rule == ConnectRule.EIGHT ) { setOffsets8(offsetsBinary,binary.stride); setOffsets8(offsetsLabeled,labeled.stride); } else { setOffsets4(offsetsBinary,binary.stride); setOffsets4(offsetsLabeled,labeled.stride); } } private void setOffsets8( int offsets[] , int stride ) { int s = stride; offsets[0] = 1; // x = 1 y = 0 offsets[1] = 1+s; // x = 1 y = 1 offsets[2] = s; // x = 0 y = 1 offsets[3] = -1+s; // x = -1 y = 1 offsets[4] = -1 ; // x = -1 y = 0 offsets[5] = -1-s; // x = -1 y = -1 offsets[6] = -s; // x = 0 y = -1 offsets[7] = 1-s; // x = 1 y = -1 } private void setOffsets4( int offsets[] , int stride ) { int s = stride; offsets[0] = 1; // x = 1 y = 0 offsets[1] = s; // x = 0 y = 1 offsets[2] = -1; // x = -1 y = 0 offsets[3] = -s; // x = 0 y = -1 } /** * * @param label * @param initialX * @param initialY * @param external True for tracing an external contour or false for internal.. * @param contour */ public void trace( int label , int initialX , int initialY , boolean external , List<Point2D_I32> contour ) { int initialDir; if( rule == ConnectRule.EIGHT ) initialDir = external ? 7 : 3; else initialDir = external ? 0 : 2; this.label = label; this.contour = contour; this.dir = initialDir; x = initialX; y = initialY; // index of pixels in the image array // binary has a 1 pixel border which labeled lacks, hence the -1,-1 for labeled indexBinary = binary.getIndex(x,y); indexLabel = labeled.getIndex(x-1,y-1); add(x,y); // find the next black pixel. handle case where its an isolated point if( !searchBlack() ) { return; } else { initialDir = dir; moveToNext(); dir = nextDirection[dir]; } while( true ) { // search in clockwise direction around the current pixel for next black pixel searchBlack(); if( x == initialX && y == initialY && dir == initialDir ) { // returned to the initial state again. search is finished return; }else { add(x, y); moveToNext(); dir = nextDirection[dir]; } } } /** * Searches in a circle around the current point in a clock-wise direction for the first black pixel. */ private boolean searchBlack() { for( int i = 0; i < offsetsBinary.length; i++ ) { if( checkBlack(indexBinary + offsetsBinary[dir])) return true; dir = (dir+1)%ruleN; } return false; } /** * Checks to see if the specified pixel is black (1). If not the pixel is marked so that it * won't be searched again */ private boolean checkBlack( int index ) { if( binary.data[index] == 1 ) { return true; } else { // mark white pixels as negative numbers to avoid retracing this contour in the future binary.data[index] = -1; return false; } } private void moveToNext() { // move to the next pixel using the precomputed pixel index offsets indexBinary += offsetsBinary[dir]; indexLabel += offsetsLabeled[dir]; // compute the new pixel coordinate from the binary pixel index int a = indexBinary - binary.startIndex; x = a%binary.stride; y = a/binary.stride; } /** * Adds a point to the contour list */ private void add( int x , int y ) { Point2D_I32 p = storagePoints.grow(); // compensate for the border added to binary image p.set(x-1, y-1); contour.add(p); labeled.data[indexLabel] = label; } }
bladestery/Sapphire
example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/alg/filter/binary/ContourTracer.java
Java
mit
6,808
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Console.Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Console.Server")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("a7943db8-a75d-467f-aa1e-96134b5739ea")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
IKende/IKendeLib
BeetleDemo/Examples/Console/Console.Server/Console.Server/Properties/AssemblyInfo.cs
C#
mit
1,324
using Microsoft.SPOT.Hardware; namespace GrFamily.MainBoard { /// <summary> /// LEDƒNƒ‰ƒX /// </summary> public class Led { /// <summary>LED‚ªÚ‘±‚³‚ꂽƒsƒ“</summary> protected readonly OutputPort LedPort; /// <summary> /// ƒRƒ“ƒXƒgƒ‰ƒNƒ^ /// </summary> /// <param name="pin">LED‚ªÚ‘±‚³‚ꂽƒsƒ“</param> public Led(Cpu.Pin pin) { LedPort = new OutputPort(pin, false); } /// <summary> /// LED‚ð“_“”^Á“”‚·‚é /// </summary> /// <param name="on">LED‚ð“_“”‚·‚éê‡‚Í trueAÁ“”‚·‚éê‡‚Í false</param> public void SetLed(bool on) { LedPort.Write(on); } } }
netmf-lib-grfamily/GrFamilyLibrary
Library/MainBoard/Peach/Led.cs
C#
mit
733
module ngFoundation.directives { //@NgDirective('topBarSection') class TopBarSectionDirective implements ng.IDirective { template = '<section class="top-bar-section" ng-transclude></section>'; restrict = "E"; transclude = true; replace = true; } }
rewso/angular-foundation
src/directives/topBarSection.ts
TypeScript
mit
272
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Three20" do it "fails" do fail "hey buddy, you should probably rename this file and start specing for real" end end
jwang/three20-gem
spec/three20_spec.rb
Ruby
mit
201
if (Zepto.ajax.restore) { Zepto.ajax.restore(); } sinon.stub(Zepto, "ajax") .yieldsTo("success", { responseStatus : 200, responseDetails : null, responseData : { feed: { link : "http://github.com", title : "GitHub Public Timeline", entries : [ { title : "Croaky signed up", link : "http://github.com/Croaky/openbeerdatabase", author : "", publishedDate : "Thu, 24 Nov 2011 19:00:00 -0600", content : "\u003cstrong\u003eCroaky\u003c/strong\u003e signed up for GitHub.", contentSnippet : "Croaky signed up for GitHub.", categories : [] } ] } } });
tristandunn/reading
spec/javascripts/fixtures/github.com.js
JavaScript
mit
753
#include "estimation/sensors/make_interpolator.hh" namespace estimation { geometry::spatial::TimeInterpolator make_accel_interpolator( const std::vector<TimedMeasurement<jet_filter::AccelMeasurement>>& accel_meas, const ImuModel& imu_model) { std::vector<geometry::spatial::TimeControlPoint> points; for (const auto& accel : accel_meas) { const jcc::Vec3 corrected_accel = imu_model.correct_measured_accel(accel.measurement.observed_acceleration); points.push_back({accel.timestamp, corrected_accel}); } const geometry::spatial::TimeInterpolator interp(points); return interp; } geometry::spatial::TimeInterpolator make_gyro_interpolator( const std::vector<TimedMeasurement<jet_filter::GyroMeasurement>>& gyro_meas) { std::vector<geometry::spatial::TimeControlPoint> points; for (const auto& gyro : gyro_meas) { points.push_back({gyro.timestamp, gyro.measurement.observed_w}); } const geometry::spatial::TimeInterpolator interp(points); return interp; } } // namespace estimation
jpanikulam/experiments
estimation/sensors/make_interpolator.cc
C++
mit
1,053
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. import threading from typing import Optional, Tuple from pyqrllib.pyqrllib import bin2hstr from pyqryptonight.pyqryptonight import StringToUInt256, UInt256ToString from qrl.core import config, BlockHeader from qrl.core.AddressState import AddressState from qrl.core.Block import Block from qrl.core.BlockMetadata import BlockMetadata from qrl.core.DifficultyTracker import DifficultyTracker from qrl.core.GenesisBlock import GenesisBlock from qrl.core.PoWValidator import PoWValidator from qrl.core.txs.Transaction import Transaction from qrl.core.txs.CoinBase import CoinBase from qrl.core.TransactionPool import TransactionPool from qrl.core.misc import logger from qrl.crypto.Qryptonight import Qryptonight from qrl.generated import qrl_pb2, qrlstateinfo_pb2 class ChainManager: def __init__(self, state): self._state = state self.tx_pool = TransactionPool(None) self._last_block = Block.deserialize(GenesisBlock().serialize()) self.current_difficulty = StringToUInt256(str(config.user.genesis_difficulty)) self.trigger_miner = False self.lock = threading.RLock() @property def height(self): with self.lock: if not self._last_block: return -1 return self._last_block.block_number @property def last_block(self) -> Block: with self.lock: return self._last_block @property def total_coin_supply(self): with self.lock: return self._state.total_coin_supply def get_block_datapoint(self, headerhash): with self.lock: return self._state.get_block_datapoint(headerhash) def get_cumulative_difficulty(self): with self.lock: last_block_metadata = self._state.get_block_metadata(self._last_block.headerhash) return last_block_metadata.cumulative_difficulty def get_block_by_number(self, block_number) -> Optional[Block]: with self.lock: return self._state.get_block_by_number(block_number) def get_block_header_hash_by_number(self, block_number) -> Optional[bytes]: with self.lock: return self._state.get_block_header_hash_by_number(block_number) def get_block(self, header_hash: bytes) -> Optional[Block]: with self.lock: return self._state.get_block(header_hash) def get_address_balance(self, address: bytes) -> int: with self.lock: return self._state.get_address_balance(address) def get_address_is_used(self, address: bytes) -> bool: with self.lock: return self._state.get_address_is_used(address) def get_address_state(self, address: bytes) -> AddressState: with self.lock: return self._state.get_address_state(address) def get_all_address_state(self): with self.lock: return self._state.get_all_address_state() def get_tx_metadata(self, transaction_hash) -> list: with self.lock: return self._state.get_tx_metadata(transaction_hash) def get_last_transactions(self): with self.lock: return self._state.get_last_txs() def get_unconfirmed_transaction(self, transaction_hash) -> list: with self.lock: for tx_set in self.tx_pool.transactions: tx = tx_set[1].transaction if tx.txhash == transaction_hash: return [tx, tx_set[1].timestamp] if transaction_hash in self.tx_pool.pending_tx_pool_hash: for tx_set in self.tx_pool.pending_tx_pool: tx = tx_set[1].transaction if tx.txhash == transaction_hash: return [tx, tx_set[1].timestamp] return [] def get_block_metadata(self, header_hash: bytes) -> Optional[BlockMetadata]: with self.lock: return self._state.get_block_metadata(header_hash) def get_blockheader_and_metadata(self, block_number=0) -> Tuple: with self.lock: block_number = block_number or self.height # if both are non-zero, then block_number takes priority result = (None, None) block = self.get_block_by_number(block_number) if block: blockheader = block.blockheader blockmetadata = self.get_block_metadata(blockheader.headerhash) result = (blockheader, blockmetadata) return result def get_block_to_mine(self, miner, wallet_address) -> list: with miner.lock: # Trying to acquire miner.lock to make sure pre_block_logic is not running with self.lock: last_block = self.last_block last_block_metadata = self.get_block_metadata(last_block.headerhash) return miner.get_block_to_mine(wallet_address, self.tx_pool, last_block, last_block_metadata.block_difficulty) def get_measurement(self, block_timestamp, parent_headerhash, parent_metadata: BlockMetadata): with self.lock: return self._state.get_measurement(block_timestamp, parent_headerhash, parent_metadata) def get_block_size_limit(self, block: Block): with self.lock: return self._state.get_block_size_limit(block) def get_block_is_duplicate(self, block: Block) -> bool: with self.lock: return self._state.get_block(block.headerhash) is not None def validate_mining_nonce(self, blockheader: BlockHeader, enable_logging=True): with self.lock: parent_metadata = self.get_block_metadata(blockheader.prev_headerhash) parent_block = self._state.get_block(blockheader.prev_headerhash) measurement = self.get_measurement(blockheader.timestamp, blockheader.prev_headerhash, parent_metadata) diff, target = DifficultyTracker.get( measurement=measurement, parent_difficulty=parent_metadata.block_difficulty) if enable_logging: logger.debug('-----------------START--------------------') logger.debug('Validate #%s', blockheader.block_number) logger.debug('block.timestamp %s', blockheader.timestamp) logger.debug('parent_block.timestamp %s', parent_block.timestamp) logger.debug('parent_block.difficulty %s', UInt256ToString(parent_metadata.block_difficulty)) logger.debug('diff %s', UInt256ToString(diff)) logger.debug('target %s', bin2hstr(target)) logger.debug('-------------------END--------------------') if not PoWValidator().verify_input(blockheader.mining_blob, target): if enable_logging: logger.warning("PoW verification failed") qn = Qryptonight() tmp_hash = qn.hash(blockheader.mining_blob) logger.warning("{}".format(bin2hstr(tmp_hash))) logger.debug('%s', blockheader.to_json()) return False return True def get_headerhashes(self, start_blocknumber): with self.lock: start_blocknumber = max(0, start_blocknumber) end_blocknumber = min(self._last_block.block_number, start_blocknumber + 2 * config.dev.reorg_limit) total_expected_headerhash = end_blocknumber - start_blocknumber + 1 node_header_hash = qrl_pb2.NodeHeaderHash() node_header_hash.block_number = start_blocknumber block = self._state.get_block_by_number(end_blocknumber) block_headerhash = block.headerhash node_header_hash.headerhashes.append(block_headerhash) end_blocknumber -= 1 while end_blocknumber >= start_blocknumber: block_metadata = self._state.get_block_metadata(block_headerhash) for headerhash in block_metadata.last_N_headerhashes[-1::-1]: node_header_hash.headerhashes.append(headerhash) end_blocknumber -= len(block_metadata.last_N_headerhashes) if len(block_metadata.last_N_headerhashes) == 0: break block_headerhash = block_metadata.last_N_headerhashes[0] node_header_hash.headerhashes[:] = node_header_hash.headerhashes[-1::-1] del node_header_hash.headerhashes[:len(node_header_hash.headerhashes) - total_expected_headerhash] return node_header_hash def set_broadcast_tx(self, broadcast_tx): with self.lock: self.tx_pool.set_broadcast_tx(broadcast_tx) def load(self, genesis_block): # load() has the following tasks: # Write Genesis Block into State immediately # Register block_number <-> blockhash mapping # Calculate difficulty Metadata for Genesis Block # Generate AddressStates from Genesis Block balances # Apply Genesis Block's transactions to the state # Detect if we are forked from genesis block and if so initiate recovery. height = self._state.get_mainchain_height() if height == -1: self._state.put_block(genesis_block, None) block_number_mapping = qrl_pb2.BlockNumberMapping(headerhash=genesis_block.headerhash, prev_headerhash=genesis_block.prev_headerhash) self._state.put_block_number_mapping(genesis_block.block_number, block_number_mapping, None) parent_difficulty = StringToUInt256(str(config.user.genesis_difficulty)) self.current_difficulty, _ = DifficultyTracker.get( measurement=config.dev.mining_setpoint_blocktime, parent_difficulty=parent_difficulty) block_metadata = BlockMetadata.create() block_metadata.set_block_difficulty(self.current_difficulty) block_metadata.set_cumulative_difficulty(self.current_difficulty) self._state.put_block_metadata(genesis_block.headerhash, block_metadata, None) addresses_state = dict() for genesis_balance in GenesisBlock().genesis_balance: bytes_addr = genesis_balance.address addresses_state[bytes_addr] = AddressState.get_default(bytes_addr) addresses_state[bytes_addr]._data.balance = genesis_balance.balance for tx_idx in range(1, len(genesis_block.transactions)): tx = Transaction.from_pbdata(genesis_block.transactions[tx_idx]) for addr in tx.addrs_to: addresses_state[addr] = AddressState.get_default(addr) coinbase_tx = Transaction.from_pbdata(genesis_block.transactions[0]) if not isinstance(coinbase_tx, CoinBase): return False addresses_state[coinbase_tx.addr_to] = AddressState.get_default(coinbase_tx.addr_to) if not coinbase_tx.validate_extended(genesis_block.block_number): return False coinbase_tx.apply_state_changes(addresses_state) for tx_idx in range(1, len(genesis_block.transactions)): tx = Transaction.from_pbdata(genesis_block.transactions[tx_idx]) tx.apply_state_changes(addresses_state) self._state.put_addresses_state(addresses_state) self._state.update_tx_metadata(genesis_block, None) self._state.update_mainchain_height(0, None) else: self._last_block = self.get_block_by_number(height) self.current_difficulty = self._state.get_block_metadata(self._last_block.headerhash).block_difficulty fork_state = self._state.get_fork_state() if fork_state: block = self._state.get_block(fork_state.initiator_headerhash) self._fork_recovery(block, fork_state) def _apply_block(self, block: Block, batch) -> bool: address_set = self._state.prepare_address_list(block) # Prepare list for current block addresses_state = self._state.get_state_mainchain(address_set) if not block.apply_state_changes(addresses_state): return False self._state.put_addresses_state(addresses_state, batch) return True def _update_chainstate(self, block: Block, batch): self._last_block = block self._update_block_number_mapping(block, batch) self.tx_pool.remove_tx_in_block_from_pool(block) self._state.update_mainchain_height(block.block_number, batch) self._state.update_tx_metadata(block, batch) def _try_branch_add_block(self, block, batch, check_stale=True) -> (bool, bool): """ This function returns list of bool types. The first bool represent if the block has been added successfully and the second bool represent the fork_flag, which becomes true when a block triggered into fork recovery. :param block: :param batch: :return: [Added successfully, fork_flag] """ if self._last_block.headerhash == block.prev_headerhash: if not self._apply_block(block, batch): return False, False self._state.put_block(block, batch) last_block_metadata = self._state.get_block_metadata(self._last_block.headerhash) if last_block_metadata is None: logger.warning("Could not find log metadata for %s", bin2hstr(self._last_block.headerhash)) return False, False last_block_difficulty = int(UInt256ToString(last_block_metadata.cumulative_difficulty)) new_block_metadata = self._add_block_metadata(block.headerhash, block.timestamp, block.prev_headerhash, batch) new_block_difficulty = int(UInt256ToString(new_block_metadata.cumulative_difficulty)) if new_block_difficulty > last_block_difficulty: if self._last_block.headerhash != block.prev_headerhash: fork_state = qrlstateinfo_pb2.ForkState(initiator_headerhash=block.headerhash) self._state.put_fork_state(fork_state, batch) self._state.write_batch(batch) return self._fork_recovery(block, fork_state), True self._update_chainstate(block, batch) if check_stale: self.tx_pool.check_stale_txn(self._state, block.block_number) self.trigger_miner = True return True, False def _remove_block_from_mainchain(self, block: Block, latest_block_number: int, batch): addresses_set = self._state.prepare_address_list(block) addresses_state = self._state.get_state_mainchain(addresses_set) for tx_idx in range(len(block.transactions) - 1, -1, -1): tx = Transaction.from_pbdata(block.transactions[tx_idx]) tx.revert_state_changes(addresses_state, self) self.tx_pool.add_tx_from_block_to_pool(block, latest_block_number) self._state.update_mainchain_height(block.block_number - 1, batch) self._state.rollback_tx_metadata(block, batch) self._state.remove_blocknumber_mapping(block.block_number, batch) self._state.put_addresses_state(addresses_state, batch) def _get_fork_point(self, block: Block): tmp_block = block hash_path = [] while True: if not block: raise Exception('[get_state] No Block Found %s, Initiator %s', block.headerhash, tmp_block.headerhash) mainchain_block = self.get_block_by_number(block.block_number) if mainchain_block and mainchain_block.headerhash == block.headerhash: break if block.block_number == 0: raise Exception('[get_state] Alternate chain genesis is different, Initiator %s', tmp_block.headerhash) hash_path.append(block.headerhash) block = self._state.get_block(block.prev_headerhash) return block.headerhash, hash_path def _rollback(self, forked_header_hash: bytes, fork_state: qrlstateinfo_pb2.ForkState = None): """ Rollback from last block to the block just before the forked_header_hash :param forked_header_hash: :param fork_state: :return: """ hash_path = [] while self._last_block.headerhash != forked_header_hash: block = self._state.get_block(self._last_block.headerhash) mainchain_block = self._state.get_block_by_number(block.block_number) if block is None: logger.warning("self.state.get_block(self.last_block.headerhash) returned None") if mainchain_block is None: logger.warning("self.get_block_by_number(block.block_number) returned None") if block.headerhash != mainchain_block.headerhash: break hash_path.append(self._last_block.headerhash) batch = self._state.batch self._remove_block_from_mainchain(self._last_block, block.block_number, batch) if fork_state: fork_state.old_mainchain_hash_path.extend([self._last_block.headerhash]) self._state.put_fork_state(fork_state, batch) self._state.write_batch(batch) self._last_block = self._state.get_block(self._last_block.prev_headerhash) return hash_path def add_chain(self, hash_path: list, fork_state: qrlstateinfo_pb2.ForkState) -> bool: """ Add series of blocks whose headerhash mentioned into hash_path :param hash_path: :param fork_state: :param batch: :return: """ with self.lock: start = 0 try: start = hash_path.index(self._last_block.headerhash) + 1 except ValueError: # Following condition can only be true if the fork recovery was interrupted last time if self._last_block.headerhash in fork_state.old_mainchain_hash_path: return False for i in range(start, len(hash_path)): header_hash = hash_path[i] block = self._state.get_block(header_hash) batch = self._state.batch if not self._apply_block(block, batch): return False self._update_chainstate(block, batch) logger.debug('Apply block #%d - [batch %d | %s]', block.block_number, i, hash_path[i]) self._state.write_batch(batch) self._state.delete_fork_state() return True def _fork_recovery(self, block: Block, fork_state: qrlstateinfo_pb2.ForkState) -> bool: logger.info("Triggered Fork Recovery") # This condition only becomes true, when fork recovery was interrupted if fork_state.fork_point_headerhash: logger.info("Recovering from last fork recovery interruption") forked_header_hash, hash_path = fork_state.fork_point_headerhash, fork_state.new_mainchain_hash_path else: forked_header_hash, hash_path = self._get_fork_point(block) fork_state.fork_point_headerhash = forked_header_hash fork_state.new_mainchain_hash_path.extend(hash_path) self._state.put_fork_state(fork_state) rollback_done = False if fork_state.old_mainchain_hash_path: b = self._state.get_block(fork_state.old_mainchain_hash_path[-1]) if b and b.prev_headerhash == fork_state.fork_point_headerhash: rollback_done = True if not rollback_done: logger.info("Rolling back") old_hash_path = self._rollback(forked_header_hash, fork_state) else: old_hash_path = fork_state.old_mainchain_hash_path if not self.add_chain(hash_path[-1::-1], fork_state): logger.warning("Fork Recovery Failed... Recovering back to old mainchain") # If above condition is true, then it means, the node failed to add_chain # Thus old chain state, must be retrieved self._rollback(forked_header_hash) self.add_chain(old_hash_path[-1::-1], fork_state) # Restores the old chain state return False logger.info("Fork Recovery Finished") self.trigger_miner = True return True def _add_block(self, block, batch=None, check_stale=True) -> (bool, bool): self.trigger_miner = False block_size_limit = self.get_block_size_limit(block) if block_size_limit and block.size > block_size_limit: logger.info('Block Size greater than threshold limit %s > %s', block.size, block_size_limit) return False, False return self._try_branch_add_block(block, batch, check_stale) def add_block(self, block: Block, check_stale=True) -> bool: with self.lock: if block.block_number < self.height - config.dev.reorg_limit: logger.debug('Skipping block #%s as beyond re-org limit', block.block_number) return False if self.get_block_is_duplicate(block): return False batch = self._state.batch block_flag, fork_flag = self._add_block(block, batch=batch, check_stale=check_stale) if block_flag: if not fork_flag: self._state.write_batch(batch) logger.info('Added Block #%s %s', block.block_number, bin2hstr(block.headerhash)) return True return False def _add_block_metadata(self, headerhash, block_timestamp, parent_headerhash, batch): block_metadata = self._state.get_block_metadata(headerhash) if not block_metadata: block_metadata = BlockMetadata.create() parent_metadata = self._state.get_block_metadata(parent_headerhash) parent_block_difficulty = parent_metadata.block_difficulty parent_cumulative_difficulty = parent_metadata.cumulative_difficulty block_metadata.update_last_headerhashes(parent_metadata.last_N_headerhashes, parent_headerhash) measurement = self._state.get_measurement(block_timestamp, parent_headerhash, parent_metadata) block_difficulty, _ = DifficultyTracker.get( measurement=measurement, parent_difficulty=parent_block_difficulty) block_cumulative_difficulty = StringToUInt256(str( int(UInt256ToString(block_difficulty)) + int(UInt256ToString(parent_cumulative_difficulty)))) block_metadata.set_block_difficulty(block_difficulty) block_metadata.set_cumulative_difficulty(block_cumulative_difficulty) parent_metadata.add_child_headerhash(headerhash) self._state.put_block_metadata(parent_headerhash, parent_metadata, batch) self._state.put_block_metadata(headerhash, block_metadata, batch) return block_metadata def _update_block_number_mapping(self, block, batch): block_number_mapping = qrl_pb2.BlockNumberMapping(headerhash=block.headerhash, prev_headerhash=block.prev_headerhash) self._state.put_block_number_mapping(block.block_number, block_number_mapping, batch)
jleni/QRL
src/qrl/core/ChainManager.py
Python
mit
23,847
<?php namespace Nitrapi\Common\Exceptions; class NitrapiHttpErrorException extends NitrapiException { }
nitrado/Nitrapi-PHP
lib/Nitrapi/Common/Exceptions/NitrapiHttpErrorException.php
PHP
mit
105
var baseURL; $.validator.addMethod("alfanumerico", function(value, element) { return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value); }, "Este campo es alfanumerico."); $("#frmGuardaTipoDocumento").validate({ rules : { descripcion : "required", codigo : {required:true,alfanumerico:true}, }, messages : { descripcion : "Ingrese este campo.", codigo : {required:"Ingrese este campo.",alfanumerico:"Este campo es alfanumerico."}, }, submitHandler : function(form) { $.ajax(form.action, { async : false, type : "POST", data : $(form).serialize(), success : function(contenido) { //alert("contenido :"+ contenido); if(contenido=="error"){ var mensaje="Este tipo de documento ya ha sido registrado"; alert(mensaje); } else{ baseURL = $("#baseURL").val(); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos?info="+contenido, function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); } } }); } }); function cancelarTipoDocumento(){ var baseURL; baseURL = $("#baseURL").val(); $("#contenidoPrincipal").html("Cargando . . ."); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); }
javiervilcapaza/inst
inst/src/main/webapp/resources/scripts/mantenimientoInterno/tipoDocumentoFormulario.js
JavaScript
mit
1,492
export { default } from 'ember-flexberry-designer/controllers/fd-interface-edit-form/new';
Flexberry/ember-flexberry-designer
app/controllers/fd-interface-edit-form/new.js
JavaScript
mit
91
<?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ //Route::middleware('auth:api')->get('/user', function (Request $request) { // return $request->user(); //}); //Route::get('wechat/index', 'WechatController@index');
growu/growu-website
routes/api.php
PHP
mit
591
package com.board.gd.domain.stock; import lombok.Data; import java.util.List; import java.util.stream.Collectors; /** * Created by gd.godong9 on 2017. 5. 19. */ @Data public class StockResult { private Long id; private String name; private String code; public static StockResult getStockResult(Stock stock) { StockResult stockResult = new StockResult(); stockResult.setId(stock.getId()); stockResult.setName(stock.getName()); stockResult.setCode(stock.getCode()); return stockResult; } public static List<StockResult> getStockResultList(List<Stock> stockList) { return stockList.stream() .map(stock -> getStockResult(stock)) .collect(Collectors.toList()); } }
godong9/spring-board
board/src/main/java/com/board/gd/domain/stock/StockResult.java
Java
mit
777
<?php /** * General purpose and commonly used PHP interface definitions * * @author Михаил Красильников <m.krasilnikov@yandex.ru> * @license http://opensource.org/licenses/MIT MIT */ namespace Mekras\Interfaces\Http\Message; use Psr\Http\Message\RequestInterface; /** * HTTP request factory * * Object can create empty instances of {@link \Psr\Http\Message\RequestInterface}. * This can be used to abstract from concrete PSR-7 implementation. * * @deprecated use https://packagist.org/packages/php-http/httplug * * @since 3.4 deprecated * @since 3.02 */ interface RequestFactory { /** * Create empty HTTP request * * @return RequestInterface * * @since 3.02 */ public function createEmptyRequest(); }
mekras/interfaces
lib/Http/Message/RequestFactory.php
PHP
mit
775
<!-- Unsafe sample input : get the UserData field of $_SESSION Uses a number_float_filter via filter_var function File : unsafe, use of untrusted data in CSS --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <style> <?php $tainted = $_SESSION['UserData']; $sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_FLOAT); if (filter_var($sanitized, FILTER_VALIDATE_FLOAT)) $tainted = $sanitized ; else $tainted = "" ; //flaw echo $tainted ; ?> </style> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/unsafe/CWE_79__SESSION__func_FILTER-CLEANING-number_float_filter__Unsafe_use_untrusted_data-style.php
PHP
mit
1,407
var today = new Date(); console.log(today);
johnvoon/launch_school
210/lesson5/date_ex1.js
JavaScript
mit
43
var RocketBoots = { isInitialized : false, readyFunctions : [], components : {}, loadedScripts: [], version: {full: "0.7.0", major: 0, minor: 7, patch: 0, codeName: "sun-master"}, _autoLoadRequirements: true, _initTimer : null, _MAX_ATTEMPTS : 300, _BOOTING_ELEMENT_ID : "booting-up-rocket-boots", _: null, // Lodash $: null, // jQuery //==== Classes Component : function(c){ this.fileName = c; this.name = null; this.isLoaded = false; this.isInstalled = false; }, //==== General Functions log : console.log, loadScript : function(url, callback){ //console.log("Loading script", url); // http://stackoverflow.com/a/7719185/1766230 var o = this; var s = document.createElement('script'); var r = false; var t; s.type = 'text/javascript'; s.src = "scripts/" + url + ".js"; s.className = "rocketboots-script"; s.onload = s.onreadystatechange = function() { //console.log( this.readyState ); //uncomment this line to see which ready states are called. if ( !r && (!this.readyState || this.readyState == 'complete') ) { r = true; o.loadedScripts.push(url); if (typeof callback == "function") callback(); } }; t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s, t); return this; }, //==== Component Functions hasComponent: function (componentClass) { if (typeof RocketBoots[componentClass] == "function") { return true; } else { return false; } }, installComponent : function (options, callback, attempt) { // options = { fileName, classNames, requirements, description, credits } var o = this; var mainClassName = (typeof options.classNames === 'object' && options.classNames.length > 0) ? options.classNames[0] : (options.classNames || options.className); var componentClass = options[mainClassName]; var requirements = options.requirements; var fileName = options.fileName; var callbacks = []; var i; // Setup array of callbacks if (typeof callback === 'function') { callbacks.push(callback); } if (typeof options.callback === 'function') { callbacks.push(options.callback); } if (typeof options.callbacks === 'object') { callbacks.concat(options.callbacks); } // Check for possible errors if (typeof mainClassName !== 'string') { console.error("Error installing component: mainClassName is not a string", mainClassName, options); console.log("options", options); return; } else if (typeof componentClass !== 'function') { console.error("Error installing component: class name", mainClassName, "not found on options:", options); console.log("options", options); return; } //console.log("Installing", fileName, " ...Are required components", requirements, " loaded?", o.areComponentsLoaded(requirements)); if (!o.areComponentsLoaded(requirements)) { var tryAgainDelay, compTimer; if (typeof attempt === "undefined") { attempt = 1; } else if (attempt > o._MAX_ATTEMPTS) { console.error("Could not initialize RocketBoots: too many attempts"); return false; } else { attempt++; } if (o._autoLoadRequirements) { console.log(fileName, "requires component(s)", requirements, " which aren't loaded. Autoloading..."); o.loadComponents(requirements); tryAgainDelay = 100 * attempt; } else { console.warn(fileName, "requires component(s)", requirements, " which aren't loaded."); tryAgainDelay = 5000; } compTimer = window.setTimeout(function(){ o.installComponent(options, callback, attempt); }, tryAgainDelay); } else { if (typeof o.components[fileName] == "undefined") { o.components[fileName] = new o.Component(fileName); } /* for (i = 0; i < callbacks.length; i++) { if (typeof callbacks[i] === "function") { callbacks[i](); } } */ o.components[fileName].name = mainClassName; o.components[fileName].isInstalled = true; o.components[fileName].callbacks = callbacks; // TODO: Add description and credits //o.components[fileName].description = ""; //o.components[fileName].credits = ""; o[mainClassName] = componentClass; } return this; }, getComponentByName: function (componentName) { var o = this; for (var cKey in o.components) { if (o.components[cKey].name == componentName) { return o.components[cKey]; } }; return; }, areComponentsLoaded: function (componentNameArr) { var o = this, areLoaded = true; if (typeof componentNameArr !== 'object') { return areLoaded; } for (var i = 0; i < componentNameArr.length; i++) { if (!o.isComponentInstalled(componentNameArr[i])) { areLoaded = false; } }; return areLoaded; }, isComponentInstalled: function (componentName) { var comp = this.getComponentByName(componentName); return (comp && comp.isInstalled); }, loadComponents : function(arr, path){ var o = this; var componentName; path = (typeof path === 'undefined') ? "rocketboots/" : path; for (var i = 0, al = arr.length; i < al; i++){ componentName = arr[i]; if (typeof o.components[componentName] == "undefined") { o.components[componentName] = new o.Component(componentName); o.loadScript(path + arr[i], function(){ o.components[componentName].isLoaded = true; }); } else { //console.warn("Trying to load", componentName, "component that already exists."); } } return this; }, loadCustomComponents : function (arr, path) { path = (typeof path === 'undefined') ? "" : path; return this.loadComponents(arr, path); }, areAllComponentsLoaded : function(){ var o = this; var componentCount = 0, componentsInstalledCount = 0; for (var c in o.components) { // if (o.components.hasOwnProperty(c)) { do stuff } componentCount++; if (o.components[c].isInstalled) componentsInstalledCount++; } console.log("RB Components Installed: " + componentsInstalledCount + "/" + componentCount); return (componentsInstalledCount >= componentCount); }, //==== Ready and Init Functions ready : function(callback){ if (typeof callback == "function") { if (this.isInitialized) { callback(this); } else { this.readyFunctions.push(callback); } } else { console.error("Ready argument (callback) not a function"); } return this; }, runReadyFunctions : function(){ var o = this; // Loop over readyFunctions and run each one var f, fn; for (var i = 0; o.readyFunctions.length > 0; i++){ f = o.readyFunctions.splice(i,1); fn = f[0]; fn(o); } return this; }, init : function(attempt){ var o = this; // TODO: allow dependecies to be injected rather than forcing them to be on the window scope var isJQueryUndefined = (typeof $ === "undefined"); var isLodashUndefined = (typeof _ === "undefined"); var areRequiredScriptsMissing = isJQueryUndefined || isLodashUndefined; if (typeof attempt === "undefined") { attempt = 1; } else if (attempt > o._MAX_ATTEMPTS) { console.error("Could not initialize RocketBoots: too many attempts"); return false; } else { attempt++; } //console.log("RB Init", attempt, (areRequiredScriptsMissing ? "Waiting on required objects from external scripts" : "")); if (!isJQueryUndefined) { o.$ = $; o.$('#' + o._BOOTING_ELEMENT_ID).show(); } if (!isLodashUndefined) { o._ = _; o.each = o.forEach = _.each; } function tryAgain () { // Clear previous to stop multiple inits from happening window.clearTimeout(o._initTimer); o._initTimer = window.setTimeout(function(){ o.init(attempt); }, (attempt * 10)); } // On first time through, do some things if (attempt === 1) { // Create "rb" alias if (typeof window.rb !== "undefined") { o._rb = window.rb; } window.rb = o; // Aliases o.window = window; o.document = window.document; // Load default components // TODO: make this configurable this.loadComponents(["Game"]); // Load required scripts if (isJQueryUndefined) { o.loadScript("libs/jquery-2.2.4.min", function(){ //o.init(1); }); } if (isLodashUndefined) { o.loadScript("libs/lodash.min", function(){ }); } } if (o.areAllComponentsLoaded() && !areRequiredScriptsMissing) { console.log("RB Init - All scripts and components are loaded.", o.loadedScripts, "\nRunning component callbacks..."); // TODO: These don't necessarily run in the correct order for requirements o.each(o.components, function(component){ o.each(component.callbacks, function(callback){ console.log("Callback for", component.name); callback(); // TODO: Make this run in the right context? }); }); console.log("RB Init - Running Ready functions.\n"); o.$('#' + o._BOOTING_ELEMENT_ID).hide(); o.runReadyFunctions(); o.isInitialized = true; return true; } tryAgain(); return false; } }; RocketBoots.init();
Lukenickerson/rocketboots
scripts/rocketboots/core.js
JavaScript
mit
8,886
<?php namespace ErenMustafaOzdal\LaravelModulesBase; use Illuminate\Database\Eloquent\Model; class Neighborhood extends Model { /** * The database table used by the model. * * @var string */ protected $table = 'neighborhoods'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['neighborhood']; public $timestamps = false; /* |-------------------------------------------------------------------------- | Model Relations |-------------------------------------------------------------------------- */ /** * Get the postal code of the district. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function postalCode() { return $this->hasOne('App\PostalCode'); } /* |-------------------------------------------------------------------------- | Model Set and Get Attributes |-------------------------------------------------------------------------- */ /** * get the neighborhood uc first * * @return string */ public function getNeighborhoodUcFirstAttribute() { return ucfirst_tr($this->neighborhood); } }
erenmustafaozdal/laravel-modules-base
src/Neighborhood.php
PHP
mit
1,262
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; // Key used by getwork/getblocktemplate miners. // Allocated in StartRPCThreads, free'd in StopRPCThreads CReserveKey* pMiningKey = NULL; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 5745 : 13000; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 12000000) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "Stop Netbits server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "Netbits server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe // ------------------------ ----------------------- ---------- ---------- { "help", &help, true, true }, { "stop", &stop, true, true }, { "getblockcount", &getblockcount, true, false }, { "getconnectioncount", &getconnectioncount, true, false }, { "getpeerinfo", &getpeerinfo, true, false }, { "addnode", &addnode, true, true }, { "getaddednodeinfo", &getaddednodeinfo, true, true }, { "getdifficulty", &getdifficulty, true, false }, { "getgenerate", &getgenerate, true, false }, { "setgenerate", &setgenerate, true, false }, { "gethashespersec", &gethashespersec, true, false }, { "getinfo", &getinfo, true, false }, { "getmininginfo", &getmininginfo, true, false }, { "getnewaddress", &getnewaddress, true, false }, { "getaccountaddress", &getaccountaddress, true, false }, { "setaccount", &setaccount, true, false }, { "getaccount", &getaccount, false, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false }, { "sendtoaddress", &sendtoaddress, false, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false }, { "backupwallet", &backupwallet, true, false }, { "keypoolrefill", &keypoolrefill, true, false }, { "walletpassphrase", &walletpassphrase, true, false }, { "walletpassphrasechange", &walletpassphrasechange, false, false }, { "walletlock", &walletlock, true, false }, { "encryptwallet", &encryptwallet, false, false }, { "validateaddress", &validateaddress, true, false }, { "getbalance", &getbalance, false, false }, { "move", &movecmd, false, false }, { "sendfrom", &sendfrom, false, false }, { "sendmany", &sendmany, false, false }, { "addmultisigaddress", &addmultisigaddress, false, false }, { "createmultisig", &createmultisig, true, true }, { "getrawmempool", &getrawmempool, true, false }, { "getblock", &getblock, false, false }, { "getblockhash", &getblockhash, false, false }, { "gettransaction", &gettransaction, false, false }, { "listtransactions", &listtransactions, false, false }, { "listaddressgroupings", &listaddressgroupings, false, false }, { "signmessage", &signmessage, false, false }, { "verifymessage", &verifymessage, false, false }, { "getwork", &getwork, true, false }, { "listaccounts", &listaccounts, false, false }, { "settxfee", &settxfee, false, false }, { "getblocktemplate", &getblocktemplate, true, false }, { "submitblock", &submitblock, false, false }, { "listsinceblock", &listsinceblock, false, false }, { "dumpprivkey", &dumpprivkey, true, false }, { "importprivkey", &importprivkey, false, false }, { "listunspent", &listunspent, false, false }, { "getrawtransaction", &getrawtransaction, false, false }, { "createrawtransaction", &createrawtransaction, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false }, { "signrawtransaction", &signrawtransaction, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false }, { "gettxoutsetinfo", &gettxoutsetinfo, true, false }, { "gettxout", &gettxout, true, false }, { "lockunspent", &lockunspent, false, false }, { "listlockunspent", &listlockunspent, false, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: netbits-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: netbits-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: netbits-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } else { ServiceConnection(conn); conn->close(); delete conn; } } void StartRPCThreads() { // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use netbitsd"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=netbitsrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Netbits Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl"); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } void StopRPCThreads() { delete pMiningKey; pMiningKey = NULL; if (rpc_io_service == NULL) return; rpc_io_service->stop(); rpc_worker_group->join_all(); delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
net-bits/Netbits
src/bitcoinrpc.cpp
C++
mit
46,782
#!/usr/bin/env python3 # Copyright (c) 2015-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Utilities for manipulating blocks and transactions.""" import struct import time import unittest from .address import ( key_to_p2sh_p2wpkh, key_to_p2wpkh, script_to_p2sh_p2wsh, script_to_p2wsh, ) from .messages import ( CBlock, COIN, COutPoint, CTransaction, CTxIn, CTxInWitness, CTxOut, hash256, ser_uint256, tx_from_hex, uint256_from_str, ) from .script import ( CScript, CScriptNum, CScriptOp, OP_1, OP_CHECKMULTISIG, OP_CHECKSIG, OP_RETURN, OP_TRUE, ) from .script_util import ( key_to_p2wpkh_script, script_to_p2wsh_script, ) from .util import assert_equal WITNESS_SCALE_FACTOR = 4 MAX_BLOCK_SIGOPS = 20000 MAX_BLOCK_SIGOPS_WEIGHT = MAX_BLOCK_SIGOPS * WITNESS_SCALE_FACTOR # Genesis block time (regtest) TIME_GENESIS_BLOCK = 1296688602 # Coinbase transaction outputs can only be spent after this number of new blocks (network rule) COINBASE_MATURITY = 100 # Soft-fork activation heights DERSIG_HEIGHT = 102 # BIP 66 CLTV_HEIGHT = 111 # BIP 65 CSV_ACTIVATION_HEIGHT = 432 # From BIP141 WITNESS_COMMITMENT_HEADER = b"\xaa\x21\xa9\xed" NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit"]} VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4 def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None): """Create a block (with regtest difficulty).""" block = CBlock() if tmpl is None: tmpl = {} block.nVersion = version or tmpl.get('version') or VERSIONBITS_LAST_OLD_BLOCK_VERSION block.nTime = ntime or tmpl.get('curtime') or int(time.time() + 600) block.hashPrevBlock = hashprev or int(tmpl['previousblockhash'], 0x10) if tmpl and not tmpl.get('bits') is None: block.nBits = struct.unpack('>I', bytes.fromhex(tmpl['bits']))[0] else: block.nBits = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams if coinbase is None: coinbase = create_coinbase(height=tmpl['height']) block.vtx.append(coinbase) if txlist: for tx in txlist: if not hasattr(tx, 'calc_sha256'): tx = tx_from_hex(tx) block.vtx.append(tx) block.hashMerkleRoot = block.calc_merkle_root() block.calc_sha256() return block def get_witness_script(witness_root, witness_nonce): witness_commitment = uint256_from_str(hash256(ser_uint256(witness_root) + ser_uint256(witness_nonce))) output_data = WITNESS_COMMITMENT_HEADER + ser_uint256(witness_commitment) return CScript([OP_RETURN, output_data]) def add_witness_commitment(block, nonce=0): """Add a witness commitment to the block's coinbase transaction. According to BIP141, blocks with witness rules active must commit to the hash of all in-block transactions including witness.""" # First calculate the merkle root of the block's # transactions, with witnesses. witness_nonce = nonce witness_root = block.calc_witness_merkle_root() # witness_nonce should go to coinbase witness. block.vtx[0].wit.vtxinwit = [CTxInWitness()] block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(witness_nonce)] # witness commitment is the last OP_RETURN output in coinbase block.vtx[0].vout.append(CTxOut(0, get_witness_script(witness_root, witness_nonce))) block.vtx[0].rehash() block.hashMerkleRoot = block.calc_merkle_root() block.rehash() def script_BIP34_coinbase_height(height): if height <= 16: res = CScriptOp.encode_op_n(height) # Append dummy to increase scriptSig size above 2 (see bad-cb-length consensus rule) return CScript([res, OP_1]) return CScript([CScriptNum(height)]) def create_coinbase(height, pubkey=None, extra_output_script=None, fees=0, nValue=50): """Create a coinbase transaction. If pubkey is passed in, the coinbase output will be a P2PK output; otherwise an anyone-can-spend output. If extra_output_script is given, make a 0-value output to that script. This is useful to pad block weight/sigops as needed. """ coinbase = CTransaction() coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff), script_BIP34_coinbase_height(height), 0xffffffff)) coinbaseoutput = CTxOut() coinbaseoutput.nValue = nValue * COIN if nValue == 50: halvings = int(height / 150) # regtest coinbaseoutput.nValue >>= halvings coinbaseoutput.nValue += fees if pubkey is not None: coinbaseoutput.scriptPubKey = CScript([pubkey, OP_CHECKSIG]) else: coinbaseoutput.scriptPubKey = CScript([OP_TRUE]) coinbase.vout = [coinbaseoutput] if extra_output_script is not None: coinbaseoutput2 = CTxOut() coinbaseoutput2.nValue = 0 coinbaseoutput2.scriptPubKey = extra_output_script coinbase.vout.append(coinbaseoutput2) coinbase.calc_sha256() return coinbase def create_tx_with_script(prevtx, n, script_sig=b"", *, amount, script_pub_key=CScript()): """Return one-input, one-output transaction object spending the prevtx's n-th output with the given amount. Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output. """ tx = CTransaction() assert n < len(prevtx.vout) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff)) tx.vout.append(CTxOut(amount, script_pub_key)) tx.calc_sha256() return tx def create_transaction(node, txid, to_address, *, amount): """ Return signed transaction spending the first output of the input txid. Note that the node must have a wallet that can sign for the output that is being spent. """ raw_tx = create_raw_transaction(node, txid, to_address, amount=amount) tx = tx_from_hex(raw_tx) return tx def create_raw_transaction(node, txid, to_address, *, amount): """ Return raw signed transaction spending the first output of the input txid. Note that the node must have a wallet that can sign for the output that is being spent. """ psbt = node.createpsbt(inputs=[{"txid": txid, "vout": 0}], outputs={to_address: amount}) for _ in range(2): for w in node.listwallets(): wrpc = node.get_wallet_rpc(w) signed_psbt = wrpc.walletprocesspsbt(psbt) psbt = signed_psbt['psbt'] final_psbt = node.finalizepsbt(psbt) assert_equal(final_psbt["complete"], True) return final_psbt['hex'] def get_legacy_sigopcount_block(block, accurate=True): count = 0 for tx in block.vtx: count += get_legacy_sigopcount_tx(tx, accurate) return count def get_legacy_sigopcount_tx(tx, accurate=True): count = 0 for i in tx.vout: count += i.scriptPubKey.GetSigOpCount(accurate) for j in tx.vin: # scriptSig might be of type bytes, so convert to CScript for the moment count += CScript(j.scriptSig).GetSigOpCount(accurate) return count def witness_script(use_p2wsh, pubkey): """Create a scriptPubKey for a pay-to-witness TxOut. This is either a P2WPKH output for the given pubkey, or a P2WSH output of a 1-of-1 multisig for the given pubkey. Returns the hex encoding of the scriptPubKey.""" if not use_p2wsh: # P2WPKH instead pkscript = key_to_p2wpkh_script(pubkey) else: # 1-of-1 multisig witness_script = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG]) pkscript = script_to_p2wsh_script(witness_script) return pkscript.hex() def create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount): """Return a transaction (in hex) that spends the given utxo to a segwit output. Optionally wrap the segwit output using P2SH.""" if use_p2wsh: program = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG]) addr = script_to_p2sh_p2wsh(program) if encode_p2sh else script_to_p2wsh(program) else: addr = key_to_p2sh_p2wpkh(pubkey) if encode_p2sh else key_to_p2wpkh(pubkey) if not encode_p2sh: assert_equal(node.getaddressinfo(addr)['scriptPubKey'], witness_script(use_p2wsh, pubkey)) return node.createrawtransaction([utxo], {addr: amount}) def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""): """Create a transaction spending a given utxo to a segwit output. The output corresponds to the given pubkey: use_p2wsh determines whether to use P2WPKH or P2WSH; encode_p2sh determines whether to wrap in P2SH. sign=True will have the given node sign the transaction. insert_redeem_script will be added to the scriptSig, if given.""" tx_to_witness = create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount) if (sign): signed = node.signrawtransactionwithwallet(tx_to_witness) assert "errors" not in signed or len(["errors"]) == 0 return node.sendrawtransaction(signed["hex"]) else: if (insert_redeem_script): tx = tx_from_hex(tx_to_witness) tx.vin[0].scriptSig += CScript([bytes.fromhex(insert_redeem_script)]) tx_to_witness = tx.serialize().hex() return node.sendrawtransaction(tx_to_witness) class TestFrameworkBlockTools(unittest.TestCase): def test_create_coinbase(self): height = 20 coinbase_tx = create_coinbase(height=height) assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), height)
yenliangl/bitcoin
test/functional/test_framework/blocktools.py
Python
mit
9,688
#include "StdAfx.h" #include "Distance Joint Description.h" #include "Spring Description.h" #include "Distance Joint.h" #include <NxDistanceJointDesc.h> using namespace StillDesign::PhysX; DistanceJointDescription::DistanceJointDescription() : JointDescription( new NxDistanceJointDesc() ) { } DistanceJointDescription::DistanceJointDescription( NxDistanceJointDesc* desc ) : JointDescription( desc ) { } float DistanceJointDescription::MinimumDistance::get() { return this->UnmanagedPointer->minDistance; } void DistanceJointDescription::MinimumDistance::set( float value ) { this->UnmanagedPointer->minDistance = value; } float DistanceJointDescription::MaximumDistance::get() { return this->UnmanagedPointer->maxDistance; } void DistanceJointDescription::MaximumDistance::set( float value ) { this->UnmanagedPointer->maxDistance = value; } SpringDescription DistanceJointDescription::Spring::get() { return (SpringDescription)this->UnmanagedPointer->spring; } void DistanceJointDescription::Spring::set( SpringDescription value ) { this->UnmanagedPointer->spring = (NxSpringDesc)value; } DistanceJointFlag DistanceJointDescription::Flags::get() { return (DistanceJointFlag)this->UnmanagedPointer->flags; } void DistanceJointDescription::Flags::set( DistanceJointFlag value ) { this->UnmanagedPointer->flags = (NxDistanceJointFlag)value; } NxDistanceJointDesc* DistanceJointDescription::UnmanagedPointer::get() { return (NxDistanceJointDesc*)JointDescription::UnmanagedPointer; }
danteinforno/PhysX.Net
PhysX.Net/PhysX.Net/Source/Distance Joint Description.cpp
C++
mit
1,564
using UnityEngine; using UnityEditor; using System.Collections; using UForms.Attributes; namespace UForms.Controls.Fields { /// <summary> /// /// </summary> [ExposeControl( "Object Field", "Fields" )] public class ObjectField : AbstractField< Object > { /// <summary> /// /// </summary> protected override Vector2 DefaultSize { get { return new Vector2( 200.0f, 16.0f ); } } /// <summary> /// /// </summary> protected override bool UseBackingFieldChangeDetection { get { return true; } } /// <summary> /// /// </summary> public System.Type Type { get; set; } /// <summary> /// /// </summary> public bool AllowSceneObjects { get; set; } public ObjectField() : base () { } /// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="allowSceneObjects"></param> /// <param name="value"></param> /// <param name="label"></param> public ObjectField( System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( value, label ) { Type = type; AllowSceneObjects = allowSceneObjects; } /// <summary> /// /// </summary> /// <param name="position"></param> /// <param name="size"></param> /// <param name="type"></param> /// <param name="allowSceneObjects"></param> /// <param name="value"></param> /// <param name="label"></param> public ObjectField( Vector2 position, Vector2 size, System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( position, size, value, label ) { Type = type; AllowSceneObjects = allowSceneObjects; } /// <summary> /// /// </summary> /// <returns></returns> protected override Object DrawAndUpdateValue() { return EditorGUI.ObjectField( ScreenRect, Label, m_cachedValue, Type, AllowSceneObjects ); } /// <summary> /// /// </summary> /// <param name="oldval"></param> /// <param name="newval"></param> /// <returns></returns> protected override bool TestValueEquality( Object oldval, Object newval ) { if ( oldval == null || newval == null ) { if ( oldval == null && newval == null ) { return true; } return false; } return oldval.Equals( newval ); } } }
kilguril/UForms
Assets/UForms/Runtime/Editor/Controls/Fields/ObjectField.cs
C#
mit
2,890
using Microsoft.AspNetCore.Http; using System.Linq; using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Primitives; using System.Globalization; namespace TCPServer.ServerImplemetation { class TCPRequest : HttpRequest { private TCPRequest() { } public static async Task<TCPRequest> Parse(TCPStream input, bool includeHeaders) { var r = new TCPRequest(); await r.ParseCore(input, includeHeaders).ConfigureAwait(false); return r; } private async Task ParseCore(TCPStream stream, bool includeHeaders) { Method = await stream.ReadStringAync().ConfigureAwait(false); var requestUri = await stream.ReadStringAync().ConfigureAwait(false); var uri = new Uri(requestUri); Scheme = uri.Scheme; IsHttps = false; Host = new HostString(uri.Host, uri.Port); PathBase = new PathString(uri.AbsolutePath); Path = new PathString(uri.AbsolutePath); QueryString = new QueryString(uri.Query); Query = new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query)); Protocol = "http"; if(includeHeaders) { var headers = new List<Tuple<string, string>>(); var headersCount = await stream.ReadVarIntAsync().ConfigureAwait(false); for(int i = 0; i < (int)headersCount; i++) { var key = await stream.ReadStringAync().ConfigureAwait(false); var value = await stream.ReadStringAync().ConfigureAwait(false); headers.Add(Tuple.Create(key, value)); } foreach(var h in headers.GroupBy(g => g.Item1, g => g.Item2)) { Headers.Add(h.Key, new StringValues(h.ToArray())); } } var hasContent = (await stream.ReadVarIntAsync().ConfigureAwait(false)) == 1; if(hasContent) { var buffer = await stream.ReadBytesAync(TCPStream.ReadType.ManagedPool).ConfigureAwait(false); Body = new MemoryStream(buffer.Array); Body.SetLength(buffer.Count); ContentLength = buffer.Count; } } HttpContext _HttpContext; public void SetHttpContext(HttpContext context) { if(context == null) throw new ArgumentNullException(nameof(context)); _HttpContext = context; } public override HttpContext HttpContext => _HttpContext; public override string Method { get; set; } public override string Scheme { get; set; } public override bool IsHttps { get; set; } public override HostString Host { get; set; } public override PathString PathBase { get; set; } public override PathString Path { get; set; } public override QueryString QueryString { get; set; } public override IQueryCollection Query { get; set; } public override string Protocol { get; set; } IHeaderDictionary _Headers = new HeaderDictionary(); public override IHeaderDictionary Headers => _Headers; public override IRequestCookieCollection Cookies { get; set; } = new RequestCookieCollection(); public override long? ContentLength { get { StringValues value; if(!Headers.TryGetValue("Content-Length", out value)) return null; return long.Parse(value.FirstOrDefault(), CultureInfo.InvariantCulture); } set { Headers.Remove("Content-Length"); if(value != null) Headers.Add("Content-Length", value.Value.ToString(CultureInfo.InvariantCulture)); } } public override string ContentType { get { StringValues value; if(!Headers.TryGetValue("Content-Type", out value)) return null; return value.FirstOrDefault(); } set { Headers.Remove("Content-Type"); if(value != null) Headers.Add("Content-Type", new StringValues(value)); } } public override Stream Body { get; set; } public override bool HasFormContentType => false; public override IFormCollection Form { get; set; } FormCollection _ReadFormAsync = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>()); public override Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult<IFormCollection>(_ReadFormAsync); } } }
stratisproject/TCPServer
TCPServer/ServerImplemetation/TCPRequest.cs
C#
mit
4,306
from .DiscreteFactor import State, DiscreteFactor from .CPD import TabularCPD from .JointProbabilityDistribution import JointProbabilityDistribution __all__ = ['TabularCPD', 'DiscreteFactor', 'State' ]
khalibartan/pgmpy
pgmpy/factors/discrete/__init__.py
Python
mit
236
/* Ql builtin and external frmt command. format text */ package frmt import ( "clive/cmd" "clive/cmd/opt" "clive/nchan" "clive/zx" "errors" "fmt" "io" "strings" "unicode" ) type parFmt { rc chan string ec chan bool } func startPar(out io.Writer, indent0, indent string, max int) *parFmt { rc := make(chan string) ec := make(chan bool, 1) wc := make(chan string) pf := &parFmt{rc, ec} go func() { for s := range rc { if s == "\n" { wc <- s continue } words := strings.Fields(strings.TrimSpace(s)) for _, w := range words { wc <- w } } close(wc) }() go func() { pos, _ := fmt.Fprintf(out, "%s", indent0) firstword := true lastword := "x" for w := range wc { if len(w) == 0 { continue } if w == "\n" { fmt.Fprintf(out, "\n") firstword = true pos = 0 continue } if pos+len(w)+1 > max { fmt.Fprintf(out, "\n") pos, _ = fmt.Fprintf(out, "%s", indent) firstword = true } if !firstword && len(w)>0 && !unicode.IsPunct(rune(w[0])) { lastr := rune(lastword[len(lastword)-1]) if !strings.ContainsRune("([{", lastr) { fmt.Fprintf(out, " ") pos++ } } fmt.Fprintf(out, "%s", w) pos += len(w) firstword = false lastword = w } if !firstword { fmt.Fprintf(out, "\n") } close(ec) }() return pf } func (pf *parFmt) WriteString(s string) { pf.rc <- s } func (pf *parFmt) Close() { if pf == nil { return } close(pf.rc) <-pf.ec } type xCmd { *cmd.Ctx *opt.Flags wid int } func tabsOf(s string) int { for i := 0; i < len(s); i++ { if s[i] != '\t' { return i } } return 0 } func (x *xCmd) RunFile(d zx.Dir, dc <-chan []byte) error { if dc == nil { return nil } rc := nchan.Lines(dc, '\n') var pf *parFmt ntabs := 0 tabs := "" doselect { case <-x.Intrc: close(rc, "interrupted") pf.Close() return errors.New("interrupted") case s, ok := <-rc: if !ok { pf.Close() return cerror(rc) } if s=="\n" || s=="" { pf.Close() pf = nil x.Printf("\n") continue } nt := tabsOf(s) if nt != ntabs { pf.Close() pf = nil ntabs = nt tabs = strings.Repeat("\t", ntabs) } if pf == nil { pf = startPar(x.Stdout, tabs, tabs, x.wid) } pf.WriteString(s) } pf.Close() if err := cerror(rc); err != nil { return err } return nil } func Run(c cmd.Ctx) (err error) { argv := c.Args x := &xCmd{Ctx: &c} x.Flags = opt.New("{file}") x.Argv0 = argv[0] x.NewFlag("w", "wid: set max line width", &x.wid) args, err := x.Parse(argv) if err != nil { x.Usage(x.Stderr) return err } if x.wid < 10 { x.wid = 70 } if cmd.Ns == nil { cmd.MkNS() } return cmd.RunFiles(x, args...) }
sbinet-staging/clive
cmd/oldql/frmt/frmt.go
GO
mit
2,706
({ baseUrl: "../linesocial/public/js", paths: { jquery: "public/js/libs/jquery-1.9.1.js" }, name: "main", out: "main-built.js" })
jackygrahamez/LineSocialPublic
build.js
JavaScript
mit
157
<?php namespace Usolv\TrackingBundle\Form\Model; use Doctrine\Common\Collections\ArrayCollection; class TimeRecordSearch { protected $project; public function setProject($project) { $this->project = $project; return $this; } public function getProject() { return $this->project; } }
LeQuangAnh/USVTracking
src/Usolv/TrackingBundle/Form/Model/TimeRecordSearch.php
PHP
mit
325
from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout from django import forms from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.db import transaction from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from django_filters import FilterSet from easy_select2 import Select2 from crispy_layout_mixin import form_actions, to_row from utils import (TIPO_TELEFONE, YES_NO_CHOICES, get_medicos, get_or_create_grupo) from .models import Especialidade, EspecialidadeMedico, Usuario class EspecialidadeMedicoFilterSet(FilterSet): class Meta: model = EspecialidadeMedico fields = ['especialidade'] def __init__(self, *args, **kwargs): super(EspecialidadeMedicoFilterSet, self).__init__(*args, **kwargs) row1 = to_row([('especialidade', 12)]) self.form.helper = FormHelper() self.form.helper.form_method = 'GET' self.form.helper.layout = Layout( Fieldset(_('Pesquisar Médico'), row1, form_actions(save_label='Filtrar')) ) class MudarSenhaForm(forms.Form): nova_senha = forms.CharField( label="Nova Senha", max_length=30, widget=forms.PasswordInput( attrs={'class': 'form-control form-control-lg', 'name': 'senha', 'placeholder': 'Nova Senha'})) confirmar_senha = forms.CharField( label="Confirmar Senha", max_length=30, widget=forms.PasswordInput( attrs={'class': 'form-control form-control-lg', 'name': 'confirmar_senha', 'placeholder': 'Confirmar Senha'})) class LoginForm(AuthenticationForm): username = forms.CharField( label="Username", max_length=30, widget=forms.TextInput( attrs={'class': 'form-control form-control-lg', 'name': 'username', 'placeholder': 'Usuário'})) password = forms.CharField( label="Password", max_length=30, widget=forms.PasswordInput( attrs={'class': 'form-control', 'name': 'password', 'placeholder': 'Senha'})) class UsuarioForm(ModelForm): # Usuário password = forms.CharField( max_length=20, label=_('Senha'), widget=forms.PasswordInput()) password_confirm = forms.CharField( max_length=20, label=_('Confirmar Senha'), widget=forms.PasswordInput()) class Meta: model = Usuario fields = ['username', 'email', 'nome', 'password', 'password_confirm', 'data_nascimento', 'sexo', 'plano', 'tipo', 'cep', 'end', 'numero', 'complemento', 'bairro', 'referencia', 'primeiro_telefone', 'segundo_telefone'] widgets = {'email': forms.TextInput( attrs={'style': 'text-transform:lowercase;'})} def __init__(self, *args, **kwargs): super(UsuarioForm, self).__init__(*args, **kwargs) self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone' self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone' def valida_igualdade(self, texto1, texto2, msg): if texto1 != texto2: raise ValidationError(msg) return True def clean(self): if ('password' not in self.cleaned_data or 'password_confirm' not in self.cleaned_data): raise ValidationError(_('Favor informar senhas atuais ou novas')) msg = _('As senhas não conferem.') self.valida_igualdade( self.cleaned_data['password'], self.cleaned_data['password_confirm'], msg) try: validate_password(self.cleaned_data['password']) except ValidationError as error: raise ValidationError(error) return self.cleaned_data @transaction.atomic def save(self, commit=False): usuario = super(UsuarioForm, self).save(commit) # Cria User u = User.objects.create(username=usuario.username, email=usuario.email) u.set_password(self.cleaned_data['password']) u.is_active = True u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao)) u.save() usuario.user = u usuario.save() return usuario class UsuarioEditForm(ModelForm): # Primeiro Telefone primeiro_tipo = forms.ChoiceField( widget=forms.Select(), choices=TIPO_TELEFONE, label=_('Tipo Telefone')) primeiro_ddd = forms.CharField(max_length=2, label=_('DDD')) primeiro_numero = forms.CharField(max_length=10, label=_('Número')) primeiro_principal = forms.TypedChoiceField( widget=forms.Select(), label=_('Telefone Principal?'), choices=YES_NO_CHOICES) # Primeiro Telefone segundo_tipo = forms.ChoiceField( required=False, widget=forms.Select(), choices=TIPO_TELEFONE, label=_('Tipo Telefone')) segundo_ddd = forms.CharField(required=False, max_length=2, label=_('DDD')) segundo_numero = forms.CharField( required=False, max_length=10, label=_('Número')) segundo_principal = forms.ChoiceField( required=False, widget=forms.Select(), label=_('Telefone Principal?'), choices=YES_NO_CHOICES) class Meta: model = Usuario fields = ['username', 'email', 'nome', 'data_nascimento', 'sexo', 'plano', 'tipo', 'cep', 'end', 'numero', 'complemento', 'bairro', 'referencia', 'primeiro_telefone', 'segundo_telefone'] widgets = {'username': forms.TextInput(attrs={'readonly': 'readonly'}), 'email': forms.TextInput( attrs={'style': 'text-transform:lowercase;'}), } def __init__(self, *args, **kwargs): super(UsuarioEditForm, self).__init__(*args, **kwargs) self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone' self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone' def valida_igualdade(self, texto1, texto2, msg): if texto1 != texto2: raise ValidationError(msg) return True def clean_primeiro_numero(self): cleaned_data = self.cleaned_data telefone = Telefone() telefone.tipo = self.data['primeiro_tipo'] telefone.ddd = self.data['primeiro_ddd'] telefone.numero = self.data['primeiro_numero'] telefone.principal = self.data['primeiro_principal'] cleaned_data['primeiro_telefone'] = telefone return cleaned_data def clean_segundo_numero(self): cleaned_data = self.cleaned_data telefone = Telefone() telefone.tipo = self.data['segundo_tipo'] telefone.ddd = self.data['segundo_ddd'] telefone.numero = self.data['segundo_numero'] telefone.principal = self.data['segundo_principal'] cleaned_data['segundo_telefone'] = telefone return cleaned_data @transaction.atomic def save(self, commit=False): usuario = super(UsuarioEditForm, self).save(commit) # Primeiro telefone tel = usuario.primeiro_telefone tel.tipo = self.data['primeiro_tipo'] tel.ddd = self.data['primeiro_ddd'] tel.numero = self.data['primeiro_numero'] tel.principal = self.data['primeiro_principal'] tel.save() usuario.primeiro_telefone = tel # Segundo telefone tel = usuario.segundo_telefone if tel: tel.tipo = self.data['segundo_tipo'] tel.ddd = self.data['segundo_ddd'] tel.numero = self.data['segundo_numero'] tel.principal = self.data['segundo_principal'] tel.save() usuario.segundo_telefone = tel # User u = usuario.user u.email = usuario.email u.groups.remove(u.groups.first()) u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao)) u.save() usuario.save() return usuario class EspecialidadeMedicoForm(ModelForm): medico = forms.ModelChoiceField( queryset=get_medicos(), widget=Select2(select2attrs={'width': '535px'})) especialidade = forms.ModelChoiceField( queryset=Especialidade.objects.all(), widget=Select2(select2attrs={'width': '535px'})) class Meta: model = EspecialidadeMedico fields = ['especialidade', 'medico']
eduardoedson/scp
usuarios/forms.py
Python
mit
8,823
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Freeform - Control Panel * * The Control Panel master class that handles all of the CP requests and displaying. * * @package Solspace:Freeform * @author Solspace, Inc. * @copyright Copyright (c) 2008-2014, Solspace, Inc. * @link http://solspace.com/docs/freeform * @license http://www.solspace.com/license_agreement * @version 4.1.7 * @filesource freeform/mcp.freeform.php */ if ( ! class_exists('Module_builder_freeform')) { require_once 'addon_builder/module_builder.php'; } class Freeform_mcp extends Module_builder_freeform { private $migration_batch_limit = 100; private $pro_update = FALSE; // -------------------------------------------------------------------- /** * Constructor * * @access public * @param bool Enable calling of methods based on URI string * @return string */ public function __construct( $switch = TRUE ) { parent::__construct(); // Install or Uninstall Request if ((bool) $switch === FALSE) return; if ( ! function_exists('lang')) { ee()->load->helper('language'); } // -------------------------------------------- // Module Menu Items // -------------------------------------------- $menu = array( 'module_forms' => array( 'link' => $this->base, 'title' => lang('forms') ), 'module_fields' => array( 'link' => $this->base . AMP . 'method=fields', 'title' => lang('fields') ), 'module_fieldtypes' => array( 'link' => $this->base . AMP . 'method=fieldtypes', 'title' => lang('fieldtypes') ), 'module_notifications' => array( 'link' => $this->base . AMP . 'method=notifications', 'title' => lang('notifications') ), /*'module_export' => array( 'link' => $this->base . AMP . 'method=export', 'title' => lang('export') ),*/ 'module_utilities' => array( 'link' => $this->base . AMP . 'method=utilities', 'title' => lang('utilities') ), 'module_preferences' => array( 'link' => $this->base . AMP . 'method=preferences', 'title' => lang('preferences') ), 'module_documentation' => array( 'link' => FREEFORM_DOCS_URL, 'title' => lang('help'), 'new_window' => TRUE ), ); $this->cached_vars['lang_module_version'] = lang('freeform_module_version'); $this->cached_vars['module_version'] = FREEFORM_VERSION; $this->cached_vars['module_menu_highlight'] = 'module_forms'; $this->cached_vars['inner_nav_links'] = array(); // ------------------------------------- // css includes. WOOT! // ------------------------------------- $this->cached_vars['cp_stylesheet'] = array( 'chosen', 'standard_cp' ); $this->cached_vars['cp_javascript'] = array( 'standard_cp.min', 'chosen.jquery.min' ); // ------------------------------------- // custom CP? // ------------------------------------- $debug_normal = (ee()->input->get_post('debug_normal') !== FALSE); $is_crappy_ie_version = FALSE; $ua = strtolower($_SERVER['HTTP_USER_AGENT']); if (stristr($ua, 'msie 6') OR stristr($ua, 'msie 7') OR stristr($ua, 'msie 8')) { //technically this should be true for any IE version, but... $is_crappy_ie_version = TRUE; } if ( ! $debug_normal AND ! $is_crappy_ie_version AND ! $this->check_no($this->preference('use_solspace_mcp_style'))) { $this->cached_vars['cp_stylesheet'][] = 'custom_cp'; } //avoids AR collisions $this->data->get_module_preferences(); $this->data->get_global_module_preferences(); $this->data->show_all_sites(); // ------------------------------------- // run upgrade or downgrade scripts // ------------------------------------- if (FREEFORM_PRO AND $this->data->global_preference('ffp') === 'n' OR ! FREEFORM_PRO AND $this->data->global_preference('ffp') === 'y') { $_GET['method'] = 'freeform_module_update'; $this->pro_update = TRUE; } $this->cached_vars['module_menu'] = $menu; } // END Freeform_cp_base() //--------------------------------------------------------------------- // begin views //--------------------------------------------------------------------- // -------------------------------------------------------------------- /** * Module's Main Homepage * * @access public * @param string * @return null */ public function index ($message='') { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } return $this->forms($message); } // END index() // -------------------------------------------------------------------- /** * My Forms * * @access public * @param string $message incoming message for flash data * @return string html output */ public function forms($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $new_form_link = $this->mod_link(array( 'method' => 'edit_form' )); $this->cached_vars['new_form_link'] = $new_form_link; $this->add_crumb( lang('forms') ); $this->freeform_add_right_link(lang('new_form'), $new_form_link); $this->set_highlight('module_forms'); //-------------------------------------- // start vars //-------------------------------------- $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; // ------------------------------------- // pagination? // ------------------------------------- ee()->load->model('freeform_form_model'); if ( ! $this->data->show_all_sites()) { ee()->freeform_form_model->where( 'site_id', ee()->config->item('site_id') ); } $total_results = ee()->freeform_form_model->count(array(), FALSE); // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); $url = $this->mod_link(array( 'method' => 'forms' )); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $url), 'query_string_segment' => 'row' )); ee()->freeform_form_model->limit( $row_limit, $pagination_data['pagination_page'] ); $paginate = $pagination_data['pagination_links']; } ee()->freeform_form_model->order_by('form_label'); $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // Did they upgrade from FF3? // ------------------------------------- $this->cached_vars['legacy'] = FALSE; $this->cached_vars['migrate_link'] = ''; ee()->load->library('freeform_migration'); if ( ee()->freeform_migration->legacy() === TRUE ) { $this->cached_vars['legacy'] = TRUE; $this->cached_vars['migrate_link'] = $this->mod_link(array('method' => 'utilities')); } // ------------------------------------- // data // ------------------------------------- $rows = ee()->freeform_form_model->get(); $form_data = array(); if ($rows !== FALSE) { // ------------------------------------- // check for composer for each form // ------------------------------------- $form_ids = array(); $potential_composer_ids = array(); foreach ($rows as $row) { $form_ids[] = $row['form_id']; if ($this->is_positive_intlike($row['composer_id'])) { $potential_composer_ids[$row['form_id']] = $row['composer_id']; } } $has_composer = array(); if ( ! empty($potential_composer_ids)) { ee()->load->model('freeform_composer_model'); $composer_ids = ee()->freeform_composer_model ->key('composer_id', 'composer_id') ->where('preview !=', 'y') ->where_in( 'composer_id', array_values($potential_composer_ids) ) ->get(); if ( ! empty($composer_ids)) { foreach ($potential_composer_ids as $form_id => $composer_id) { if (in_array($composer_id, $composer_ids)) { $has_composer[$form_id] = $composer_id; } } } } // ------------------------------------- // suppliment rows // ------------------------------------- foreach ($rows as $row) { $row['submissions_count'] = ( $this->data->get_form_submissions_count($row['form_id']) ); $row['moderate_count'] = ( $this->data->get_form_needs_moderation_count($row['form_id']) ); $row['has_composer'] = isset( $has_composer[$row['form_id']] ); // ------------------------------------- // piles o' links // ------------------------------------- $row['form_submissions_link'] = $this->mod_link(array( 'method' => 'entries', 'form_id' => $row['form_id'] )); $row['form_moderate_link'] = $this->mod_link(array( 'method' => 'moderate_entries', 'form_id' => $row['form_id'], 'search_status' => 'pending' )); $row['form_edit_composer_link'] = $this->mod_link(array( 'method' => 'form_composer', 'form_id' => $row['form_id'] )); $row['form_settings_link'] = $this->mod_link(array( 'method' => 'edit_form', 'form_id' => $row['form_id'] )); $row['form_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_form', 'duplicate_id' => $row['form_id'] )); $row['form_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_form', 'form_id' => $row['form_id'] )); $form_data[] = $row; } } $this->cached_vars['form_data'] = $form_data; $this->cached_vars['form_url'] = $this->mod_link(array( 'method' => 'delete_confirm_form' )); // ---------------------------------------- // Load vars // ---------------------------------------- // ------------------------------------- // JS // ------------------------------------- ee()->cp->add_js_script( array('plugin' => array('tooltip', 'dataTables')) ); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'forms.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END forms // -------------------------------------------------------------------- /** * delete_confirm_form * * @access public * @return string */ public function delete_confirm_form () { $form_ids = ee()->input->get_post('form_id', TRUE); if ( ! is_array($form_ids) AND ! $this->is_positive_intlike($form_ids) ) { $this->actions()->full_stop(lang('no_form_ids_submitted')); } //already checked for numeric :p if ( ! is_array($form_ids)) { $form_ids = array($form_ids); } return $this->delete_confirm( 'delete_forms', array('form_ids' => $form_ids), 'delete_form_confirmation' ); } //END delete_confirm_form // -------------------------------------------------------------------- /** * delete_forms * * @access public * @return string */ public function delete_forms ($form_ids = array()) { $message = 'delete_form_success'; if ( empty($form_ids) ) { $form_ids = ee()->input->get_post('form_ids'); } if ( ! is_array($form_ids) AND $this->is_positive_intlike($form_ids)) { $form_ids = array($form_ids); } //if everything is all nice and array like, DELORT //but one last check on each item to make sure its a number if ( is_array($form_ids)) { ee()->load->library('freeform_forms'); foreach ($form_ids as $form_id) { if ($this->is_positive_intlike($form_id)) { ee()->freeform_forms->delete_form($form_id); } } } //the voyage home ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => $message ))); } //END delete_forms // -------------------------------------------------------------------- /** * Edit Form * * @access public * @return string html output */ public function edit_form () { // ------------------------------------- // form ID? we must be editing // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $update = $this->cached_vars['update'] = ($form_id != 0); // ------------------------------------- // default data // ------------------------------------- $inputs = array( 'form_id' => '0', 'form_name' => '', 'form_label' => '', 'default_status' => $this->data->defaults['default_form_status'], 'notify_admin' => 'n', 'notify_user' => 'n', 'user_email_field' => '', 'user_notification_id' => '0', 'admin_notification_id' => '0', 'admin_notification_email' => ee()->config->item('webmaster_email'), 'form_description' => '', 'template_id' => '0', 'composer_id' => '0', 'field_ids' => '', 'field_order' => '', ); // ------------------------------------- // updating? // ------------------------------------- if ($update) { $form_data = $this->data->get_form_info($form_id); if ($form_data) { foreach ($form_data as $key => $value) { if ($key == 'admin_notification_email') { $value = str_replace('|', ', ', $value); } if ($key == 'field_ids') { $value = ( ! empty($value)) ? implode('|', $value) : ''; } $inputs[$key] = form_prep($value); } } else { $this->actions()->full_stop(lang('invalid_form_id')); } } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( $update ? lang('update_form') . ': ' . $form_data['form_label'] : lang('new_form') ); $this->set_highlight('module_forms'); // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $this->cached_vars['duplicate_id'] = $duplicate_id; $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $form_data = $this->data->get_form_info($duplicate_id); if ($form_data) { foreach ($form_data as $key => $value) { if (in_array($key, array('form_id', 'form_label', 'form_name'))) { continue; } if ($key == 'field_ids') { $value = ( ! empty($value)) ? implode('|', $value) : ''; } if ($key == 'admin_notification_email') { $value = str_replace('|', ', ', $value); } $inputs[$key] = form_prep($value); } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $form_data['form_label']; } } if (isset($form_data['field_ids']) AND ! empty($form_data['field_ids']) AND isset($form_data['field_order']) AND ! empty($form_data['field_order'])) { $field_ids = $form_data['field_ids']; if ( ! is_array($field_ids)) { $field_ids = $this->actions()->pipe_split($field_ids); } $field_order = $form_data['field_order']; if ( ! is_array($field_order)) { $field_order = $this->actions()->pipe_split($field_order); } $missing_ids = array_diff($field_ids, $field_order); $inputs['field_order'] = implode('|', array_merge($field_order, $missing_ids)); } // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } // ------------------------------------- // select boxes // ------------------------------------- $this->cached_vars['statuses'] = $this->data->get_form_statuses(); ee()->load->model('freeform_field_model'); $available_fields = ee()->freeform_field_model->get(); $available_fields = ($available_fields !== FALSE) ? $available_fields : array(); //fields $this->cached_vars['available_fields'] = $available_fields; //notifications $this->cached_vars['notifications'] = $this->data->get_available_notification_templates(); // ------------------------------------- // user email fields // ------------------------------------- $user_email_fields = array('' => lang('choose_user_email_field')); $f_rows = ee()->freeform_field_model ->select('field_id, field_label, settings') ->get(array('field_type' => 'text')); //we only want fields that are being validated as email if ($f_rows) { foreach ($f_rows as $row) { $row_settings = json_decode($row['settings'], TRUE); $row_settings = (is_array($row_settings)) ? $row_settings : array(); if (isset($row_settings['field_content_type']) AND $row_settings['field_content_type'] == 'email') { $user_email_fields[$row['field_id']] = $row['field_label']; } } } $this->cached_vars['user_email_fields'] = $user_email_fields; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_form' )); // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; ee()->cp->add_js_script(array( 'ui' => array('draggable', 'droppable', 'sortable') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'edit_form.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_form // -------------------------------------------------------------------- /** * form composer * * ajax form and field builder * * @access public * @param string message lang line * @return string html output */ public function form_composer ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; // ------------------------------------- // form_id // ------------------------------------- $form_id = ee()->input->get_post('form_id', TRUE); $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $update = $form_data['composer_id'] != 0; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->base ); $this->add_crumb( lang('composer') . ': ' . $form_data['form_label'] ); $this->set_highlight('module_forms'); // ------------------------------------- // data // ------------------------------------- $this->cached_vars['form_data'] = $form_data; // ------------------------------------- // fields for composer // ------------------------------------- ee()->load->model('freeform_field_model'); $available_fields = ee()->freeform_field_model ->where('composer_use', 'y') ->order_by('field_label') ->key('field_name') ->get(); $available_fields = ($available_fields !== FALSE) ? $available_fields : array(); // ------------------------------------- // templates // ------------------------------------- ee()->load->model('freeform_template_model'); $available_templates = ee()->freeform_template_model ->where('enable_template', 'y') ->order_by('template_label') ->key('template_id', 'template_label') ->get(); $available_templates = ($available_templates !== FALSE) ? $available_templates : array(); // ------------------------------------- // get field output for composer // ------------------------------------- ee()->load->library('freeform_fields'); $field_composer_output = array(); $field_id_list = array(); foreach ($available_fields as $field_name => $field_data) { $field_id_list[$field_data['field_id']] = $field_name; //encode to keep JS from running //camel case because its exposed in JS $field_composer_output[$field_name] = $this->composer_field_data( $field_data['field_id'], $field_data, TRUE ); } $this->cached_vars['field_id_list'] = $this->json_encode($field_id_list); $this->cached_vars['field_composer_output_json'] = $this->json_encode($field_composer_output); $this->cached_vars['available_fields'] = $available_fields; $this->cached_vars['available_templates'] = $available_templates; $this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names; $this->cached_vars['notifications'] = $this->data->get_available_notification_templates(); $this->cached_vars['disable_missing_submit_warning'] = $this->check_yes( $this->preference('disable_missing_submit_warning') ); // ------------------------------------- // previous composer data? // ------------------------------------- $composer_data = '{}'; if ($form_data['composer_id'] > 0) { ee()->load->model('freeform_composer_model'); $composer = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $form_data['composer_id']) ->get_row(); if ($composer !== FALSE) { $composer_data_test = $this->json_decode($composer['composer_data']); if ($composer_data_test) { $composer_data = $composer['composer_data']; } } } $this->cached_vars['composer_layout_data'] = $composer_data; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['lang_allowed_html_tags'] = ( lang('allowed_html_tags') . "&lt;" . implode("&gt;, &lt;", $this->data->allowed_html_tags) . "&gt;" ); $this->cached_vars['captcha_dummy_url'] = $this->sc->addon_theme_url . 'images/captcha.png'; $this->cached_vars['new_field_url'] = $this->mod_link(array( 'method' => 'edit_field', //this builds a URL, so yes this is intentionally a string 'modal' => 'true' ), TRUE); $this->cached_vars['field_data_url'] = $this->mod_link(array( 'method' => 'composer_field_data' ), TRUE); $this->cached_vars['composer_preview_url'] = $this->mod_link(array( 'method' => 'composer_preview', 'form_id' => $form_id ), TRUE); $this->cached_vars['composer_ajax_save_url'] = $this->mod_link(array( 'method' => 'save_composer_data', 'form_id' => $form_id ), TRUE); // $this->cached_vars['composer_save_url'] = $this->mod_link(array( 'method' => 'save_composer_data', 'form_id' => $form_id )); $this->cached_vars['allowed_html_tags'] = "'" . implode("','", $this->data->allowed_html_tags) . "'"; // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); ee()->cp->add_js_script(array( 'ui' => array('sortable', 'draggable', 'droppable'), 'file' => array('underscore', 'json2') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['cp_javascript'][] = 'composer_cp.min'; $this->cached_vars['cp_javascript'][] = 'edit_field_cp.min'; $this->cached_vars['cp_javascript'][] = 'security.min'; $this->cached_vars['current_page'] = $this->view( 'composer.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END form_composer // -------------------------------------------------------------------- /** * Composer preview * * @access public * @return mixed ajax return if detected or else html without cp */ public function composer_preview () { $form_id = $this->get_post_or_zero('form_id'); $template_id = $this->get_post_or_zero('template_id'); $composer_id = $this->get_post_or_zero('composer_id'); $preview_id = $this->get_post_or_zero('preview_id'); $subpreview = (ee()->input->get_post('subpreview') !== FALSE); $composer_page = $this->get_post_or_zero('composer_page'); if ( ! $this->data->is_valid_form_id($form_id)) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // is this a preview? // ------------------------------------- if ($preview_id > 0) { $preview_mode = TRUE; $composer_id = $preview_id; } $page_count = 1; // ------------------------------------- // main output or sub output? // ------------------------------------- if ( ! $subpreview) { // ------------------------------------- // get composer data and build page count // ------------------------------------- if ($composer_id > 0) { ee()->load->model('freeform_composer_model'); $composer = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $composer_id) ->get_row(); if ($composer !== FALSE) { $composer_data = $this->json_decode( $composer['composer_data'], TRUE ); if ($composer_data AND isset($composer_data['rows']) AND ! empty($composer_data['rows'])) { foreach ($composer_data['rows'] as $row) { if ($row == 'page_break') { $page_count++; } } } } } $page_url = array(); for ($i = 1, $l = $page_count; $i <= $l; $i++) { $page_url[] = $this->mod_link(array( 'method' => __FUNCTION__, 'form_id' => $form_id, 'template_id' => $template_id, 'preview_id' => $preview_id, 'subpreview' => 'true', 'composer_page' => $i )); } $this->cached_vars['page_url'] = $page_url; $this->cached_vars['default_preview_css'] = $this->sc->addon_theme_url . 'css/default_composer.css'; $this->cached_vars['jquery_src'] = ee()->functions->fetch_site_index(0, 0) . QUERY_MARKER . 'ACT=jquery'; $html = $this->view('composer_preview.html', NULL, TRUE); } else { $subhtml = "{exp:freeform:composer form_id='$form_id'"; $subhtml .= ($composer_page > 1) ? " multipage_page='" . $composer_page . "'" : ''; $subhtml .= ($template_id > 0) ? " composer_template_id='" . $template_id . "'" : ''; $subhtml .= ($preview_id > 0) ? " preview_id='" . $preview_id . "'" : ''; $subhtml .= "}"; $html = $this->actions()->template()->process_string_as_template($subhtml); } if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'html' => $html )); } else { exit($html); } } //end composer preview // -------------------------------------------------------------------- /** * entries * * @access public * @param string $message message lang line * @param bool $moderate are we moderating? * @param bool $export export? * @return string html output */ public function entries ( $message = '' , $moderate = FALSE, $export = FALSE) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg', TRUE)); } $this->cached_vars['message'] = $message; // ------------------------------------- // moderate // ------------------------------------- $search_status = ee()->input->get_post('search_status'); $moderate = ( $moderate AND ($search_status == 'pending' OR $search_status === FALSE ) ); //if moderate and search status was not submitted, fake into pending if ($moderate AND $search_status === FALSE) { $_POST['search_status'] = 'pending'; } $this->cached_vars['moderate'] = $moderate; $this->cached_vars['method'] = $method = ( $moderate ? 'moderate_entries' : 'entries' ); // ------------------------------------- // user using session id instead of cookies? // ------------------------------------- $this->cached_vars['fingerprint'] = $this->get_session_id(); // ------------------------------------- // form data? legit? GTFO? // ------------------------------------- $form_id = ee()->input->get_post('form_id'); ee()->load->library('freeform_forms'); ee()->load->model('freeform_form_model'); //form data does all of the proper id validity checks for us $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { $this->actions()->full_stop(lang('invalid_form_id')); exit(); } $this->cached_vars['form_id'] = $form_id; $this->cached_vars['form_label'] = $form_data['form_label']; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( $form_data['form_label'] . ': ' . lang($moderate ? 'moderate' : 'entries') ); $this->set_highlight('module_forms'); $this->freeform_add_right_link( lang('new_entry'), $this->mod_link(array( 'method' => 'edit_entry', 'form_id' => $form_id )) ); // ------------------------------------- // status prefs // ------------------------------------- $form_statuses = $this->data->get_form_statuses(); $this->cached_vars['form_statuses'] = $form_statuses; // ------------------------------------- // rest of models // ------------------------------------- ee()->load->model('freeform_entry_model'); ee()->freeform_entry_model->id($form_id); // ------------------------------------- // custom field labels // ------------------------------------- $standard_columns = $this->get_standard_column_names(); //we want author instead of author id until we get data $possible_columns = $standard_columns; //key = value $all_columns = array_combine($standard_columns, $standard_columns); $column_labels = array(); $field_column_names = array(); //field prefix $f_prefix = ee()->freeform_form_model->form_field_prefix; //keyed labels for the front end foreach ($standard_columns as $column_name) { $column_labels[$column_name] = lang($column_name); } // ------------------------------------- // check for fields with custom views for entry tables // ------------------------------------- ee()->load->library('freeform_fields'); //fields in this form foreach ($form_data['fields'] as $field_id => $field_data) { //outputs form_field_1, form_field_2, etc for ->select() $field_id_name = $f_prefix . $field_id; $field_column_names[$field_id_name] = $field_data['field_name']; $all_columns[$field_id_name] = $field_data['field_name']; $column_labels[$field_data['field_name']] = $field_data['field_label']; $column_labels[$field_id_name] = $field_data['field_label']; $possible_columns[] = $field_id; $instance =& ee()->freeform_fields->get_field_instance(array( 'field_id' => $field_id, 'field_data' => $field_data )); if ( ! empty($instance->entry_views)) { foreach ($instance->entry_views as $e_lang => $e_method) { $this->freeform_add_right_link( $e_lang, $this->mod_link(array( 'method' => 'field_method', 'field_id' => $field_id, 'field_method' => $e_method, 'form_id' => $form_id )) ); } } } // ------------------------------------- // visible columns // ------------------------------------- $visible_columns = $this->visible_columns($standard_columns, $possible_columns); $this->cached_vars['visible_columns'] = $visible_columns; $this->cached_vars['column_labels'] = $column_labels; $this->cached_vars['possible_columns'] = $possible_columns; $this->cached_vars['all_columns'] = $all_columns; // ------------------------------------- // prep unused from from possible // ------------------------------------- //so so used $un_used = array(); foreach ($possible_columns as $pcid) { $check = ($this->is_positive_intlike($pcid)) ? $f_prefix . $pcid : $pcid; if ( ! in_array($check, $visible_columns)) { $un_used[] = $check; } } $this->cached_vars['unused_columns'] = $un_used; // ------------------------------------- // build query // ------------------------------------- //base url for pagination $pag_url = array( 'method' => $method, 'form_id' => $form_id ); //cleans out blank keys from unset $find_columns = array_merge(array(), $visible_columns); $must_haves = array('entry_id'); // ------------------------------------- // search criteria // building query // ------------------------------------- $has_search = FALSE; $search_vars = array( 'search_keywords', 'search_status', 'search_date_range', 'search_date_range_start', 'search_date_range_end', 'search_on_field' ); foreach ($search_vars as $search_var) { $$search_var = ee()->input->get_post($search_var, TRUE); //set for output $this->cached_vars[$search_var] = ( ($$search_var) ? trim($$search_var) : '' ); } // ------------------------------------- // search keywords // ------------------------------------- if ($search_keywords AND trim($search_keywords) !== '' AND $search_on_field AND in_array($search_on_field, $visible_columns)) { ee()->freeform_entry_model->like( $search_on_field, $search_keywords ); //pagination $pag_url['search_keywords'] = $search_keywords; $pag_url['search_on_field'] = $search_on_field; $has_search = TRUE; } //no search on field? guess we had better search it all *gulp* else if ($search_keywords AND trim($search_keywords) !== '') { $first = TRUE; ee()->freeform_entry_model->group_like( $search_keywords, array_values($visible_columns) ); $pag_url['search_keywords'] = $search_keywords; $has_search = TRUE; } //status search? if ($moderate) { ee()->freeform_entry_model->where('status', 'pending'); } else if ($search_status AND in_array($search_status, array_flip( $form_statuses))) { ee()->freeform_entry_model->where('status', $search_status); //pagination $pag_url['search_status'] = $search_status; $has_search = TRUE; } // ------------------------------------- // date range? // ------------------------------------- //pagination if ($search_date_range == 'date_range') { //if its the same date, lets set the time to the end of the day if ($search_date_range_start == $search_date_range_end) { $search_date_range_end .= ' 23:59'; } if ($search_date_range_start !== FALSE) { $pag_url['search_date_range_start'] = $search_date_range_start; } if ($search_date_range_end !== FALSE) { $pag_url['search_date_range_end'] = $search_date_range_end; } //pagination if ($search_date_range_start OR $search_date_range_end) { $pag_url['search_date_range'] = 'date_range'; $has_search = TRUE; } } else if ($search_date_range !== FALSE) { $pag_url['search_date_range'] = $search_date_range; $has_search = TRUE; } ee()->freeform_entry_model->date_where( $search_date_range, $search_date_range_start, $search_date_range_end ); // ------------------------------------- // any searches? // ------------------------------------- $this->cached_vars['has_search'] = $has_search; // ------------------------------------- // data from all sites? // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->freeform_entry_model->where( 'site_id', ee()->config->item('site_id') ); } //we need the counts for exports and end results $total_entries = ee()->freeform_entry_model->count(array(), FALSE); // ------------------------------------- // orderby // ------------------------------------- $order_by = 'entry_date'; $p_order_by = ee()->input->get_post('order_by'); if ($p_order_by !== FALSE AND in_array($p_order_by, $all_columns)) { $order_by = $p_order_by; $pag_url['order_by'] = $order_by; } // ------------------------------------- // sort // ------------------------------------- $sort = ($order_by == 'entry_date') ? 'desc' : 'asc'; $p_sort = ee()->input->get_post('sort'); if ($p_sort !== FALSE AND in_array(strtolower($p_sort), array('asc', 'desc'))) { $sort = strtolower($p_sort); $pag_url['sort'] = $sort; } ee()->freeform_entry_model->order_by($order_by, $sort); $this->cached_vars['order_by'] = $order_by; $this->cached_vars['sort'] = $sort; // ------------------------------------- // export button // ------------------------------------- if ($total_entries > 0) { $this->freeform_add_right_link( lang('export_entries'), '#export_entries' ); } // ------------------------------------- // export url // ------------------------------------- $export_url = $pag_url; $export_url['moderate'] = $moderate ? 'true' : 'false'; $export_url['method'] = 'export_entries'; $this->cached_vars['export_url'] = $this->mod_link($export_url); // ------------------------------------- // export? // ------------------------------------- if ($export) { $export_fields = ee()->input->get_post('export_fields'); $export_labels = $column_labels; // ------------------------------------- // build possible select alls // ------------------------------------- $select = array(); //are we sending just the selected fields? if ($export_fields != 'all') { $select = array_unique(array_merge($must_haves, $find_columns)); foreach ($export_labels as $key => $value) { //clean export labels for json if ( ! in_array($key, $select)) { unset($export_labels[$key]); } } //get real names foreach ($select as $key => $value) { if (isset($field_column_names[$value])) { $select[$key] = $field_column_names[$value]; } } } //sending all fields means we need to still clean some labels else { foreach ($all_columns as $field_id_name => $field_name) { //clean export labels for json if ($field_id_name != $field_name) { unset($export_labels[$field_id_name]); } $select[] = $field_name; } } foreach ($export_labels as $key => $value) { //fix entities $value = html_entity_decode($value, ENT_COMPAT, 'UTF-8'); $export_labels[$key] = $value; if (isset($field_column_names[$key])) { $export_labels[$field_column_names[$key]] = $value; } } ee()->freeform_entry_model->select(implode(', ', $select)); // ------------------------------------- // check for chunking, etc // ------------------------------------- ee()->load->library('freeform_export'); ee()->freeform_export->format_dates = (ee()->input->get_post('format_dates') == 'y'); ee()->freeform_export->export(array( 'method' => ee()->input->get_post('export_method'), 'form_id' => $form_id, 'form_name' => $form_data['form_name'], 'output' => 'download', 'model' => ee()->freeform_entry_model, 'remove_entry_id' => ($export_fields != 'all' AND ! in_array('entry_id', $visible_columns)), 'header_labels' => $export_labels, 'total_entries' => $total_entries )); } //END if ($export) // ------------------------------------- // selects // ------------------------------------- $needed_selects = array_unique(array_merge($must_haves, $find_columns)); ee()->freeform_entry_model->select(implode(', ', $needed_selects)); //-------------------------------------- // pagination start vars //-------------------------------------- $pag_url = $this->mod_link($pag_url); $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; //moved above exports //$total_entries = ee()->freeform_entry_model->count(array(), FALSE); $current_page = 0; // ------------------------------------- // pagination? // ------------------------------------- // do we need pagination? if ($total_entries > $row_limit ) { $row_count = $this->get_post_or_zero('row'); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_entries, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $pag_url), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; $current_page = $pagination_data['pagination_page']; ee()->freeform_entry_model->limit($row_limit, $current_page); } $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // get data // ------------------------------------- $result_array = ee()->freeform_entry_model->get(); $count = $row_count; $entries = array(); if ( ! $result_array) { $result_array = array(); } $entry_ids = array(); foreach ($result_array as $row) { $entry_ids[] = $row['entry_id']; } // ------------------------------------- // allow pre_process // ------------------------------------- ee()->freeform_fields->apply_field_method(array( 'method' => 'pre_process_entries', 'form_id' => $form_id, 'entry_id' => $entry_ids, 'form_data' => $form_data, 'field_data' => $form_data['fields'] )); foreach ( $result_array as $row) { //apply display_entry_cp to our field data $field_parse = ee()->freeform_fields->apply_field_method(array( 'method' => 'display_entry_cp', 'form_id' => $form_id, 'entry_id' => $row['entry_id'], 'form_data' => $form_data, 'field_data' => $form_data['fields'], 'field_input_data' => $row )); $row = array_merge($row, $field_parse['variables']); $entry = array(); $entry['view_entry_link'] = $this->mod_link(array( 'method' => 'view_entry', 'form_id' => $form_id, 'entry_id' => $row['entry_id'] )); $entry['edit_entry_link'] = $this->mod_link(array( 'method' => 'edit_entry', 'form_id' => $form_id, 'entry_id' => $row['entry_id'] )); $entry['approve_link'] = $this->mod_link(array( 'method' => 'approve_entries', 'form_id' => $form_id, 'entry_ids' => $row['entry_id'] )); $entry['count'] = ++$count; $entry['id'] = $row['entry_id']; // ------------------------------------- // remove entry_id and author_id if we // arent showing them // ------------------------------------- if ( ! in_array('entry_id', $visible_columns)) { unset($row['entry_id']); } // ------------------------------------- // dates // ------------------------------------- if (in_array('entry_date', $visible_columns)) { $row['entry_date'] = $this->format_cp_date($row['entry_date']); } if (in_array('edit_date', $visible_columns)) { $row['edit_date'] = ($row['edit_date'] == 0) ? '' : $this->format_cp_date($row['edit_date']); } $entry['data'] = $row; $entries[] = $entry; } $this->cached_vars['entries'] = $entries; // ------------------------------------- // ajax request? // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'entries' => $entries, 'paginate' => $paginate, 'visibleColumns' => $visible_columns, 'allColumns' => $all_columns, 'columnLabels' => $column_labels, 'success' => TRUE )); exit(); } // ------------------------------------- // moderation count? // ------------------------------------- //lets not waste the query if we are already moderating $moderation_count = ( ( ! $moderate) ? $this->data->get_form_needs_moderation_count($form_id) : 0 ); if ($moderation_count > 0) { $this->cached_vars['lang_num_items_awaiting_moderation'] = str_replace( array('%num%', '%form_label%'), array($moderation_count, $form_data['form_label']), lang('num_items_awaiting_moderation') ); } $this->cached_vars['moderation_count'] = $moderation_count; $this->cached_vars['moderation_link'] = $this->mod_link(array( 'method' => 'moderate_entries', 'form_id' => $form_id, 'search_status' => 'pending' )); // ------------------------------------- // is admin? // ------------------------------------- $this->cached_vars['is_admin'] = $is_admin = ( ee()->session->userdata('group_id') == 1 ); // ------------------------------------- // can save field layout? // ------------------------------------- //$this->cached_vars['can_edit_layout'] = $can_edit_layout = ( // $is_admin OR // $this->check_yes($this->preference('allow_user_field_layout')) //); //just in case $this->cached_vars['can_edit_layout'] = TRUE; $this->freeform_add_right_link( lang('edit_field_layout'), '#edit_field_layout' ); // ------------------------------------- // member groups // ------------------------------------- $member_groups = array(); if ($is_admin) { ee()->db->select('group_id, group_title'); $member_groups = $this->prepare_keyed_result( ee()->db->get('member_groups'), 'group_id', 'group_title' ); } $this->cached_vars['member_groups'] = $member_groups; // ------------------------------------- // lang items // ------------------------------------- // ------------------------------------- // no results lang // ------------------------------------- $this->cached_vars['lang_no_results_for_form'] = ( ($has_search) ? lang('no_results_for_search') : ( ($moderate) ? lang('no_entries_awaiting_approval') : lang('no_entries_for_form') ) ); // ------------------------------------- // moderation lang // ------------------------------------- $this->cached_vars['lang_viewing_moderation'] = str_replace( '%form_label%', $form_data['form_label'], lang('viewing_moderation') ); // ------------------------------------- // other vars // ------------------------------------- $this->cached_vars['form_url'] = $this->mod_link(array( 'method' => 'entries_action', 'return_method' => (($moderate) ? 'moderate_' : '' ) . 'entries' )); $this->cached_vars['save_layout_url'] = $this->mod_link(array( 'method' => 'save_field_layout' )); // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); //$this->load_datatables(); ee()->cp->add_js_script(array( 'ui' => array('datepicker', 'sortable'), 'file' => 'underscore' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'entries.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END entries // -------------------------------------------------------------------- /** * Fire a field method as a page view * * @access public * @param string $message lang line to load for a message * @return string html output */ public function field_method ($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg', TRUE)); } $this->cached_vars['message'] = $message; // ------------------------------------- // goods // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $field_id = $this->get_post_or_zero('field_id'); $field_method = ee()->input->get_post('field_method'); $instance = FALSE; if ( $field_method == FALSE OR ! $this->data->is_valid_form_id($form_id) OR $field_id == 0) { ee()->functions->redirect($this->mod_link(array('method' => 'forms'))); } ee()->load->library('freeform_fields'); $instance =& ee()->freeform_fields->get_field_instance(array( 'form_id' => $form_id, 'field_id' => $field_id )); //legit? if ( ! is_object($instance) OR empty($instance->entry_views) OR //removed so you can post to this //! in_array($field_method, $instance->entry_views) OR ! is_callable(array($instance, $field_method))) { ee()->functions->redirect($this->mod_link(array('method' => 'forms'))); } $method_lang = lang('field_entry_view'); foreach ($instance->entry_views as $e_lang => $e_method) { if ($field_method == $e_method) { $method_lang = $e_lang; } } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('entries'), $this->mod_link(array( 'method' => 'entries', 'form_id' => $form_id )) ); $this->add_crumb($method_lang); $this->set_highlight('module_forms'); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $instance->$field_method(); // ------------------------------------- // loading these after the instance // incase the instance exits // ------------------------------------- $this->load_fancybox(); return $this->ee_cp_view('index.html'); } //END field_method // -------------------------------------------------------------------- /** * migrate collections * * @access public * @return string */ public function migrate_collections ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('utilities')); $this->set_highlight('module_utilities'); //-------------------------------------- // Library //-------------------------------------- ee()->load->library('freeform_migration'); //-------------------------------------- // Variables //-------------------------------------- $migrate_empty_fields = 'n'; $migrate_attachments = 'n'; $this->cached_vars['total'] = 0; $this->cached_vars['collections'] = ''; $collections = ee()->input->post('collections'); if ( $collections !== FALSE ) { $this->cached_vars['total'] = ee()->freeform_migration ->get_migration_count( $collections ); $this->cached_vars['collections'] = implode('|', $collections); if ($this->check_yes( ee()->input->post('migrate_empty_fields') ) ) { $migrate_empty_fields = 'y'; } if ($this->check_yes( ee()->input->post('migrate_attachments') ) ) { $migrate_attachments = 'y'; } } //-------------------------------------- // Migration ajax url //-------------------------------------- $this->cached_vars['ajax_url'] = $this->base . '&method=migrate_collections_ajax' . '&migrate_empty_fields=' . $migrate_empty_fields . '&migrate_attachments=' . $migrate_attachments . '&collections=' . urlencode( $this->cached_vars['collections'] ) . '&total=' . $this->cached_vars['total'] . '&batch=0'; //-------------------------------------- // images //-------------------------------------- //Success image $this->cached_vars['success_png_url'] = $this->sc->addon_theme_url . 'images/success.png'; // Error image $this->cached_vars['error_png_url'] = $this->sc->addon_theme_url . 'images/exclamation.png'; //-------------------------------------- // Javascript //-------------------------------------- $this->cached_vars['cp_javascript'][] = 'migrate'; ee()->cp->add_js_script( array('ui' => array('core', 'progressbar')) ); //-------------------------------------- // Load page //-------------------------------------- $this->cached_vars['current_page'] = $this->view( 'migrate.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } // End migrate collections // -------------------------------------------------------------------- /** * migrate collections ajax * * @access public * @return string */ public function migrate_collections_ajax() { $upper_limit = 9999; //-------------------------------------- // Base output //-------------------------------------- $out = array( 'done' => FALSE, 'batch' => ee()->input->get('batch'), 'total' => ee()->input->get('total') ); //-------------------------------------- // Libraries //-------------------------------------- ee()->load->library('freeform_migration'); //-------------------------------------- // Validate //-------------------------------------- $collections = ee()->input->get('collections'); if ( empty( $collections ) OR ee()->input->get('batch') === FALSE ) { $out['error'] = TRUE; $out['errors'] = array( 'no_collections' => lang('no_collections') ); $this->send_ajax_response($out); exit(); } //-------------------------------------- // Done? //-------------------------------------- if ( ee()->input->get('batch') !== FALSE AND ee()->input->get('total') !== FALSE AND ee()->input->get('batch') >= ee()->input->get('total') ) { $out['done'] = TRUE; $this->send_ajax_response($out); exit(); } //-------------------------------------- // Anything? //-------------------------------------- $collections = $this->actions()->pipe_split( urldecode( ee()->input->get('collections') ) ); $counts = ee()->freeform_migration->get_collection_counts($collections); if (empty($counts)) { $out['error'] = TRUE; $out['errors'] = array( 'no_collections' => lang('no_collections') ); $this->send_ajax_response($out); exit(); } //-------------------------------------- // Do any of the submitted collections have unmigrated entries? //-------------------------------------- $migrate = FALSE; foreach ( $counts as $form_name => $val ) { if ( ! empty( $val['unmigrated'] ) ) { $migrate = TRUE; } } if ( empty( $migrate ) ) { $out['done'] = TRUE; $this->send_ajax_response($out); exit(); } //-------------------------------------- // Master arrays //-------------------------------------- $forms = array(); $form_fields = array(); //-------------------------------------- // Loop and process //-------------------------------------- foreach ( $counts as $form_name => $val ) { //-------------------------------------- // For each collection, create a form //-------------------------------------- $form_data = ee()->freeform_migration->create_form($form_name); if ( $form_data !== FALSE ) { $forms[ $form_data['form_name'] ]['form_id'] = $form_data['form_id']; $forms[ $form_data['form_name'] ]['form_label'] = $form_data['form_label']; } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } //-------------------------------------- // For each collection, determine fields //-------------------------------------- $migrate_empty_fields = ( $this->check_yes(ee()->input->get('migrate_empty_fields')) ) ? 'y': 'n'; $fields = ee()->freeform_migration->get_fields_for_collection( $form_name, $migrate_empty_fields ); if ($fields !== FALSE) { $form_fields[ $form_name ]['fields'] = $fields; } else { $errors = ee()->freeform_migration->get_errors(); if ($errors !== FALSE) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } //-------------------------------------- // For each collection, create necessary fields if they don't yet exist. //-------------------------------------- $created_field_ids = array(); if ( ! empty( $form_fields[$form_name]['fields'] ) ) { foreach ( $form_fields[$form_name]['fields'] as $name => $attr ) { $field_id = ee()->freeform_migration->create_field( $forms[$form_name]['form_id'], $name, $attr ); if ($field_id !== FALSE ) { $created_field_ids[] = $field_id; } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } } } //-------------------------------------- // For each collection, create upload fields if needed. //-------------------------------------- $attachment_profiles = ee()->freeform_migration->get_attachment_profiles( $form_name ); if ($this->check_yes( ee()->input->get('migrate_attachments') ) AND $attachment_profiles !== FALSE ) { foreach ( $attachment_profiles as $row ) { $field_id = ee()->freeform_migration->create_upload_field( $forms[ $form_name ]['form_id'], $row['name'], $row ); if ($field_id !== FALSE) { $created_field_ids[] = $field_id; $upload_pref_id_map[ $row['pref_id'] ] = array( 'field_id' => $field_id, 'field_name' => $row['name'] ); } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } } if ( ! empty( $upload_pref_id_map ) ) { ee()->freeform_migration->set_property( 'upload_pref_id_map', $upload_pref_id_map ); } } //-------------------------------------- // Assign the fields to our form. //-------------------------------------- ee()->freeform_migration->assign_fields_to_form( $forms[ $form_data['form_name'] ]['form_id'], $created_field_ids ); //-------------------------------------- // Safeguard? //-------------------------------------- if ( ee()->input->get('batch') == $upper_limit ) { $this->send_ajax_response(array('done' => TRUE )); exit(); } //-------------------------------------- // Pass attachments pref //-------------------------------------- if ($this->check_yes( ee()->input->get('migrate_attachments') ) ) { ee()->freeform_migration->set_property('migrate_attachments', TRUE); } //-------------------------------------- // Grab entries //-------------------------------------- ee()->freeform_migration->set_property( 'batch_limit', $this->migration_batch_limit ); $entries = ee()->freeform_migration->get_legacy_entries($form_name); if ( $entries !== FALSE ) { foreach ( $entries as $entry ) { //-------------------------------------- // Insert //-------------------------------------- $entry_id = ee()->freeform_migration->set_legacy_entry( $forms[ $form_name ]['form_id'], $entry ); if ( $entry_id === FALSE ) { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } else { $out['batch'] = $out['batch'] + 1; } } } } //-------------------------------------- // Are we done? //-------------------------------------- $this->send_ajax_response($out); exit(); } // End migrate collections ajax // -------------------------------------------------------------------- /** * moderate entries * * almost the same as entries but with some small modifications * * @access public * @param string message lang line * @return string html output */ public function moderate_entries ( $message = '' ) { return $this->entries($message, TRUE); } //END moderate_entries // -------------------------------------------------------------------- /** * Action from submitted entries links * * @access public * @return string html output */ public function entries_action () { $action = ee()->input->get_post('submit_action'); if ($action == 'approve') { return $this->approve_entries(); } else if ($action == 'delete') { return $this->delete_confirm_entries(); } /* else if ($action == 'edit') { $this->edit_entries(); } */ } //END entries_action // -------------------------------------------------------------------- /** * [edit_entry description] * * @access public * @return string parsed html */ public function edit_entry ($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; // ------------------------------------- // edit? // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $entry_id = $this->get_post_or_zero('entry_id'); ee()->load->model('freeform_form_model'); ee()->load->model('freeform_entry_model'); $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $entry_data = array(); $edit = FALSE; if ($entry_id > 0) { $entry_data = ee()->freeform_entry_model ->id($form_id) ->where('entry_id', $entry_id) ->get_row(); if ($entry_data == FALSE) { return $this->actions()->full_stop(lang('invalid_entry_id')); } $edit = TRUE; } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( lang($edit ? 'edit_entry' : 'new_entry') . ': ' . $form_data['form_label'] ); $this->set_highlight('module_forms'); // ------------------------------------- // load the template library in case // people get upset or something // ------------------------------------- if ( ! isset(ee()->TMPL) OR ! is_object(ee()->TMPL)) { ee()->load->library('template'); $globals['TMPL'] =& ee()->template; ee()->TMPL =& ee()->template; } // ------------------------------------- // get fields // ------------------------------------- ee()->load->library('freeform_fields'); $field_output_data = array(); $field_loop_ids = array_keys($form_data['fields']); if ($form_data['field_order'] !== '') { $order_ids = $this->actions()->pipe_split($form_data['field_order']); if ( ! empty($order_ids)) { //this makes sure that any fields in 'fields' are in the //order set as well. Will add missing at the end like this $field_loop_ids = array_merge( $order_ids, array_diff($field_loop_ids, $order_ids) ); } } foreach ($field_loop_ids as $field_id) { if ( ! isset($form_data['fields'][$field_id])) { continue; } $f_data = $form_data['fields'][$field_id]; $instance =& ee()->freeform_fields->get_field_instance(array( 'field_id' => $field_id, 'field_data' => $f_data, 'form_id' => $form_id, 'entry_id' => $entry_id, 'edit' => $edit, 'extra_settings' => array( 'entry_id' => $entry_id ) )); $column_name = ee()->freeform_entry_model->form_field_prefix . $field_id; $display_field_data = ''; if ($edit) { if (isset($entry_data[$column_name])) { $display_field_data = $entry_data[$column_name]; } else if (isset($entry_data[$f_data['field_name']])) { $display_field_data = $entry_data[$f_data['field_name']]; } } $field_output_data[$field_id] = array( 'field_display' => $instance->display_edit_cp($display_field_data), 'field_label' => $f_data['field_label'], 'field_description' => $f_data['field_description'] ); } $entry_data['screen_name'] = ''; $entry_data['group_title'] = ''; if (!empty($entry_data['author_id'])) { $member_data = ee()->db ->select('group_title, screen_name') ->from('members') ->join('member_groups', 'members.group_id = member_groups.group_id', 'left') ->where('member_id', $entry_data['author_id']) ->limit(1) ->get(); if ($member_data->num_rows() > 0) { $entry_data['screen_name'] = $member_data->row('screen_name'); $entry_data['group_title'] = $member_data->row('group_title'); } } if ($entry_data['screen_name'] == '') { $entry_data['screen_name'] = lang('guest'); $entry_data['group_title'] = lang('guest'); $guest_data = ee()->db ->select('group_title') ->from('member_groups') ->where('group_id', 3) ->limit(1) ->get(); if ($guest_data->num_rows() > 0) { $entry_data['group_title'] = $guest_data->row('group_title'); } } $entry_data['entry_date'] = ( ! empty( $entry_data['entry_date'] ) ) ? $entry_data['entry_date'] : ee()->localize->now; $entry_data['entry_date'] = $this->format_cp_date($entry_data['entry_date']); $entry_data['edit_date'] = (!empty($entry_data['edit_date'])) ? $this->format_cp_date($entry_data['edit_date']) : lang('n_a'); $this->cached_vars['entry_data'] = $entry_data; $this->cached_vars['field_output_data'] = $field_output_data; $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_entry' )); $this->cached_vars['form_id'] = $form_id; $this->cached_vars['entry_id'] = $entry_id; $this->cached_vars['statuses'] = $this->data->get_form_statuses(); // -------------------------------------------- // Load page // -------------------------------------------- $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; $this->cached_vars['current_page'] = $this->view( 'edit_entry.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_entry // -------------------------------------------------------------------- /** * fields * * @access public * @param string message * @return string */ public function fields ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->cached_vars['new_field_link'] = $this->mod_link(array( 'method' => 'edit_field' )); $this->add_crumb( lang('fields') ); //optional $this->freeform_add_right_link(lang('new_field'), $this->cached_vars['new_field_link']); $this->set_highlight('module_fields'); // ------------------------------------- // data // ------------------------------------- $this->cached_vars['fingerprint'] = $this->get_session_id(); $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; $field_data = array(); $paginate_url = array('method' => 'fields'); ee()->load->model('freeform_field_model'); ee()->freeform_field_model->select( 'field_label, field_name, field_type, field_id, field_description' ); // ------------------------------------- // search? // ------------------------------------- $field_search = ''; $field_search_on = ''; $search = ee()->input->get_post('field_search', TRUE); if ($search) { $f_search_on = ee()->input->get_post('field_search_on'); if ($f_search_on == 'field_name') { ee()->freeform_field_model->like('field_name', $search); $field_search_on = 'field_name'; } else if ($f_search_on == 'field_label') { ee()->freeform_field_model->like('field_label', $search); $field_search_on = 'field_label'; } else if ($f_search_on == 'field_description') { ee()->freeform_field_model->like('field_description', $search); $field_search_on = 'field_description'; } else //if ($f_search_on == 'all') { ee()->freeform_field_model->like('field_name', $search); ee()->freeform_field_model->or_like('field_label', $search); ee()->freeform_field_model->or_like('field_description', $search); $field_search_on = 'all'; } $field_search = $search; $paginate_url['field_search'] = $search; $paginate_url['field_search_on'] = $field_search_on; } $this->cached_vars['field_search'] = $field_search; $this->cached_vars['field_search_on'] = $field_search_on; // ------------------------------------- // all sites? // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->freeform_field_model->where( 'site_id', ee()->config->item('site_id') ); } ee()->freeform_field_model->order_by('field_name', 'asc'); $total_results = ee()->freeform_field_model->count(array(), FALSE); $row_count = 0; // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $this->mod_link($paginate_url)), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; ee()->freeform_field_model->limit( $row_limit, $pagination_data['pagination_page'] ); } $query = ee()->freeform_field_model->get(); $count = $row_count; if ($query !== FALSE) { foreach ($query as $row) { $row['count'] = ++$count; $row['field_edit_link'] = $this->mod_link(array( 'method' => 'edit_field', 'field_id' => $row['field_id'] )); $row['field_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_field', 'duplicate_id' => $row['field_id'] )); $row['field_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_fields', 'field_id' => $row['field_id'] )); $field_data[] = $row; } } $this->cached_vars['field_data'] = $field_data; $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // ajax? // ------------------------------------- if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'field_data' => $field_data, 'paginate' => $paginate )); } // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'delete_confirm_fields' )); // ------------------------------------- // js // ------------------------------------- ee()->cp->add_js_script(array( 'file' => array('underscore', 'json2') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'fields.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END fields // -------------------------------------------------------------------- /** * Edit Field * * @access public * @param bool $modal is this a modal version? * @return string */ public function edit_field ($modal = FALSE) { // ------------------------------------- // field ID? we must be editing // ------------------------------------- $field_id = $this->get_post_or_zero('field_id'); $update = ($field_id != 0); $modal = ( ! $modal AND $this->check_yes(ee()->input->get_post('modal'))) ? TRUE : $modal; $this->cached_vars['modal'] = $modal; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('fields') , $this->base . AMP . 'method=fields'); $this->add_crumb( lang(($update ? 'update_field' : 'new_field')) ); //optional //$this->freeform_add_right_link(lang('home'), $this->base . AMP . 'method=some_method'); $this->set_highlight('module_fields'); // ------------------------------------- // default values // ------------------------------------- $inputs = array( 'field_id' => '0', 'field_name' => '', 'field_label' => '', 'field_order' => '0', 'field_type' => $this->data->defaults['field_type'], 'field_length' => $this->data->defaults['field_length'], 'field_description' => '', 'submissions_page' => 'y', 'moderation_page' => 'y', 'composer_use' => 'y', ); // ------------------------------------- // defaults // ------------------------------------- $this->cached_vars['edit_warning'] = FALSE; $field_in_forms = array(); $incoming_settings = FALSE; if ($update) { $field_data = $this->data->get_field_info_by_id($field_id); if (empty($field_data)) { $this->actions()->full_stop(lang('invalid_field_id')); } foreach ($field_data as $key => $value) { $inputs[$key] = $value; } // ------------------------------------- // is this change going to affect any // forms that use this field? // ------------------------------------- $form_info = $this->data->get_form_info_by_field_id($field_id); if ($form_info AND ! empty($form_info)) { $this->cached_vars['edit_warning'] = TRUE; $form_names = array(); foreach ($form_info as $row) { $field_in_forms[] = $row['form_id']; $form_names[] = $row['form_label']; } $this->cached_vars['lang_field_edit_warning'] = lang('field_edit_warning'); $this->cached_vars['lang_field_edit_warning_desc'] = str_replace( '%form_names%', implode(', ', $form_names), lang('field_edit_warning_desc') ); } } $this->cached_vars['form_ids'] = implode('|', array_unique($field_in_forms)); // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $duplicate = FALSE; $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $field_data = $this->data->get_field_info_by_id($duplicate_id); if ($field_data) { $duplicate = TRUE; foreach ($field_data as $key => $value) { if (in_array($key, array('field_id', 'field_label', 'field_name'))) { continue; } $inputs[$key] = $value; } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $field_data['field_label']; } } // ------------------------------------- // get available field types // ------------------------------------- ee()->load->library('freeform_fields'); $this->cached_vars['fieldtypes'] = ee()->freeform_fields->get_available_fieldtypes(); // ------------------------------------- // get available forms to add this to // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->db->where('site_id', ee()->config->item('site_id')); } $this->cached_vars['available_forms'] = $this->prepare_keyed_result( ee()->db->get('freeform_forms'), 'form_id' ); // ------------------------------------- // add desc and lang for field types // ------------------------------------- foreach($this->cached_vars['fieldtypes'] as $fieldtype => $field_data) { //settings? $settings = ( ($update OR $duplicate ) AND $inputs['field_type'] == $fieldtype AND isset($inputs['settings']) ) ? json_decode($inputs['settings'], TRUE) : array(); //we are encoding this and decoding in JS because leaving the //fields intact while in storage in the html makes dupes of fields. //I could do some html moving around, but that would keep running //individual settings JS over and over again when it should //only be run on display. $this->cached_vars['fieldtypes'][$fieldtype]['settings_output'] = base64_encode( ee()->freeform_fields->fieldtype_display_settings_output( $fieldtype, $settings ) ); } if (isset($inputs['field_label'])) { $inputs['field_label'] = form_prep($inputs['field_label']); } if (isset($inputs['field_description'])) { $inputs['field_description'] = form_prep($inputs['field_description']); } // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_field' )); //---------------------------------------- // Load vars //---------------------------------------- $this->cached_vars['lang_submit_word'] = lang( ($update ? 'update_field' : 'create_field') ); $this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['cp_javascript'][] = 'edit_field_cp.min'; $this->cached_vars['current_page'] = $this->view( 'edit_field.html', NULL, TRUE ); if ($modal) { exit($this->cached_vars['current_page']); } $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; return $this->ee_cp_view('index.html'); } //END edit_field // -------------------------------------------------------------------- /** * Field Types * * @access public * @param message * @return string */ public function fieldtypes ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('fieldtypes') ); $this->set_highlight('module_fieldtypes'); //-------------------------------------- // start vars //-------------------------------------- $fieldtypes = array(); ee()->load->library('freeform_fields'); ee()->load->model('freeform_field_model'); ee()->load->model('freeform_fieldtype_model'); if ( ( $installed_fieldtypes = ee()->freeform_fieldtype_model->installed_fieldtypes() ) === FALSE ) { $installed_fieldtypes = array(); } $fieldtypes = ee()->freeform_fields->get_installable_fieldtypes(); // ------------------------------------- // missing fieldtype folders? // ------------------------------------- $missing_fieldtypes = array(); foreach ($installed_fieldtypes as $name => $version) { if ( ! array_key_exists($name, $fieldtypes)) { $missing_fieldtypes[] = $name; } } // ------------------------------------- // add urls and crap // ------------------------------------- $action_url = $this->base . AMP . 'method=freeform_fieldtype_action'; foreach ($fieldtypes as $name => $data) { $fieldtypes[$name]['installed_lang'] = lang($data['installed'] ? 'installed' : 'not_installed'); $action = ($data['installed'] ? 'uninstall' : 'install'); $fieldtypes[$name]['action_lang'] = lang($action); $fieldtypes[$name]['action_url'] = $this->mod_link(array( 'method' => 'freeform_fieldtype_action', 'name' => $name, 'action' => $action, //some other time -gf //'folder' => base64_encode($data['folder']) )); } $this->cached_vars['fieldtypes'] = $fieldtypes; $this->cached_vars['freeform_ft_docs_url'] = $this->data->doc_links['custom_fields']; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'fieldtypes.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END field_types // -------------------------------------------------------------------- /** * notifications * * @access public * @param string message to output * @return string outputted template */ public function notifications ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->cached_vars['new_notification_link'] = $this->mod_link(array( 'method' => 'edit_notification' )); $this->add_crumb( lang('notifications') ); $this->freeform_add_right_link( lang('new_notification'), $this->cached_vars['new_notification_link'] ); $this->set_highlight('module_notifications'); // ------------------------------------- // data // ------------------------------------- $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; $notification_data = array(); ee()->db->start_cache(); ee()->db->order_by('notification_name', 'asc'); if ( ! $this->data->show_all_sites()) { ee()->db->where('site_id', ee()->config->item('site_id')); } ee()->db->from('freeform_notification_templates'); ee()->db->stop_cache(); $total_results = ee()->db->count_all_results(); // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); $url = $this->mod_link(array( 'method' => 'notifications' )); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $url), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; ee()->db->limit($row_limit, $pagination_data['pagination_page']); } $query = ee()->db->get(); ee()->db->flush_cache(); if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) { $row['notification_edit_link'] = $this->mod_link(array( 'method' => 'edit_notification', 'notification_id' => $row['notification_id'], )); $row['notification_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_notification', 'duplicate_id' => $row['notification_id'], )); $row['notification_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_notification', 'notification_id' => $row['notification_id'], )); $notification_data[] = $row; } } $this->cached_vars['notification_data'] = $notification_data; $this->cached_vars['paginate'] = $paginate; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'delete_confirm_notification' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'notifications.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END notifications // -------------------------------------------------------------------- /** * edit_notification * * @access public * @return string */ public function edit_notification () { // ------------------------------------- // notification ID? we must be editing // ------------------------------------- $notification_id = $this->get_post_or_zero('notification_id'); $update = ($notification_id != 0); //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb( lang('notifications'), $this->base . AMP . 'method=notifications' ); $this->add_crumb( lang(($update ? 'update_notification' : 'new_notification')) ); $this->set_highlight('module_notifications'); // ------------------------------------- // data items // ------------------------------------- $inputs = array( 'notification_id' => '0', 'notification_name' => '', 'notification_label' => '', 'notification_description' => '', 'wordwrap' => $this->data->defaults['wordwrap'], 'allow_html' => $this->data->defaults['allow_html'], 'from_name' => form_prep(ee()->config->item('webmaster_name')), 'from_email' => ee()->config->item('webmaster_email'), 'reply_to_email' => ee()->config->item('webmaster_email'), 'email_subject' => '', 'template_data' => '', 'include_attachments' => 'n' ); // ------------------------------------- // defaults // ------------------------------------- $this->cached_vars['edit_warning'] = FALSE; if ($update) { $notification_data = $this->data->get_notification_info_by_id($notification_id); foreach ($notification_data as $key => $value) { $inputs[$key] = form_prep($value); } // ------------------------------------- // is this change going to affect any // forms that use this field? // ------------------------------------- $form_info = $this->data->get_form_info_by_notification_id($notification_id); if ($form_info AND ! empty($form_info)) { $this->cached_vars['edit_warning'] = TRUE; $form_names = array(); foreach ($form_info as $row) { $form_names[] = $row['form_label']; } $this->cached_vars['lang_notification_edit_warning'] = str_replace( '%form_names%', implode(', ', $form_names), lang('notification_edit_warning') ); } } // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $notification_data = $this->data->get_notification_info_by_id($duplicate_id); if ($notification_data) { foreach ($notification_data as $key => $value) { //TODO: remove other items that dont need to be duped? if (in_array($key, array( 'notification_id', 'notification_label', 'notification_name' ))) { continue; } $inputs[$key] = form_prep($value); } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $notification_data['notification_label']; } } // ------------------------------------- // get available fields // ------------------------------------- ee()->load->model('freeform_field_model'); $this->cached_vars['available_fields'] = array(); if ( ( $fields = ee()->freeform_field_model->get() ) !== FALSE ) { $this->cached_vars['available_fields'] = $fields; } $this->cached_vars['standard_tags'] = $this->data->standard_notification_tags; // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } $this->cached_vars['form_uri'] = $this->base . AMP . 'method=save_notification'; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['lang_submit_word'] = lang( ($update ? 'update_notification' : 'create_notification') ); $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'edit_notification.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_notification // -------------------------------------------------------------------- /** * preferences * * @access public * @return string */ public function preferences ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('preferences')); $this->set_highlight('module_preferences'); // ------------------------------------- // global prefs // ------------------------------------- $this->cached_vars['msm_enabled'] = $msm_enabled = $this->data->msm_enabled; $is_admin = (ee()->session->userdata('group_id') == 1); $this->cached_vars['show_global_prefs'] = ($is_admin AND $msm_enabled); $global_pref_data = array(); $global_prefs = $this->data->get_global_module_preferences(); $default_global_prefs = array_keys($this->data->default_global_preferences); //dynamically get prefs and lang so we can just add them to defaults foreach( $global_prefs as $key => $value ) { //this skips things that don't need to be shown on this page //so we can use the prefs table for other areas of the addon if ( ! in_array($key, $default_global_prefs)) { continue; } $pref = array(); $pref['name'] = $key; $pref['lang_label'] = lang($key); $key_desc = $key . '_desc'; $pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc); $pref['value'] = form_prep($value); $pref['type'] = $this->data->default_global_preferences[$key]['type']; $global_pref_data[] = $pref; } $this->cached_vars['global_pref_data'] = $global_pref_data; // ------------------------------------- // these two will only be used if MSM // is enabled, but setting them // anyway to avoid potential PHP errors // ------------------------------------- $prefs_all_sites = ! $this->check_no( $this->data->global_preference('prefs_all_sites') ); $this->cached_vars['lang_site_prefs_for_site'] = ( lang('site_prefs_for') . ' ' . ( ($prefs_all_sites) ? lang('all_sites') : ee()->config->item('site_label') ) ); //-------------------------------------- // per site prefs //-------------------------------------- $pref_data = array(); $prefs = $this->data->get_module_preferences(); $default_prefs = array_keys($this->data->default_preferences); //dynamically get prefs and lang so we can just add them to defaults foreach( $prefs as $key => $value ) { //this skips things that don't need to be shown on this page //so we can use the prefs table for other areas of the addon if ( ! in_array($key, $default_prefs)) { continue; } //admin only pref? //MSM pref and no MSM? if ( (ee()->session->userdata('group_id') != 1 AND in_array($key, $this->data->admin_only_prefs)) OR ( ! $msm_enabled AND in_array($key, $this->data->msm_only_prefs)) ) { continue; } $pref = array(); $pref['name'] = $key; $pref['lang_label'] = lang($key); $key_desc = $key . '_desc'; $pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc); $pref['value'] = form_prep($value); $pref['type'] = $this->data->default_preferences[$key]['type']; $pref_data[] = $pref; } $this->cached_vars['pref_data'] = $pref_data; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_preferences' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'preferences.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END preferences // -------------------------------------------------------------------- /** * delete confirm page abstractor * * @access private * @param string method you want to post data to after confirm * @param array all of the values you want to carry over to post * @param string the lang line of the warning message to display * @param string the lang line of the submit button for confirm * @param bool $message_use_lang use the lang wrapper for the message? * @return string */ private function delete_confirm ($method, $hidden_values, $message_line, $submit_line = 'delete', $message_use_lang = TRUE) { $this->cached_vars = array_merge($this->cached_vars, array( 'hidden_values' => $hidden_values, 'lang_message' => ($message_use_lang ? lang($message_line) : $message_line), 'lang_submit' => lang($submit_line), 'form_url' => $this->mod_link(array('method' => $method)) )); $this->cached_vars['current_page'] = $this->view( 'delete_confirm.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END delete_confirm //-------------------------------------------------------------------- // end views //-------------------------------------------------------------------- // -------------------------------------------------------------------- /** * Clean up inputted paragraph html * * @access public * @param string $string string to clean * @return mixed string if html or json if not */ public function clean_paragraph_html ($string = '', $allow_ajax = TRUE) { if ( ! $string OR trim($string == '')) { $string = ee()->input->get_post('clean_string'); if ( $string === FALSE OR trim($string) === '') { $string = ''; } } $allowed_tags = '<' . implode('><', $this->data->allowed_html_tags) . '>'; $string = strip_tags($string, $allowed_tags); $string = ee()->security->xss_clean($string); return $string; } //END clean_paragraph_html // -------------------------------------------------------------------- /** * Fieldtype Actions * * this installs or uninstalles depending on the sent action * this will redirect no matter what * * @access public * @return null */ public function freeform_fieldtype_action () { $return_url = array('method' => 'fieldtypes'); $name = ee()->input->get_post('name', TRUE); $action = ee()->input->get_post('action'); if ($name AND $action) { ee()->load->library('freeform_fields'); if ($action === 'install') { if (ee()->freeform_fields->install_fieldtype($name)) { $return_url['msg'] = 'fieldtype_installed'; } else { return $this->actions()->full_stop(lang('fieldtype_install_error')); } } else if ($action === 'uninstall') { $uninstall = $this->uninstall_confirm_fieldtype($name); //if its not a boolean true, its a confirmation if ($uninstall !== TRUE) { return $uninstall; } else { $return_url['msg'] = 'fieldtype_uninstalled'; } } } if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'message' => lang('fieldtype_uninstalled') )); } else { ee()->functions->redirect($this->mod_link($return_url)); } } //END freeform_fieldtype_action // -------------------------------------------------------------------- /** * save field layout * * ajax called method for saving field layout in the entries screen * * @access public * @return string */ public function save_field_layout () { ee()->load->library('freeform_forms'); ee()->load->model('freeform_form_model'); $save_for = ee()->input->get_post('save_for', TRUE); $shown_fields = ee()->input->get_post('shown_fields', TRUE); $form_id = $this->get_post_or_zero('form_id'); $form_data = $this->data->get_form_info($form_id); // ------------------------------------- // valid // ------------------------------------- if ( ! $this->is_ajax_request() OR ! is_array($save_for) OR ! is_array($shown_fields) OR ! $form_data ) { return $this->send_ajax_response(array( 'success' => FALSE, 'message' => lang('invalid_input') )); } // ------------------------------------- // permissions? // ------------------------------------- //if (ee()->session->userdata('group_id') != 1 AND // ! $this->check_yes($this->preference('allow_user_field_layout')) //) //{ // return $this->send_ajax_response(array( // 'success' => FALSE, // 'message' => lang('invalid_permissions') // )); //} // ------------------------------------- // save // ------------------------------------- $field_layout_prefs = $this->preference('field_layout_prefs'); $original_prefs = ( is_array($field_layout_prefs) ? $field_layout_prefs : array() ); // ------------------------------------- // who is it for? // ------------------------------------- $for = array(); foreach ($save_for as $item) { //if this is for everyone, we can stop if (in_array($item, array('just_me', 'everyone'))) { $for = $item; break; } if ($this->is_positive_intlike($item)) { $for[] = $item; } } // ------------------------------------- // what do they want to see? // ------------------------------------- $standard_columns = $this->get_standard_column_names(); $possible_columns = $standard_columns; //build possible columns foreach ($form_data['fields'] as $field_id => $field_data) { $possible_columns[] = $field_id; } $data = array(); $prefix = ee()->freeform_form_model->form_field_prefix; //check for field validity, no funny business foreach ($shown_fields as $field_name) { $field_id = str_replace($prefix, '', $field_name); if (in_array($field_name, $standard_columns)) { $data[] = $field_name; unset( $possible_columns[ array_search( $field_name, $possible_columns ) ] ); } else if (in_array($field_id , array_keys($form_data['fields']))) { $data[] = $field_id; unset( $possible_columns[ array_search( $field_id, $possible_columns ) ] ); } } //removes holes sort($possible_columns); // ------------------------------------- // insert the data per group or all // ------------------------------------- $settings = array( 'visible' => $data, 'hidden' => $possible_columns ); if ($for == 'just_me') { $id = ee()->session->userdata('member_id'); $original_prefs['entry_layout_prefs']['member'][$id] = $settings; } else if ($for == 'everyone') { $original_prefs['entry_layout_prefs']['all']['visible'] = $settings; } else { foreach ($for as $who) { $original_prefs['entry_layout_prefs']['group'][$who]['visible'] = $settings; } } // ------------------------------------- // save // ------------------------------------- $this->data->set_module_preferences(array( 'field_layout_prefs' => json_encode($original_prefs) )); // ------------------------------------- // success! // ------------------------------------- //TODO test for ajax request or redirect back //don't want JS erorrs preventing this from //working $this->send_ajax_response(array( 'success' => TRUE, 'message' => lang('layout_saved'), 'update_fields' => array() )); //prevent EE CP default spit out exit(); } //END save_field_layout // -------------------------------------------------------------------- /** * save_form * * @access public * @return null */ public function save_form () { // ------------------------------------- // form ID? we must be editing // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $update = ($form_id != 0); // ------------------------------------- // default status // ------------------------------------- $default_status = ee()->input->get_post('default_status', TRUE); $default_status = ($default_status AND trim($default_status) != '') ? $default_status : $this->data->defaults['default_form_status']; // ------------------------------------- // composer return? // ------------------------------------- $do_composer = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer'); $composer_save_finish = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer_save_finish'); if ($composer_save_finish) { $do_composer = TRUE; } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // field name // ------------------------------------- $form_name = ee()->input->get_post('form_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $form_name OR ! trim($form_name)) { $errors['form_name'] = lang('form_name_required'); } else { $form_name = strtolower(trim($form_name)); if ( in_array($form_name, $this->data->prohibited_names ) ) { $errors['form_name'] = str_replace( '%name%', $form_name, lang('reserved_form_name') ); } //if the form_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $form_name) OR is_numeric($form_name)) { $errors['form_name'] = lang('form_name_can_only_contain'); } ee()->load->model('freeform_form_model'); //get dupe from field names $dupe_data = ee()->freeform_form_model->get_row(array( 'form_name' => $form_name )); //if we are updating, we don't want to error on the same field id if ( ! empty($dupe_data) AND ! ($update AND $dupe_data['form_id'] == $form_id)) { $errors['form_name'] = str_replace( '%name%', $form_name, lang('form_name_exists') ); } } // ------------------------------------- // form label // ------------------------------------- $form_label = ee()->input->get_post('form_label', TRUE); if ( ! $form_label OR ! trim($form_label) ) { $errors['form_label'] = lang('form_label_required'); } // ------------------------------------- // admin notification email // ------------------------------------- $admin_notification_email = ee()->input->get_post('admin_notification_email', TRUE); if ($admin_notification_email AND trim($admin_notification_email) != '') { ee()->load->helper('email'); $emails = preg_split( '/(\s+)?\,(\s+)?/', $admin_notification_email, -1, PREG_SPLIT_NO_EMPTY ); $errors['admin_notification_email'] = array(); foreach ($emails as $key => $email) { $emails[$key] = trim($email); if ( ! valid_email($email)) { $errors['admin_notification_email'][] = str_replace('%email%', $email, lang('non_valid_email')); } } if (empty($errors['admin_notification_email'])) { unset($errors['admin_notification_email']); } $admin_notification_email = implode('|', $emails); } else { $admin_notification_email = ''; } // ------------------------------------- // user email field // ------------------------------------- $user_email_field = ee()->input->get_post('user_email_field'); ee()->load->model('freeform_field_model'); $field_ids = ee()->freeform_field_model->key('field_id', 'field_id')->get(); if ($user_email_field AND $user_email_field !== '--' AND trim($user_email_field) !== '' AND ! in_array($user_email_field, $field_ids )) { $errors['user_email_field'] = lang('invalid_user_email_field'); } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } //send ajax response exists //but this is in case someone is using a replacer //that uses if ($this->check_yes(ee()->input->get_post('validate_only'))) { if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'errors' => array() )); } exit(); } // ------------------------------------- // field ids // ------------------------------------- $field_ids = array_filter( $this->actions()->pipe_split( ee()->input->get_post('field_ids', TRUE) ), array($this, 'is_positive_intlike') ); $sorted_field_ids = $field_ids; sort($sorted_field_ids); // ------------------------------------- // insert data // ------------------------------------- $data = array( 'form_name' => strip_tags($form_name), 'form_label' => strip_tags($form_label), 'default_status' => $default_status, 'user_notification_id' => $this->get_post_or_zero('user_notification_id'), 'admin_notification_id' => $this->get_post_or_zero('admin_notification_id'), 'admin_notification_email' => $admin_notification_email, 'form_description' => strip_tags(ee()->input->get_post('form_description', TRUE)), 'author_id' => ee()->session->userdata('member_id'), 'field_ids' => implode('|', $sorted_field_ids), 'field_order' => implode('|', $field_ids), 'notify_admin' => ( (ee()->input->get_post('notify_admin') == 'y') ? 'y' : 'n' ), 'notify_user' => ( (ee()->input->get_post('notify_user') == 'y') ? 'y' : 'n' ), 'user_email_field' => $user_email_field, ); //load the forms model if its not been already ee()->load->library('freeform_forms'); if ($do_composer) { unset($data['field_ids']); unset($data['field_order']); } if ($update) { unset($data['author_id']); if ( ! $do_composer) { $data['composer_id'] = 0; } ee()->freeform_forms->update_form($form_id, $data); } else { //we don't want this running on update, will only happen for dupes $composer_id = $this->get_post_or_zero('composer_id'); //this is a dupe and they want composer to dupe too? if ($do_composer AND $composer_id > 0) { ee()->load->model('freeform_composer_model'); $composer_data = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $composer_id) ->get_row(); if ($composer_data !== FALSE) { $data['composer_id'] = ee()->freeform_composer_model->insert( array( 'composer_data' => $composer_data['composer_data'], 'site_id' => ee()->config->item('site_id') ) ); } } $form_id = ee()->freeform_forms->create_form($data); } // ------------------------------------- // return // ------------------------------------- if ( ! $composer_save_finish AND $do_composer) { ee()->functions->redirect($this->mod_link(array( 'method' => 'form_composer', 'form_id' => $form_id, 'msg' => 'edit_form_success' ))); } //'save and finish, default' else { ee()->functions->redirect($this->mod_link(array( 'method' => 'forms', 'msg' => 'edit_form_success' ))); } } //END save_form // -------------------------------------------------------------------- /** * Save Entry * * @access public * @return null redirect */ public function save_entry () { // ------------------------------------- // edit? // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $entry_id = $this->get_post_or_zero('entry_id'); ee()->load->model('freeform_form_model'); ee()->load->model('freeform_entry_model'); ee()->load->library('freeform_forms'); ee()->load->library('freeform_fields'); $form_data = $this->data->get_form_info($form_id); // ------------------------------------- // valid form id // ------------------------------------- if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $previous_inputs = array(); if ( $entry_id > 0) { $entry_data = ee()->freeform_entry_model ->id($form_id) ->where('entry_id', $entry_id) ->get_row(); if ( ! $entry_data) { return $this->actions()->full_stop(lang('invalid_entry_id')); } $previous_inputs = $entry_data; } // ------------------------------------- // form data // ------------------------------------- $field_labels = array(); $valid_fields = array(); foreach ( $form_data['fields'] as $row) { $field_labels[$row['field_name']] = $row['field_label']; $valid_fields[] = $row['field_name']; } // ------------------------------------- // is this an edit? entry_id // ------------------------------------- $edit = ($entry_id AND $entry_id != 0); // ------------------------------------- // for hooks // ------------------------------------- $this->edit = $edit; $this->multipage = FALSE; $this->last_page = TRUE; // ------------------------------------- // prevalidate hook // ------------------------------------- $errors = array(); //to assist backward compat $this->field_errors = array(); if (ee()->extensions->active_hook('freeform_module_validate_begin') === TRUE) { $backup_errors = $errors; $errors = ee()->extensions->universal_call( 'freeform_module_validate_begin', $errors, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($errors) AND $this->check_yes($this->preference('hook_data_protection'))) { $errors = $backup_errors; } } // ------------------------------------- // validate // ------------------------------------- $field_input_data = array(); $field_list = array(); // ------------------------------------- // status? // ------------------------------------- $available_statuses = $this->data->get_form_statuses(); $status = ee()->input->get_post('status'); if ( ! array_key_exists($status, $available_statuses)) { $field_input_data['status'] = $this->data->defaults['default_form_status']; } else { $field_input_data['status'] = $status; } foreach ($form_data['fields'] as $field_id => $field_data) { $field_list[$field_data['field_name']] = $field_data['field_label']; $field_post = ee()->input->get_post($field_data['field_name']); //if it's not even in $_POST or $_GET, lets skip input //unless its an uploaded file, then we'll send false anyway //because its fieldtype will handle the rest of that work if ($field_post !== FALSE OR isset($_FILES[$field_data['field_name']])) { $field_input_data[$field_data['field_name']] = $field_post; } } //form fields do thier own validation, //so lets just get results! (sexy results?) $this->field_errors = array_merge( $this->field_errors, ee()->freeform_fields->validate( $form_id, $field_input_data ) ); // ------------------------------------- // post validate hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_validate_end') === TRUE) { $backup_errors = $errors; $errors = ee()->extensions->universal_call( 'freeform_module_validate_end', $errors, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($errors) AND $this->check_yes($this->preference('hook_data_protection'))) { $errors = $backup_errors; } } $errors = array_merge($errors, $this->field_errors); // ------------------------------------- // halt on errors // ------------------------------------- if (count($errors) > 0) { $this->actions()->full_stop($errors); } //send ajax response exists //but this is in case someone is using a replacer //that uses if ($this->check_yes(ee()->input->get_post('validate_only'))) { if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'errors' => array() )); } exit(); } // ------------------------------------- // entry insert begin hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_insert_begin') === TRUE) { $backup_field_input_data = $field_input_data; $field_input_data = ee()->extensions->universal_call( 'freeform_module_insert_begin', $field_input_data, $entry_id, $form_id, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($field_input_data) AND $this->check_yes($this->preference('hook_data_protection'))) { $field_input_data = $backup_field_input_data; } } // ------------------------------------- // insert/update data into db // ------------------------------------- if ($edit) { ee()->freeform_forms->update_entry( $form_id, $entry_id, $field_input_data ); } else { $entry_id = ee()->freeform_forms->insert_new_entry( $form_id, $field_input_data ); } // ------------------------------------- // entry insert begin hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_insert_end') === TRUE) { ee()->extensions->universal_call( 'freeform_module_insert_end', $field_input_data, $entry_id, $form_id, $this ); if (ee()->extensions->end_script === TRUE) return; } // ------------------------------------- // return // ------------------------------------- $success_line = ($edit) ? 'edit_entry_success' : 'new_entry_success'; if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'form_id' => $form_id, 'entry_id' => $entry_id, 'message' => lang($success_line), 'success' => TRUE )); } //'save and finish, default' else { ee()->functions->redirect($this->mod_link(array( 'method' => 'entries', 'form_id' => $form_id, 'msg' => $success_line ))); } } //END edit_entry // -------------------------------------------------------------------- /** * approve entries * * accepts ajax call to approve entries * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to approve * @return string */ public function approve_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // valid form id? // ------------------------------------- if ( ! $form_id OR $form_id <= 0) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->actions()->full_stop(lang('invalid_entry_id')); } // ------------------------------------- // approve! // ------------------------------------- $updates = array(); foreach($entry_ids as $entry_id) { $updates[] = array( 'entry_id' => $entry_id, 'status' => 'open' ); } ee()->load->model('freeform_form_model'); ee()->db->update_batch( ee()->freeform_form_model->table_name($form_id), $updates, 'entry_id' ); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); exit(); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'moderate_entries'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'form_id' => $form_id, 'msg' => 'entries_approved' ))); } } //END approve_entry // -------------------------------------------------------------------- /** * get/post form_id * * gets and validates the current form_id possibly passed * * @access private * @param bool validate form_id * @return mixed integer of passed in form_id or bool false */ private function get_post_form_id ($validate = TRUE) { $form_id = $this->get_post_or_zero('form_id'); if ($form_id == 0 OR ($validate AND ! $this->data->is_valid_form_id($form_id)) ) { return FALSE; } return $form_id; } //ENd get_post_form_id // -------------------------------------------------------------------- /** * get/post entry_ids * * gets and validates the current entry possibly passed * * @access private * @return mixed array of passed in entry_ids or bool false */ private function get_post_entry_ids () { $entry_ids = ee()->input->get_post('entry_ids'); if ( ! is_array($entry_ids) AND ! $this->is_positive_intlike($entry_ids)) { return FALSE; } if ( ! is_array($entry_ids)) { $entry_ids = array($entry_ids); } //clean and validate each as int $entry_ids = array_filter($entry_ids, array($this, 'is_positive_intlike')); if (empty($entry_ids)) { return FALSE; } return $entry_ids; } //END get_post_entry_ids // -------------------------------------------------------------------- /** * delete_confirm_entries * * accepts ajax call to delete entry * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to delete * @return string */ public function delete_confirm_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // ajax requests should be doing front // end delete confirm. This also handles // the ajax errors properly // ------------------------------------- if ( $this->is_ajax_request()) { return $this->delete_entries(); } // ------------------------------------- // form id? // ------------------------------------- if ( ! $form_id OR $form_id <= 0) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->show_error(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->show_error(lang('invalid_entry_id')); } // ------------------------------------- // return method? // ------------------------------------- $return_method = ee()->input->get_post('return_method'); $return_method = ($return_method AND is_callable(array($this, $return_method))) ? $return_method : 'entries'; // ------------------------------------- // confirmation page // ------------------------------------- return $this->delete_confirm( 'delete_entries', array( 'form_id' => $form_id, 'entry_ids' => $entry_ids, 'return_method' => $return_method ), 'confirm_delete_entries' ); } //END delete_confirm_entries // -------------------------------------------------------------------- /** * delete entries * * accepts ajax call to delete entry * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to delete * @return string */ public function delete_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // valid form id? // ------------------------------------- if ( ! $this->is_positive_intlike($form_id)) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->actions()->full_stop(lang('invalid_entry_id')); } ee()->load->library('freeform_forms'); $success = ee()->freeform_forms->delete_entries($form_id, $entry_ids); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success )); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'entries'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'form_id' => $form_id, 'msg' => 'entries_deleted' ))); } } //END delete_entries // -------------------------------------------------------------------- /** * Confirm Delete Fields * * @access public * @return html */ public function delete_confirm_fields () { //the following fields will be deleted //the following forms will be affected //they contain the forms.. $field_ids = ee()->input->get_post('field_id', TRUE); if ( ! is_array($field_ids) AND ! $this->is_positive_intlike($field_ids) ) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } //already checked for numeric :p if ( ! is_array($field_ids)) { $field_ids = array($field_ids); } $delete_field_confirmation = ''; $clean_field_ids = array(); foreach ($field_ids as $field_id) { if ($this->is_positive_intlike($field_id)) { $clean_field_ids[] = $field_id; } } if (empty($clean_field_ids)) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } // ------------------------------------- // build a list of forms affected by fields // ------------------------------------- ee()->db->where_in('field_id', $clean_field_ids); $all_field_data = ee()->db->get('freeform_fields'); $delete_field_confirmation = lang('delete_field_confirmation'); $extra_form_data = ''; foreach ($all_field_data->result_array() as $row) { //this doesn't get field data, so we had to above; $field_form_data = $this->data->get_form_info_by_field_id($row['field_id']); // ------------------------------------- // get each form affected by each field listed // and show the user what forms will be affected // ------------------------------------- if ( $field_form_data !== FALSE ) { $freeform_affected = array(); foreach ($field_form_data as $form_id => $form_data) { $freeform_affected[] = $form_data['form_label']; } $extra_form_data .= '<p>' . '<strong>' . $row['field_label'] . '</strong>: ' . implode(', ', $freeform_affected) . '</p>'; } } //if we have anything, add some extra warnings if ($extra_form_data != '') { $delete_field_confirmation .= '<p>' . lang('freeform_will_lose_data') . '</p>' . $extra_form_data; } return $this->delete_confirm( 'delete_fields', array('field_id' => $clean_field_ids), $delete_field_confirmation, 'delete', FALSE ); } //END delete_confirm_fields // -------------------------------------------------------------------- /** * utilities * * @access public * @return string */ public function utilities ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('utilities')); $this->set_highlight('module_utilities'); //-------------------------------------- // Counts //-------------------------------------- ee()->load->library('freeform_migration'); $this->cached_vars['counts'] = ee()->freeform_migration->get_collection_counts(); // $test = ee()->freeform_migration->create_upload_field( 1, 'goff', array( 'file_upload_location' => '1' ) ); // print_r( $test ); print_r( ee()->freeform_migration->get_errors() ); //-------------------------------------- // File upload field installed? //-------------------------------------- $this->cached_vars['file_upload_installed'] = ee()->freeform_migration->get_field_type_installed('file_upload'); $query = ee()->db->query( "SELECT * FROM exp_freeform_fields WHERE field_type = 'file_upload'" ); //-------------------------------------- // Load vars //-------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'migrate_collections' )); //-------------------------------------- // Load page //-------------------------------------- $this->cached_vars['current_page'] = $this->view( 'utilities.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } // End utilities // -------------------------------------------------------------------- /** * Confirm Uninstall Fieldtypes * * @access public * @return html */ public function uninstall_confirm_fieldtype ($name = '') { $name = trim($name); if ($name == '') { ee()->functions->redirect($this->base); } ee()->load->model('freeform_field_model'); $items = ee()->freeform_field_model ->key('field_label', 'field_label') ->get(array('field_type' => $name)); if ($items == FALSE) { return $this->uninstall_fieldtype($name); } else { $confirmation = '<p>' . lang('following_fields_converted') . ': <strong>'; $confirmation .= implode(', ', $items) . '</strong></p>'; return $this->delete_confirm( 'uninstall_fieldtype', array('fieldtype' => $name), $confirmation, 'uninstall', FALSE ); } } //END uninstall_confirm_fieldtype // -------------------------------------------------------------------- /** * Uninstalls fieldtypes * * @access public * @param string $name fieldtype name to remove * @return void */ public function uninstall_fieldtype ($name = '', $redirect = TRUE) { if ($name == '') { $name = ee()->input->get_post('fieldtype', TRUE); } if ( ! $name) { $this->actions()->full_stop(lang('no_fieldtypes_submitted')); } ee()->load->library('freeform_fields'); $success = ee()->freeform_fields->uninstall_fieldtype($name); if ( ! $redirect) { return $success; } if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success, 'message' => lang('fieldtype_uninstalled'), )); } else { ee()->functions->redirect($this->mod_link(array( 'method' => 'fieldtypes', 'msg' => 'fieldtype_uninstalled' ))); } } //END uninstall_fieldtype // -------------------------------------------------------------------- /** * Delete Fields * * @access public * @return void */ public function delete_fields () { // ------------------------------------- // safety goggles // ------------------------------------- // $field_ids = ee()->input->get_post('field_id', TRUE); if ( ! is_array($field_ids) AND ! $this->is_positive_intlike($field_ids) ) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } //already checked for numeric :p if ( ! is_array($field_ids)) { $field_ids = array($field_ids); } // ------------------------------------- // delete fields // ------------------------------------- ee()->load->library('freeform_fields'); ee()->freeform_fields->delete_field($field_ids); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); } else { ee()->functions->redirect($this->mod_link(array( 'method' => 'fields', 'msg' => 'fields_deleted' ))); } } //END delete_fields // -------------------------------------------------------------------- /** * Confirm deletion of notifications * * accepts ajax call to delete notification * * @access public * @param int form id * @param mixed array or int of notification ids to delete * @return string */ public function delete_confirm_notification ($notification_id = 0) { // ------------------------------------- // ajax requests should be doing front // end delete confirm. This also handles // the ajax errors properly // ------------------------------------- if ( $this->is_ajax_request()) { return $this->delete_notification(); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $notification_id = ee()->input->get_post('notification_id'); } if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $this->actions()->full_stop(lang('invalid_notification_id')); } if ( is_array($notification_id)) { $notification_id = array_filter( $notification_id, array($this, 'is_positive_intlike') ); } else { $notification_id = array($notification_id); } // ------------------------------------- // confirmation page // ------------------------------------- return $this->delete_confirm( 'delete_notification', array( 'notification_id' => $notification_id, 'return_method' => 'notifications' ), 'confirm_delete_notification' ); } //END delete_confirm_notification // -------------------------------------------------------------------- /** * Delete Notifications * * @access public * @param integer $notification_id notification * @return null */ public function delete_notification ($notification_id = 0) { // ------------------------------------- // entry ids? // ------------------------------------- if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $notification_id = ee()->input->get_post('notification_id'); } if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $this->actions()->full_stop(lang('invalid_notification_id')); } if ( is_array($notification_id)) { $notification_id = array_filter( $notification_id, array($this, 'is_positive_intlike') ); } else { $notification_id = array($notification_id); } ee()->load->model('freeform_notification_model'); $success = ee()->freeform_notification_model ->where_in('notification_id', $notification_id) ->delete(); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success )); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'notifications'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'msg' => 'delete_notification_success' ))); } } //END delete_notification // -------------------------------------------------------------------- /** * save_field * * @access public * @return void (redirect) */ public function save_field () { // ------------------------------------- // field ID? we must be editing // ------------------------------------- $field_id = $this->get_post_or_zero('field_id'); $update = ($field_id != 0); // ------------------------------------- // yes or no items (all default yes) // ------------------------------------- $y_or_n = array('submissions_page', 'moderation_page', 'composer_use'); foreach ($y_or_n as $item) { //set as local var $$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y'; } // ------------------------------------- // field instance // ------------------------------------- $field_type = ee()->input->get_post('field_type', TRUE); ee()->load->library('freeform_fields'); ee()->load->model('freeform_field_model'); $available_fieldtypes = ee()->freeform_fields->get_available_fieldtypes(); //get the update with previous settings if this is an edit if ($update) { $field = ee()->freeform_field_model ->where('field_id', $field_id) ->where('field_type', $field_type) ->count(); //make sure that we have the correct type just in case they //are changing type like hooligans if ($field) { $field_instance =& ee()->freeform_fields->get_field_instance($field_id); } else { $field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type); } } else { $field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type); } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // field name // ------------------------------------- $field_name = ee()->input->get_post('field_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $field_name OR ! trim($field_name)) { $errors['field_name'] = lang('field_name_required'); } else { $field_name = strtolower(trim($field_name)); if ( in_array($field_name, $this->data->prohibited_names ) ) { $errors['field_name'] = str_replace( '%name%', $field_name, lang('freeform_reserved_field_name') ); } //if the field_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $field_name) OR is_numeric($field_name)) { $errors['field_name'] = lang('field_name_can_only_contain'); } //get dupe from field names $f_query = ee()->db->select('field_name, field_id')->get_where( 'freeform_fields', array('field_name' => $field_name) ); //if we are updating, we don't want to error on the same field id if ($f_query->num_rows() > 0 AND ! ($update AND $f_query->row('field_id') == $field_id)) { $errors['field_name'] = str_replace( '%name%', $field_name, lang('field_name_exists') ); } } // ------------------------------------- // field label // ------------------------------------- $field_label = ee()->input->get_post('field_label', TRUE); if ( ! $field_label OR ! trim($field_label) ) { $errors['field_label'] = lang('field_label_required'); } // ------------------------------------- // field type // ------------------------------------- if ( ! $field_type OR ! array_key_exists($field_type, $available_fieldtypes)) { $errors['field_type'] = lang('invalid_fieldtype'); } // ------------------------------------- // field settings errors? // ------------------------------------- $field_settings_validate = $field_instance->validate_settings(); if ( $field_settings_validate !== TRUE) { if (is_array($field_settings_validate)) { $errors['field_settings'] = $field_settings_validate; } else if (! empty($field_instance->errors)) { $errors['field_settings'] = $field_instance->errors; } else { $errors['field_settings'] = lang('field_settings_error'); } } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } if ($this->check_yes(ee()->input->get_post('validate_only')) AND $this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); } // ------------------------------------- // insert data // ------------------------------------- $data = array( 'field_name' => strip_tags($field_name), 'field_label' => strip_tags($field_label), 'field_type' => $field_type, 'edit_date' => '0', //overridden if update 'field_description' => strip_tags(ee()->input->get_post('field_description', TRUE)), 'submissions_page' => $submissions_page, 'moderation_page' => $moderation_page, 'composer_use' => $composer_use, 'settings' => json_encode($field_instance->save_settings()) ); if ($update) { ee()->freeform_field_model->update( array_merge( $data, array( 'edit_date' => ee()->localize->now ) ), array('field_id' => $field_id) ); } else { $field_id = ee()->freeform_field_model->insert( array_merge( $data, array( 'author_id' => ee()->session->userdata('member_id'), 'entry_date' => ee()->localize->now, 'site_id' => ee()->config->item('site_id') ) ) ); } $field_instance->field_id = $field_id; $field_instance->post_save_settings(); $field_in_forms = array(); if ($update) { $field_in_forms = $this->data->get_form_info_by_field_id($field_id); if ($field_in_forms) { $field_in_forms = array_keys($field_in_forms); } else { $field_in_forms = array(); } } $form_ids = ee()->input->get_post('form_ids'); if ($form_ids !== FALSE) { $form_ids = preg_split( '/\|/', $form_ids, -1, PREG_SPLIT_NO_EMPTY ); } else { $form_ids = array(); } if ( ! (empty($form_ids) AND empty($field_in_forms))) { $remove = array_unique(array_diff($field_in_forms, $form_ids)); $add = array_unique(array_diff($form_ids, $field_in_forms)); ee()->load->library('freeform_forms'); foreach ($add as $add_id) { ee()->freeform_forms->add_field_to_form($add_id, $field_id); } foreach ($remove as $remove_id) { ee()->freeform_forms->remove_field_from_form($remove_id, $field_id); } } // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $return = array( 'success' => TRUE, 'field_id' => $field_id, ); if ($this->check_yes(ee()->input->get_post('include_field_data'))) { $return['composerFieldData'] = $this->composer_field_data($field_id, NULL, TRUE); } $this->send_ajax_response($return); } else { //redirect back to fields on success ee()->functions->redirect($this->mod_link(array( 'method' => 'fields', 'msg' => 'edit_field_success' ))); } } //END save_field // -------------------------------------------------------------------- /** * save_notification * * @access public * @return null (redirect) */ public function save_notification () { // ------------------------------------- // notification ID? we must be editing // ------------------------------------- $notification_id = $this->get_post_or_zero('notification_id'); $update = ($notification_id != 0); // ------------------------------------- // yes or no items (default yes) // ------------------------------------- $y_or_n = array('wordwrap'); foreach ($y_or_n as $item) { //set as local var $$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y'; } // ------------------------------------- // yes or no items (default no) // ------------------------------------- $n_or_y = array('allow_html', 'include_attachments'); foreach ($n_or_y as $item) { //set as local var $$item = $this->check_yes(ee()->input->get_post($item)) ? 'y' : 'n'; } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // notification name // ------------------------------------- $notification_name = ee()->input->get_post('notification_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $notification_name OR ! trim($notification_name)) { $errors['notification_name'] = lang('notification_name_required'); } else { $notification_name = strtolower(trim($notification_name)); if ( in_array($notification_name, $this->data->prohibited_names ) ) { $errors['notification_name'] = str_replace( '%name%', $notification_name, lang('reserved_notification_name') ); } //if the field_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $notification_name) OR is_numeric($notification_name)) { $errors['notification_name'] = lang('notification_name_can_only_contain'); } //get dupe from field names ee()->db->select('notification_name, notification_id'); $f_query = ee()->db->get_where( 'freeform_notification_templates', array( 'notification_name' => $notification_name ) ); //if we are updating, we don't want to error on the same field id if ($f_query->num_rows() > 0 AND ! ($update AND $f_query->row('notification_id') == $notification_id)) { $errors['notification_name'] = str_replace( '%name%', $notification_name, lang('notification_name_exists') ); } } // ------------------------------------- // notification label // ------------------------------------- $notification_label = ee()->input->get_post('notification_label', TRUE); if ( ! $notification_label OR ! trim($notification_label) ) { $errors['notification_label'] = lang('notification_label_required'); } ee()->load->helper('email'); // ------------------------------------- // notification email // ------------------------------------- $from_email = ee()->input->get_post('from_email', TRUE); if ($from_email AND trim($from_email) != '') { $from_email = trim($from_email); //allow tags if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $from_email)) { if ( ! valid_email($from_email)) { $errors['from_email'] = str_replace( '%email%', $from_email, lang('non_valid_email') ); } } } // ------------------------------------- // from name // ------------------------------------- $from_name = ee()->input->get_post('from_name', TRUE); if ( ! $from_name OR ! trim($from_name) ) { //$errors['from_name'] = lang('from_name_required'); } // ------------------------------------- // reply to email // ------------------------------------- $reply_to_email = ee()->input->get_post('reply_to_email', TRUE); if ($reply_to_email AND trim($reply_to_email) != '') { $reply_to_email = trim($reply_to_email); //allow tags if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $reply_to_email)) { if ( ! valid_email($reply_to_email)) { $errors['reply_to_email'] = str_replace( '%email%', $reply_to_email, lang('non_valid_email') ); } } } else { $reply_to_email = ''; } // ------------------------------------- // email subject // ------------------------------------- $email_subject = ee()->input->get_post('email_subject', TRUE); if ( ! $email_subject OR ! trim($email_subject) ) { $errors['email_subject'] = lang('email_subject_required'); } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } //ajax checking? else if ($this->check_yes(ee()->input->get_post('validate_only'))) { return $this->send_ajax_response(array( 'success' => TRUE )); } // ------------------------------------- // insert data // ------------------------------------- $data = array( 'notification_name' => strip_tags($notification_name), 'notification_label' => strip_tags($notification_label), 'notification_description' => strip_tags(ee()->input->get_post('notification_description', TRUE)), 'wordwrap' => $wordwrap, 'allow_html' => $allow_html, 'from_name' => $from_name, 'from_email' => $from_email, 'reply_to_email' => $reply_to_email, 'email_subject' => strip_tags($email_subject), 'template_data' => ee()->input->get_post('template_data'), 'include_attachments' => $include_attachments ); ee()->load->model('freeform_notification_model'); if ($update) { ee()->freeform_notification_model->update( $data, array('notification_id' => $notification_id) ); } else { $notification_id = ee()->freeform_notification_model->insert( array_merge( $data, array( 'site_id' => ee()->config->item('site_id') ) ) ); } // ------------------------------------- // ajax? // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'notification_id' => $notification_id )); } else { //redirect back to fields on success ee()->functions->redirect($this->mod_link(array( 'method' => 'notifications', 'msg' => 'edit_notification_success' ))); } } //END save_notification // -------------------------------------------------------------------- /** * Sets the menu highlight and assists with permissions (Freeform Pro) * * @access protected * @param string $menu_item The menu item to highlight */ protected function set_highlight($menu_item = 'module_forms') { $this->cached_vars['module_menu_highlight'] = $menu_item; } //END set_highlight // -------------------------------------------------------------------- /** * save_preferences * * @access public * @return null (redirect) */ public function save_preferences() { //defaults are in data.freeform.php $prefs = array(); $all_prefs = array_merge( $this->data->default_preferences, $this->data->default_global_preferences ); //check post input for all existing prefs and default if not present foreach($all_prefs as $pref_name => $data) { $input = ee()->input->get_post($pref_name, TRUE); //default $output = $data['value']; //int if ($data['type'] == 'int' AND $this->is_positive_intlike($input, -1)) { $output = $input; } //yes or no elseif ($data['type'] == 'y_or_n' AND in_array(trim($input), array('y', 'n'), TRUE)) { $output = trim($input); } //list of items //this seems nutty, but this serializes the list of items elseif ($data['type'] == 'list') { //lotses? if (is_array($input)) { $temp_input = array(); foreach ($input as $key => $value) { if (trim($value) !== '') { $temp_input[] = trim($value); } } $output = json_encode($temp_input); } //just one :/ else if (trim($input) !== '') { $output = json_encode(array(trim($input))); } } //text areas elseif ($data['type'] == 'text' OR $data['type'] == 'textarea' ) { $output = trim($input); } $prefs[$pref_name] = $output; } //send all prefs to DB $this->data->set_module_preferences($prefs); // ---------------------------------- // Redirect to Homepage with Message // ---------------------------------- ee()->functions->redirect( $this->base . AMP . 'method=preferences' . AMP . 'msg=preferences_updated' ); } //END save_preferences // -------------------------------------------------------------------- /** * Export Entries * * Calls entries with proper flags to cue export * * @access public * @return mixed forces a download of the exported items or error */ public function export_entries () { $moderate = (ee()->input->get_post('moderate') == 'true'); return $this->entries(NULL, $moderate, TRUE); } //END export_entries // -------------------------------------------------------------------- /** * get_standard_column_names * * gets the standard column names and replaces author_id with author * * @access private * @return null */ private function get_standard_column_names() { $standard_columns = array_keys( ee()->freeform_form_model->default_form_table_columns ); array_splice( $standard_columns, array_search('author_id', $standard_columns), 1, 'author' ); return $standard_columns; } //END get_standard_column_names // -------------------------------------------------------------------- /** * mod_link * * makes $this->base . AMP . 'key=value' out of arrays * * @access public * @param array key value pair of get vars to add to base * @param bool $real_amp use a real ampersand? * @return string */ private function mod_link ($vars = array(), $real_amp = FALSE) { $link = $this->base; $amp = $real_amp ? '&' : AMP; if ($real_amp) { $link = str_replace(AMP, '&', $link); } else { //Swap all to regular amp first so we don't get false //positives. Could do this with negative lookups, but //those are spottier than this. $link = str_replace('&', AMP, str_replace(AMP, '&', $link)); } if ( ! empty($vars)) { foreach ($vars as $key => $value) { $link .= $amp . $key . '=' . $value; } } return $link; } //END mod_link // -------------------------------------------------------------------- /** * load_fancybox * * loads fancybox jquery UI plugin and its needed css * * @access private * @return null */ private function load_fancybox() { //so currently the fancybox setup inlucded in EE doesn't get built //automaticly and requires relying on the current CP theme. //Dislike. Inlcuding our own version instead. //Seems fancy box has also been removed from some later versions //of EE, so instinct here was correct. $css_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.css'; $js_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.pack.js'; ee()->cp->add_to_head('<link href="' . $css_link . '" type="text/css" rel="stylesheet" media="screen" />'); ee()->cp->add_to_foot('<script src="' . $js_link . '" type="text/javascript"></script>'); } //END load_fancybox // -------------------------------------------------------------------- /** * freeform_add_right_link * * abstractor for cp add_right_link so freeform can move it how it needs * when an alternate style is chosen * * @access private * @param string words of link to display * @param string link to display * @return null */ private function freeform_add_right_link ($lang, $link) { $this->cached_vars['inner_nav_links'][$lang] = $link; //return $this->add_right_link($lang, $link); } //END freeform_add_right_link // -------------------------------------------------------------------- /** * Module Upgrading * * This function is not required by the 1.x branch of ExpressionEngine by default. However, * as the install and deinstall ones are, we are just going to keep the habit and include it * anyhow. * - Originally, the $current variable was going to be passed via parameter, but as there might * be a further use for such a variable throughout the module at a later date we made it * a class variable. * * * @access public * @return bool */ public function freeform_module_update() { if ( ! isset($_POST['run_update']) OR $_POST['run_update'] != 'y') { $this->add_crumb(lang('update_freeform_module')); $this->build_crumbs(); $this->cached_vars['form_url'] = $this->base . '&msg=update_successful'; if ($this->pro_update) { $this->cached_vars['form_url'] .= "&update_pro=true"; } $this->cached_vars['current_page'] = $this->view( 'update_module.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } require_once $this->addon_path . 'upd.freeform.php'; $U = new Freeform_upd(); if ($U->update() !== TRUE) { return ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => lang('update_failure') ))); } else { return ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => lang('update_successful') ))); } } // END freeform_module_update() // -------------------------------------------------------------------- /** * Visible Columns * * @access protected * @param $possible_columns possible columns * @return array array of visible columns */ protected function visible_columns ($standard_columns = array(), $possible_columns = array()) { // ------------------------------------- // get column settings // ------------------------------------- $column_settings = array(); ee()->load->model('freeform_form_model'); $field_layout_prefs = $this->preference('field_layout_prefs'); $member_id = ee()->session->userdata('member_id'); $group_id = ee()->session->userdata('group_id'); $f_prefix = ee()->freeform_form_model->form_field_prefix; //¿existe? Member? Group? all? if ($field_layout_prefs) { //$field_layout_prefs = json_decode($field_layout_prefs, TRUE); $entry_layout_prefs = ( isset($field_layout_prefs['entry_layout_prefs']) ? $field_layout_prefs['entry_layout_prefs'] : FALSE ); if ($entry_layout_prefs) { if (isset($entry_layout_prefs['member'][$member_id])) { $column_settings = $entry_layout_prefs['member'][$member_id]; } else if (isset($entry_layout_prefs['all'])) { $column_settings = $entry_layout_prefs['all']; } else if (isset($entry_layout_prefs['group'][$group_id])) { $column_settings = $entry_layout_prefs['group'][$group_id]; } } } //if a column is missing, we don't want to error //and if its newer than the settings, show it by default //settings are also in order of appearence here. //we also store the field ids without the prefix //in case someone changed it. That would probably //hose everything, but who knows? ;) if ( ! empty($column_settings)) { $to_sort = array(); //we are going over possible instead of settings in case something //is new or an old column is missing foreach ($possible_columns as $cid) { //if these are new, put them at the end if (! in_array($cid, $column_settings['visible']) AND ! in_array($cid, $column_settings['hidden']) ) { $to_sort[$cid] = $cid; } } //now we want columns from the settings order to go first //this way stuff thats not been removed gets to keep settings foreach ($column_settings['visible'] as $ecid) { if (in_array($ecid, $possible_columns)) { //since we are getting our real results now //we can add the prefixes if ( ! in_array($ecid, $standard_columns) ) { $ecid = $f_prefix . $ecid; } $visible_columns[] = $ecid; } } //and if we have anything left over (new fields probably) //its at the end if (! empty($to_sort)) { foreach ($to_sort as $tsid) { //since we are getting our real results now //we can add the prefixes if ( ! in_array($tsid, $standard_columns) ) { $tsid = $f_prefix . $tsid; } $visible_columns[] = $tsid; } } } //if we don't have any settings, just toss it all in in order else { foreach ($possible_columns as $pcid) { if ( ! in_array($pcid, $standard_columns) ) { $pcid = $f_prefix . $pcid; } $visible_columns[] = $pcid; } //in theory it should always be there if prefs are empty ... $default_hide = array('site_id', 'entry_id', 'complete'); foreach ($default_hide as $hide_me_seymour) { if (in_array($hide_me_seymour, $visible_columns)) { unset( $visible_columns[ array_search( $hide_me_seymour, $visible_columns ) ] ); } } //fix keys, but preserve order $visible_columns = array_merge(array(), $visible_columns); } return $visible_columns; } //END visible_columns // -------------------------------------------------------------------- /** * Format CP date * * @access public * @param mixed $date unix time * @return string unit time formatted to cp date formatting pref */ public function format_cp_date($date) { return $this->actions()->format_cp_date($date); } //END format_cp_date // -------------------------------------------------------------------- /** * Send AJAX response * * Outputs and exit either an HTML string or a * JSON array with the Profile disabled and correct * headers sent. * * @access public * @param string|array String is sent as HTML, Array is sent as JSON * @param bool Is this an error message? * @param bool bust cache for JSON? * @return void */ public function send_ajax_response($msg, $error = FALSE, $cache_bust = TRUE) { $this->restore_xid(); parent::send_ajax_response($msg, $error, $cache_bust); } //END send_ajax_response // -------------------------------------------------------------------- /** * EE 2.7+ restore xid with version check * @access public * @return voic */ public function restore_xid() { //deprecated in 2.8. Weeee! if (version_compare($this->ee_version, '2.7', '>=') && version_compare($this->ee_version, '2.8', '<')) { ee()->security->restore_xid(); } } //END restore_xid } // END CLASS Freeform
cfox89/EE-Integration-to-API
system/expressionengine/third_party/freeform/mcp.freeform.php
PHP
mit
159,782
/* exported Qualifications */ function Qualifications(skills, items) { var requirements = { 'soldier': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 3 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 3 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.flakArmor, level: 3 }, { skill: skills.engineer.nanoArmorKit, level: 4 }, { skill: skills.engineer.tankMine, level: 1 } ], equipment: [] }, 'Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 3 }, { skill: skills.medic.medicalApplicator, level: 4 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.advancedMobileStation, level: 1 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 0 } ], equipment: [] } } }, 'veteran': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 1 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.c4, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 2 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.nanoArmorKit, level: 6 }, { skill: skills.engineer.claymoreMine, level: 2 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.ammunitionPackage, level: 3 }, { skill: skills.engineer.stickyGrenade, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] }, 'Medic': { certifications: [ { skill: skills.medic.medicalApplicator, level: 6 }, { skill: skills.medic.nanoRegenDevice, level: 6 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.advancedEquipmentTerminalHacking, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.blockadeArmor, level: 3 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 2 } ], equipment: [] } } }, 'medic': { meta: { passPercentage: 100 }, classes: { 'Loadout: Offensive Medic': { certifications: [ { skill: skills.medic.grenadeBandolier, level: 2 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.nanoRegenDevice, level: 6 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] }, 'Loadout: Defensive Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 4 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.regenerationField, level: 5 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] } } }, 'engineer': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.claymoreMine, level: 2 } ], equipment: [ items.weapon.trac5s ] }, 'Loadout: Anti-Vehicle MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.avManaTurret, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] } } }, 'lightAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Bounty Hunter': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 4 }, { skill: skills.lightAssault.jumpJets, level: 6 }, { skill: skills.lightAssault.flashGrenade, level: 1 } ], equipment: [] }, 'Loadout: Death From Above': { certifications: [ { skill: skills.lightAssault.grenadeBandolier, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 5 }, { skill: skills.lightAssault.smokeGrenade, level: 1 } ], equipment: [] } } }, 'infiltrator': { meta: { passPercentage: 100 }, classes: { 'Loadout: Close Quarters': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 4 }, { skill: skills.infiltrator.grenadeBandolier, level: 2 }, { skill: skills.infiltrator.reconDetectDevice, level: 6 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.empGrenade, level: 1 } ], equipment: [ items.weapon.ns7pdw ] }, 'Loadout: Assassin': { certifications: [ { skill: skills.infiltrator.ammunitionBelt, level: 3 }, { skill: skills.infiltrator.motionSpotter, level: 5 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.decoyGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.rams ] } } }, 'heavyAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.heavyAssault.grenadeBandolier, level: 2 }, { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.concussionGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.decimator ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.c4, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 } ], equipment: [ items.weapon.skep, items.weapon.grounder ] } } }, 'maxUnit': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftMercy, items.max.rightMercy ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftPounder, items.max.rightPounder ] }, 'Loadout: Anti-Air': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftBurster, items.max.rightBurster ] } } }, 'basicTanks': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 1 } ], equipment: [ items.prowler.walker ] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] } } }, 'sunderer': { meta: { passPercentage: 100 }, classes: { 'Sunderer': { certifications: [ { skill: skills.sunderer.mineGuard, level: 4 }, { skill: skills.sunderer.blockadeArmor, level: 4 }, { skill: skills.sunderer.gateShieldDiffuser, level: 3 }, { skill: skills.sunderer.naniteProximityRepairSystem, level: 6 } ], equipment: [] } } }, 'prowler': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 4 }, { skill: skills.prowler.mineGuard, level: 4 } ], equipment: [ items.prowler.p2120ap, items.prowler.halberd ] } } }, 'lightning': { meta: { passPercentage: 100 }, classes: { 'Lightning': { certifications: [ { skill: skills.lightning.reinforcedTopArmor, level: 1 } ], equipment: [ items.lightning.skyguard ] } } }, 'harasser': { meta: { passPercentage: 100 }, classes: { 'Harasser': { certifications: [ { skill: skills.harasser.fireSuppressionSystem, level: 4 }, { skill: skills.harasser.compositeArmor, level: 4 }, { skill: skills.harasser.turbo, level: 5 } ], equipment: [ items.harasser.halberd ] } } }, 'commander': { meta: { passPercentage: 100 }, classes: { 'Squad Leader': { certifications: [ { skill: skills.squadLeader.commandCommChannel, level: 1 }, { skill: skills.squadLeader.requestReinforcements, level: 1 }, { skill: skills.squadLeader.rallyPointGreen, level: 1 }, { skill: skills.squadLeader.rallyPointOrange, level: 1 }, { skill: skills.squadLeader.rallyPointPurple, level: 1 }, { skill: skills.squadLeader.rallyPointYellow, level: 1 }, { skill: skills.squadLeader.priorityDeployment, level: 4 } ], equipment: [] } } } }, echoHavoc = qual('Echo Havoc', null, null, true), max = qual('MAX', echoHavoc, requirements.maxUnit), heavyAssault = qual('Heavy Assault', max, requirements.heavyAssault), echoCovertOps = qual('Echo Covert Ops', null, null, true), infiltrator = qual('Infiltrator', echoCovertOps, requirements.infiltrator), lightAssault = qual('Light Assault', infiltrator, requirements.lightAssault), echoSpecialist = qual('Echo Specialist', null, null, true), engineer = qual('Engineer', echoSpecialist, requirements.engineer), combatMedic = qual('Combat Medic', engineer, requirements.medic), commander = qual('Commander', null, requirements.commander, true), sunderer = qual('Sunderer', [ echoSpecialist, echoCovertOps, echoHavoc ], requirements.sunderer), harasser = qual('Harasser', null, requirements.harasser), lightning = qual('Lightning', harasser, requirements.lightning), prowler = qual('Prowler', lightning, requirements.prowler), basicTanks = qual('Basic Tanks', [ sunderer, prowler ], requirements.basicTanks), veteran = qual('Veteran', [ combatMedic, lightAssault, heavyAssault, commander ], requirements.veteran, true), soldier = qual('Soldier', [ veteran, basicTanks ], requirements.soldier, true); addParentRelationships(soldier); return soldier; function qual(name, child, certs, isRank) { var obj = {}; obj.name = name; if (child) { if ($.isArray(child)) { obj.child = child; } else { obj.child = [ child ]; } } if (certs) { obj.cert = certs; } if (isRank) { obj.isRank = true; } return obj; } function addParentRelationships(rank, parent) { if (parent) { if (rank.parent) { rank.parent.push(parent); } else { rank.parent = [ parent ]; } } if (rank.child) { $.each(rank.child, function() { addParentRelationships(this, rank); }); } } }
stevenbenner/ps2-equipment-check
js/qualifications.js
JavaScript
mit
12,343
package addonloader.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Properties; /** * Simple wrapper around {@link Properites}, * allowing to easily access objects. * @author Enginecrafter77 */ public class ObjectSettings extends Properties{ private static final long serialVersionUID = -8939834947658913650L; private final File path; public ObjectSettings(File path) throws FileNotFoundException, IOException { this.path = path; this.load(new FileReader(path)); } public ObjectSettings(String path) throws FileNotFoundException, IOException { this(new File(path)); } public boolean getBoolean(String key, boolean def) { return Boolean.parseBoolean(this.getProperty(key, String.valueOf(def))); } public int getInteger(String key, int def) { return Integer.parseInt(this.getProperty(key, String.valueOf(def))); } public float getFloat(String key, float def) { return Float.parseFloat(this.getProperty(key, String.valueOf(def))); } public void set(String key, Object val) { this.setProperty(key, val.toString()); } public void store(String comment) { try { this.store(new FileOutputStream(path), comment); } catch(IOException e) { e.printStackTrace(); } } }
Enginecrafter77/LMPluger
src/addonloader/util/ObjectSettings.java
Java
mit
1,423
print ARGF.read.gsub!(/\B[a-z]+\B/) {|x| x.split('').sort_by{rand}.join}
J-Y/RubyQuiz
ruby_quiz/quiz76_sols/solutions/Himadri Choudhury/scramble.rb
Ruby
mit
73
import { useEffect, useRef, useState } from "react" import * as React from "react" import { RelayPaginationProp, RelayRefetchProp, createPaginationContainer, } from "react-relay" import { graphql } from "relay-runtime" import Waypoint from "react-waypoint" import { Box, Flex, Spacer, Spinner } from "@artsy/palette" import compact from "lodash/compact" import styled from "styled-components" import { extractNodes } from "v2/Utils/extractNodes" import { ItemFragmentContainer } from "./Item" import { Reply } from "./Reply" import { ConversationMessagesFragmentContainer as ConversationMessages } from "./ConversationMessages" import { ConversationHeader } from "./ConversationHeader" import { ConfirmArtworkModalQueryRenderer } from "./ConfirmArtworkModal" import { BuyerGuaranteeMessage } from "./BuyerGuaranteeMessage" import { returnOrderModalDetails } from "../Utils/returnOrderModalDetails" import { OrderModal } from "./OrderModal" import { UnreadMessagesToastQueryRenderer } from "./UnreadMessagesToast" import useOnScreen from "../Utils/useOnScreen" import { UpdateConversation } from "../Mutation/UpdateConversationMutation" import { Conversation_conversation } from "v2/__generated__/Conversation_conversation.graphql" import { useRouter } from "v2/System/Router/useRouter" export interface ConversationProps { conversation: Conversation_conversation showDetails: boolean setShowDetails: (showDetails: boolean) => void relay: RelayPaginationProp refetch: RelayRefetchProp["refetch"] } export const PAGE_SIZE: number = 15 const Loading: React.FC = () => ( <SpinnerContainer> <Spinner /> </SpinnerContainer> ) const Conversation: React.FC<ConversationProps> = props => { const { conversation, relay, showDetails, setShowDetails } = props const liveArtwork = conversation?.items?.[0]?.liveArtwork const artwork = liveArtwork?.__typename === "Artwork" ? liveArtwork : null const isOfferable = !!artwork && !!artwork?.isOfferableFromInquiry const [showConfirmArtworkModal, setShowConfirmArtworkModal] = useState< boolean >(false) const inquiryItemBox = compact(conversation.items).map((i, idx) => { const isValidType = i.item?.__typename === "Artwork" || i.item?.__typename === "Show" return ( <ItemFragmentContainer item={i.item!} key={isValidType ? i.item?.id : idx} /> ) }) // ORDERS const [showOrderModal, setShowOrderModal] = useState<boolean>(false) const activeOrder = extractNodes(conversation.orderConnection)[0] let orderID let kind if (activeOrder) { kind = activeOrder.buyerAction orderID = activeOrder.internalID } const { url, modalTitle } = returnOrderModalDetails({ kind: kind!, orderID: orderID, }) // SCROLLING AND FETCHING // States and Refs const bottomOfMessageContainer = useRef<HTMLElement>(null) const initialMount = useRef(true) const initialScroll = useRef(true) const scrollContainer = useRef<HTMLDivElement>(null) const [fetchingMore, setFetchingMore] = useState<boolean>(false) const [lastMessageID, setLastMessageID] = useState<string | null>() const [lastOrderUpdate, setLastOrderUpdate] = useState<string | null>() const isBottomVisible = useOnScreen(bottomOfMessageContainer) // Functions const loadMore = (): void => { if (relay.isLoading() || !relay.hasMore() || !initialMount.current) return setFetchingMore(true) const scrollCursor = scrollContainer.current ? scrollContainer.current?.scrollHeight - scrollContainer.current?.scrollTop : 0 relay.loadMore(PAGE_SIZE, error => { if (error) console.error(error) setFetchingMore(false) if (scrollContainer.current) { // Scrolling to former position scrollContainer.current?.scrollTo({ top: scrollContainer.current?.scrollHeight - scrollCursor, behavior: "smooth", }) } }) } const { match } = useRouter() const conversationID = match?.params?.conversationID // TODO: refactor useEffect(() => { initialScroll.current = false }, [conversationID]) useEffect(() => { initialScroll.current = !fetchingMore }, [fetchingMore]) useEffect(() => { if (!fetchingMore && !initialScroll.current) { scrollToBottom() } }) const scrollToBottom = () => { if (!!bottomOfMessageContainer?.current) { bottomOfMessageContainer.current?.scrollIntoView?.({ block: "end", inline: "nearest", behavior: initialMount.current ? "auto" : "smooth", }) if (isBottomVisible) initialMount.current = false setLastMessageID(conversation?.lastMessageID) setOrderKey() } } const refreshData = () => { props.refetch({ conversationID: conversation.internalID }, null, error => { if (error) console.error(error) scrollToBottom() }) } const setOrderKey = () => { setLastOrderUpdate(activeOrder?.updatedAt) } const [toastBottom, setToastBottom] = useState(0) // Behaviours // -Navigation useEffect(() => { setLastMessageID(conversation?.fromLastViewedMessageID) initialMount.current = true setOrderKey() }, [ conversation.internalID, conversation.fromLastViewedMessageID, setOrderKey, ]) // -Last message opened useEffect(() => { // Set on a timeout so the user sees the "new" flag setTimeout( () => { UpdateConversation(relay.environment, conversation) }, !!conversation.isLastMessageToUser ? 3000 : 0 ) }, [lastMessageID]) // -Workaround Reply render resizing race condition useEffect(() => { if (initialMount.current) scrollToBottom() const rect = scrollContainer.current?.getBoundingClientRect() setToastBottom(window.innerHeight - (rect?.bottom ?? 0) + 30) }, [scrollContainer?.current?.clientHeight]) // -On scroll down useEffect(() => { if (isBottomVisible) refreshData() }, [isBottomVisible]) return ( <Flex flexDirection="column" flexGrow={1}> <ConversationHeader partnerName={conversation.to.name} showDetails={showDetails} setShowDetails={setShowDetails} /> <NoScrollFlex flexDirection="column" width="100%"> <MessageContainer ref={scrollContainer as any}> <Box pb={[6, 6, 6, 0]} pr={1}> <Spacer mt={["75px", "75px", 2]} /> <Flex flexDirection="column" width="100%" px={1}> {isOfferable && <BuyerGuaranteeMessage />} {inquiryItemBox} <Waypoint onEnter={loadMore} /> {fetchingMore ? <Loading /> : null} <ConversationMessages messages={conversation.messagesConnection!} events={conversation.orderConnection} lastViewedMessageID={conversation?.fromLastViewedMessageID} setShowDetails={setShowDetails} /> <Box ref={bottomOfMessageContainer as any} /> </Flex> </Box> <UnreadMessagesToastQueryRenderer conversationID={conversation?.internalID!} lastOrderUpdate={lastOrderUpdate} bottom={toastBottom} hasScrolled={!isBottomVisible} onClick={scrollToBottom} refreshCallback={refreshData} /> </MessageContainer> <Reply onScroll={scrollToBottom} conversation={conversation} refetch={props.refetch} environment={relay.environment} openInquiryModal={() => setShowConfirmArtworkModal(true)} openOrderModal={() => setShowOrderModal(true)} /> </NoScrollFlex> {isOfferable && ( <ConfirmArtworkModalQueryRenderer artworkID={artwork?.internalID!} conversationID={conversation.internalID!} show={showConfirmArtworkModal} closeModal={() => setShowConfirmArtworkModal(false)} /> )} {isOfferable && ( <OrderModal path={url!} orderID={orderID} title={modalTitle!} show={showOrderModal} closeModal={() => { refreshData() setShowOrderModal(false) }} /> )} </Flex> ) } const MessageContainer = styled(Box)` flex-grow: 1; overflow-y: auto; ` const NoScrollFlex = styled(Flex)` overflow: hidden; flex-grow: 1; ` const SpinnerContainer = styled.div` width: 100%; height: 100px; position: relative; ` export const ConversationPaginationContainer = createPaginationContainer( Conversation, { conversation: graphql` fragment Conversation_conversation on Conversation @argumentDefinitions( count: { type: "Int", defaultValue: 30 } after: { type: "String" } ) { id internalID from { name email } to { name initials } initialMessage lastMessageID fromLastViewedMessageID isLastMessageToUser unread orderConnection( first: 10 states: [APPROVED, FULFILLED, SUBMITTED, REFUNDED, CANCELED] participantType: BUYER ) { edges { node { internalID updatedAt ... on CommerceOfferOrder { buyerAction } } } ...ConversationMessages_events } unread messagesConnection(first: $count, after: $after, sort: DESC) @connection(key: "Messages_messagesConnection", filters: []) { pageInfo { startCursor endCursor hasPreviousPage hasNextPage } edges { node { id } } totalCount ...ConversationMessages_messages } items { item { __typename ... on Artwork { id isOfferableFromInquiry internalID } ...Item_item } liveArtwork { ... on Artwork { isOfferableFromInquiry internalID __typename } } } ...ConversationCTA_conversation } `, }, { direction: "forward", getConnectionFromProps(props) { return props.conversation?.messagesConnection }, getFragmentVariables(prevVars, count) { return { ...prevVars, count, } }, getVariables(props, { cursor, count }) { return { count, cursor, after: cursor, conversationID: props.conversation.id, } }, query: graphql` query ConversationPaginationQuery( $count: Int $after: String $conversationID: ID! ) { node(id: $conversationID) { ...Conversation_conversation @arguments(count: $count, after: $after) } } `, } )
artsy/force
src/v2/Apps/Conversation/Components/Conversation.tsx
TypeScript
mit
11,098
package ch.bisi.koukan.job; import ch.bisi.koukan.provider.XMLExchangeRatesProvider; import ch.bisi.koukan.repository.DataAccessException; import ch.bisi.koukan.repository.ExchangeRatesRepository; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * Executes scheduled tasks for updating the in memory exchange rates * by querying the European Central Bank endpoints. */ @Component public class ECBDataLoaderScheduler { private static final Logger logger = LoggerFactory.getLogger(ECBDataLoaderScheduler.class); private final XMLExchangeRatesProvider xmlExchangeRatesProvider; private final ExchangeRatesRepository exchangeRatesRepository; private final URL dailyEndpoint; private final URL pastDaysEndpoint; /** * Instantiates a new {@link ECBDataLoaderScheduler}. * * @param xmlExchangeRatesProvider the provider of exchange rates * @param exchangeRatesRepository the repository * @param dailyEndpoint the ECB daily endpoint {@link URL} * @param pastDaysEndpoint the ECB endpoint {@link URL} for retrieving past days data */ @Autowired public ECBDataLoaderScheduler( @Qualifier("ECBProvider") final XMLExchangeRatesProvider xmlExchangeRatesProvider, final ExchangeRatesRepository exchangeRatesRepository, @Qualifier("dailyEndpoint") final URL dailyEndpoint, @Qualifier("pastDaysEndpoint") final URL pastDaysEndpoint) { this.xmlExchangeRatesProvider = xmlExchangeRatesProvider; this.exchangeRatesRepository = exchangeRatesRepository; this.dailyEndpoint = dailyEndpoint; this.pastDaysEndpoint = pastDaysEndpoint; } /** * Retrieves the whole exchange rates daily data. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${daily.rates.update.rate}") public void loadDailyData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = dailyEndpoint.openStream()) { logger.info("Updating ECB daily exchange rates data"); loadData(inputStream); } } /** * Retrieves the whole exchange rates data for past days. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${past.days.rates.update.rate}") public void loadPastDaysData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = pastDaysEndpoint.openStream()) { logger.info("Updating ECB exchange rates data for the past 90 days"); loadData(inputStream); } } /** * Loads exchange rates data from the given {@link InputStream}. * * @param inputStream the {@link InputStream} * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ private void loadData(final InputStream inputStream) throws XMLStreamException, DataAccessException { final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance() .createXMLStreamReader(inputStream); exchangeRatesRepository.save(xmlExchangeRatesProvider.retrieveAll(xmlStreamReader)); } }
bisignam/koukan
src/main/java/ch/bisi/koukan/job/ECBDataLoaderScheduler.java
Java
mit
3,982
<?php namespace JetMinds\Job\Updates; use Schema; use October\Rain\Database\Schema\Blueprint; use October\Rain\Database\Updates\Migration; class CreateResumesTable extends Migration { public function up() { Schema::create('jetminds_job_resumes', function(Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('first_name')->nullable(); $table->string('last_name')->nullable(); $table->string('email')->nullable(); $table->string('phone')->nullable(); $table->string('position')->nullable(); $table->longText('location')->nullable(); $table->string('resume_category')->nullable(); $table->string('resume_education')->nullable(); $table->longText('education_note')->nullable(); $table->string('resume_experience')->nullable(); $table->longText('experience_note')->nullable(); $table->string('resume_language')->nullable(); $table->string('resume_skill')->nullable(); $table->longText('resume_note')->nullable(); $table->boolean('is_invite')->default(1); $table->timestamps(); }); } public function down() { Schema::dropIfExists('jetminds_job_resumes'); } }
jetmindsgroup/job-plugin
updates/create_resumes_table.php
PHP
mit
1,311
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace SpartaHack { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public static ObservableValue<string> Title { get; set; } public static ObservableValue<bool> LoggedIn { get; set; } public static ObservableValue<string> Time { get; set; } public static MainPage root; private DateTime DoneTime; public MainPage(Frame frame) { this.InitializeComponent(); Title = new ObservableValue<string>(); LoggedIn = new ObservableValue<bool>(); Time = new ObservableValue<string>(); this.MySplitView.Content = frame; DataContext = this; DoneTime = DateTime.Parse("1/22/2017 17:00:00 GMT"); DispatcherTimer dt = new DispatcherTimer(); dt.Interval = TimeSpan.FromSeconds(1); dt.Tick += Dt_Tick; this.Loaded += (s,e) => { rdAnnouncements.IsChecked = true; dt.Start(); }; MySplitView.PaneClosed += (s, e) => { grdHideView.Visibility = Visibility.Collapsed; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); }; } private void Dt_Tick(object sender, object e) { TimeSpan dt = DoneTime.ToUniversalTime().Subtract(DateTime.Now.ToUniversalTime()); if (dt.TotalSeconds <= 0) Time.Value = "FINISHED"; else //txtCountDown.Text = dt.ToString(@"hh\:mm\:ss"); //Time.Value = $"{(int)dt.TotalHours}H {dt.Minutes}M {dt.Seconds}S"; Time.Value= string.Format("{0:##}h {1:##}m {2:##}s", ((int)dt.TotalHours), dt.Minutes.ToString(), dt.Seconds.ToString()); } private void OnAnnouncementsChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(AnnouncementsPage)); } catch { } } private void OnScheduleChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(SchedulePage)); } catch { } } private void OnTicketChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(TicketPage)); } catch { } } private void OnMapChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(MapPage)); } catch { } } private void OnSponsorChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(SponsorPage)); } catch { } } private void OnPrizeChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(PrizePage)); } catch { } } private void OnLoginChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(ProfilePage)); } catch { } } private void HambButton_Click(object sender, RoutedEventArgs e) { try { grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); } catch { } } private void grdHideView_Tapped(object sender, TappedRoutedEventArgs e) { try { grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); } catch { } } } }
SpartaHack/SpartaHack2016-Windows
2017/SpartaHack/SpartaHack/MainPage.xaml.cs
C#
mit
6,063
using System; using System.Diagnostics; namespace Oragon.Architecture.IO.Path { partial class PathHelpers { #region Private Classes private sealed class RelativeFilePath : RelativePathBase, IRelativeFilePath { #region Internal Constructors internal RelativeFilePath(string pathString) : base(pathString) { Debug.Assert(pathString != null); Debug.Assert(pathString.Length > 0); Debug.Assert(pathString.IsValidRelativeFilePath()); } #endregion Internal Constructors #region Public Properties public string FileExtension { get { return FileNameHelpers.GetFileNameExtension(m_PathString); } } // // File Name and File Name Extension // public string FileName { get { return FileNameHelpers.GetFileName(m_PathString); } } public string FileNameWithoutExtension { get { return FileNameHelpers.GetFileNameWithoutExtension(m_PathString); } } // // IsFilePath ; IsDirectoryPath // public override bool IsDirectoryPath { get { return false; } } public override bool IsFilePath { get { return true; } } #endregion Public Properties #region Public Methods public override IAbsolutePath GetAbsolutePathFrom(IAbsoluteDirectoryPath path) { return (this as IRelativeFilePath).GetAbsolutePathFrom(path); } public IRelativeDirectoryPath GetBrotherDirectoryWithName(string directoryName) { Debug.Assert(directoryName != null); // Enforced by contract Debug.Assert(directoryName.Length > 0); // Enforced by contract IDirectoryPath path = PathBrowsingHelpers.GetBrotherDirectoryWithName(this, directoryName); var pathTyped = path as IRelativeDirectoryPath; Debug.Assert(pathTyped != null); return pathTyped; } public IRelativeFilePath GetBrotherFileWithName(string fileName) { Debug.Assert(fileName != null); // Enforced by contract Debug.Assert(fileName.Length > 0); // Enforced by contract IFilePath path = PathBrowsingHelpers.GetBrotherFileWithName(this, fileName); var pathTyped = path as IRelativeFilePath; Debug.Assert(pathTyped != null); return pathTyped; } public bool HasExtension(string extension) { // All these 3 assertions have been checked by contract! Debug.Assert(extension != null); Debug.Assert(extension.Length >= 2); Debug.Assert(extension[0] == '.'); return FileNameHelpers.HasExtension(m_PathString, extension); } IDirectoryPath IFilePath.GetBrotherDirectoryWithName(string directoryName) { Debug.Assert(directoryName != null); // Enforced by contract Debug.Assert(directoryName.Length > 0); // Enforced by contract return this.GetBrotherDirectoryWithName(directoryName); } // Explicit Impl methods IFilePath IFilePath.GetBrotherFileWithName(string fileName) { Debug.Assert(fileName != null); // Enforced by contract Debug.Assert(fileName.Length > 0); // Enforced by contract return this.GetBrotherFileWithName(fileName); } IFilePath IFilePath.UpdateExtension(string newExtension) { // All these 3 assertions have been checked by contract! Debug.Assert(newExtension != null); Debug.Assert(newExtension.Length >= 2); Debug.Assert(newExtension[0] == '.'); return this.UpdateExtension(newExtension); } // // Absolute/Relative pathString conversion // IAbsoluteFilePath IRelativeFilePath.GetAbsolutePathFrom(IAbsoluteDirectoryPath path) { Debug.Assert(path != null); // Enforced by contracts! string pathAbsolute, failureReason; if (!AbsoluteRelativePathHelpers.TryGetAbsolutePathFrom(path, this, out pathAbsolute, out failureReason)) { throw new ArgumentException(failureReason); } Debug.Assert(pathAbsolute != null); Debug.Assert(pathAbsolute.Length > 0); return (pathAbsolute + MiscHelpers.DIR_SEPARATOR_CHAR + this.FileName).ToAbsoluteFilePath(); } // // Path Browsing facilities // public IRelativeFilePath UpdateExtension(string newExtension) { // All these 3 assertions have been checked by contract! Debug.Assert(newExtension != null); Debug.Assert(newExtension.Length >= 2); Debug.Assert(newExtension[0] == '.'); string pathString = PathBrowsingHelpers.UpdateExtension(this, newExtension); Debug.Assert(pathString.IsValidRelativeFilePath()); return new RelativeFilePath(pathString); } #endregion Public Methods } #endregion Private Classes } }
luizcarlosfaria/Oragon.Architecture
[source]/Oragon.Architecture/IO/Path/PathHelpers+RelativeFilePath.cs
C#
mit
4,445