text
stringlengths
2
1.04M
meta
dict
// // BWPhotoManager.m // Miss-Scarlett // // Created by mortal on 16/10/29. // Copyright © 2016年 mortal. All rights reserved. // #import "BWPhotoManager.h" #import <Photos/Photos.h> @implementation BWPhotoManager #pragma mark - 获取之前相册 + (PHAssetCollection *)fetchAssetColletion:(NSString *)albumTitle { /** PHAssetCollectionTypeAlbum = 1, PHAssetCollectionTypeSmartAlbum = 2, PHAssetCollectionTypeMoment = 3, */ PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil]; for (PHAssetCollection *assetCollection in fetchResult) { if ([assetCollection.localizedTitle isEqualToString:albumTitle]) { return assetCollection; } } return nil; } #pragma mark - 保存图片到自定义相册 + (void)savePhoto:(UIImage *)image albumTitle:(NSString *)albumTitle completionHandler:(void(^)(BOOL success, NSError *error))completionHandler { //自定义相册,必须导入 <Photos/Photos.h> 框架 // PHPhotoLibrary:相簿(所有相册集合) // PHAsset:图片 // PHAssetCollection:相册,所有相片集合 // PHAssetChangeRequest:创建,修改,删除图片 // PHAssetCollectionChangeRequest:创建,修改,删除相册 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ //判断之前是否有相同的相册,获取 PHAssetCollection *oldCollection = [self fetchAssetColletion:albumTitle]; PHAssetCollectionChangeRequest *assetCollection = nil; if (oldCollection) { assetCollection = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:oldCollection]; }else { //创建自定义相册 assetCollection = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumTitle]; } //保存图片到系统相册 PHAssetChangeRequest *assetChange = [PHAssetChangeRequest creationRequestForAssetFromImage:image]; //将保存的图片添加到自定义相册 PHObjectPlaceholder *placeholder = [assetChange placeholderForCreatedAsset]; [assetCollection addAssets:@[placeholder]];//添加的是 NSFastEnumeration 类型,相当于数组 } completionHandler:completionHandler]; } @end
{ "content_hash": "641b1925c315a15017ddb16e27304831", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 167, "avg_line_length": 34.92063492063492, "alnum_prop": 0.6981818181818182, "repo_name": "mortal-master/Miss-Scarlett", "id": "fc0368eaccf955b4c7819e38f1efa451f576055e", "size": "2457", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Miss-Scarlett/Miss-Scarlett/Classes/Utils(业务类)/Photo/BWPhotoManager.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "135081" }, { "name": "Ruby", "bytes": "225" } ], "symlink_target": "" }
package it.polito.appeal.traci.protocol; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.zip.Checksum; import de.uniluebeck.itm.tcpip.Storage; /** * Represents a TraCI messages used to send {@link Command}s from the client to * server (i.e. requests). After construction, the commands are appended one * after one with {@link #append(Command)}. The whole message, along with its * length header, can be then retrieved in a serialized form via the * {@link #writeTo(DataOutputStream)} method. * * @author Enrico Gueli &lt;enrico.gueli@polito.it&gt; * @see <a * href="https://sourceforge.net/apps/mediawiki/sumo/index.php?title=TraCI/Protocol#Messages">https://sourceforge.net/apps/mediawiki/sumo/index.php?title=TraCI/Protocol#Messages</a> */ public class RequestMessage { private final List<Command> commands = new ArrayList<Command>(); /** * Adds a command to the tail of this message. * @param c * @throws NullPointerException if the command is <code>null</code>. */ public void append(Command c) { if (c == null) throw new NullPointerException("the command can't be null"); commands.add(c); } /** * Writes the commands to the specified {@link DataOutputStream} object, in * the same order as the calls of {@link #append(Command)}. * @param dos * @throws IOException */ public void writeTo(DataOutputStream dos) throws IOException { int totalLen = Integer.SIZE / 8; // the length header for (Command cmd : commands) { totalLen += cmd.rawSize(); } Checksum checksum = null; dos.writeInt(totalLen); for (Command cmd : commands) { Storage s = new Storage(); cmd.writeRawTo(s); writeStorage(s, dos, checksum); } } private void writeStorage(Storage storage, OutputStream os, Checksum checksum) throws IOException { byte[] buf = new byte[storage.getStorageList().size()]; int n = 0; for (Byte b : storage.getStorageList()) { if (checksum != null) checksum.update(b); buf[n] = b; n++; } os.write(buf); } public List<Command> commands() { return Collections.unmodifiableList(commands); } }
{ "content_hash": "ba6d55fc21974f6af1abb4e58d22dd41", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 186, "avg_line_length": 27.50588235294118, "alnum_prop": 0.6757912745936698, "repo_name": "baumfalk/TrafficMAS", "id": "2e0fe0752806e8d16ee9bef95feff30848b6a5f4", "size": "3096", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "TraaS/it/polito/appeal/traci/protocol/RequestMessage.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "661842" } ], "symlink_target": "" }
import { clamp } from '../../utils'; import Scrollbar from 'smooth-scrollbar'; import { setStyle } from '../../utils/set-style'; const GLOW_MAX_OPACITY = 0.75; const GLOW_MAX_OFFSET = 0.25; export class Glow { private _canvas = document.createElement('canvas'); private _ctx = this._canvas.getContext('2d') as CanvasRenderingContext2D; private _touchX: number; private _touchY: number; constructor( private _scrollbar: Scrollbar, ) { setStyle(this._canvas, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', display: 'none', }); } mount() { this._scrollbar.containerEl.appendChild(this._canvas); } unmount() { if (this._canvas.parentNode) { this._canvas.parentNode.removeChild(this._canvas); } } adjust() { const { size, } = this._scrollbar; const DPR = window.devicePixelRatio || 1; const nextWidth = size.container.width * DPR; const nextHeight = size.container.height * DPR; if (nextWidth === this._canvas.width && nextHeight === this._canvas.height) { return; } this._canvas.width = nextWidth; this._canvas.height = nextHeight; this._ctx.scale(DPR, DPR); } recordTouch(event: TouchEvent) { const touch = event.touches[event.touches.length - 1]; this._touchX = touch.clientX; this._touchY = touch.clientY; } render({ x = 0, y = 0 }, color: string) { if (!x && !y) { setStyle(this._canvas, { display: 'none', }); return; } setStyle(this._canvas, { display: 'block', }); const { size, } = this._scrollbar; this._ctx.clearRect(0, 0, size.container.width, size.container.height); this._ctx.fillStyle = color; this._renderX(x); this._renderY(y); } private _getMaxOverscroll(): number { const options = this._scrollbar.options.plugins.overscroll; return options && options.maxOverscroll ? options.maxOverscroll : 150; } private _renderX(strength: number) { const { size, } = this._scrollbar; const maxOverscroll = this._getMaxOverscroll(); const { width, height } = size.container; const ctx = this._ctx; ctx.save(); if (strength > 0) { // glow on right side // horizontally flip ctx.transform(-1, 0, 0, 1, width, 0); } const opacity = clamp(Math.abs(strength) / maxOverscroll, 0, GLOW_MAX_OPACITY); const startOffset = clamp(opacity, 0, GLOW_MAX_OFFSET) * width; // controll point const x = Math.abs(strength); const y = this._touchY || (height / 2); ctx.globalAlpha = opacity; ctx.beginPath(); ctx.moveTo(0, -startOffset); ctx.quadraticCurveTo(x, y, 0, height + startOffset); ctx.fill(); ctx.closePath(); ctx.restore(); } private _renderY(strength: number) { const { size, } = this._scrollbar; const maxOverscroll = this._getMaxOverscroll(); const { width, height } = size.container; const ctx = this._ctx; ctx.save(); if (strength > 0) { // glow on bottom side // vertically flip ctx.transform(1, 0, 0, -1, 0, height); } const opacity = clamp(Math.abs(strength) / maxOverscroll, 0, GLOW_MAX_OPACITY); const startOffset = clamp(opacity, 0, GLOW_MAX_OFFSET) * width; // controll point const x = this._touchX || (width / 2); const y = Math.abs(strength); ctx.globalAlpha = opacity; ctx.beginPath(); ctx.moveTo(-startOffset, 0); ctx.quadraticCurveTo(x, y, width + startOffset, 0); ctx.fill(); ctx.closePath(); ctx.restore(); } }
{ "content_hash": "00bada788f91b4e8c9c55c2f2620cf5d", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 83, "avg_line_length": 22.68944099378882, "alnum_prop": 0.6011497399397755, "repo_name": "idiotWu/smooth-scrollbar", "id": "2ed69b1053fb622b77848704de031f4276df042b", "size": "3653", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/plugins/overscroll/glow.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10297" }, { "name": "TypeScript", "bytes": "67480" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncpy_65b.c Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE806.label.xml Template File: sources-sink-65b.tmpl.c */ /* * @description * CWE: 121 Stack Based Buffer Overflow * BadSource: Initialize data as a large string * GoodSource: Initialize data as a small string * Sinks: ncpy * BadSink : Copy data to string using strncpy * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncpy_65b_badSink(char * data) { { char dest[50] = ""; /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ strncpy(dest, data, strlen(data)); dest[50-1] = '\0'; /* Ensure the destination buffer is null terminated */ printLine(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncpy_65b_goodG2BSink(char * data) { { char dest[50] = ""; /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ strncpy(dest, data, strlen(data)); dest[50-1] = '\0'; /* Ensure the destination buffer is null terminated */ printLine(data); } } #endif /* OMITGOOD */
{ "content_hash": "082d9c2a858e12f2ea918f6f26614b29", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 154, "avg_line_length": 31.74, "alnum_prop": 0.6622558286074354, "repo_name": "maurer/tiamat", "id": "33bef88ebeba5028c21e5256f1cd21fb9a7b98ea", "size": "1587", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE121_Stack_Based_Buffer_Overflow/s06/CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncpy_65b.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
require "backbone_handlebars/version" require "backbone_handlebars/engine"
{ "content_hash": "ada1d53f34191ad061f55ecba36db874", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 37, "avg_line_length": 37.5, "alnum_prop": 0.84, "repo_name": "BlakeWilliams/backbone_handlebars", "id": "d171d72a27fbdbf43d1df7defdc7158417c3927b", "size": "75", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/backbone_handlebars.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "167" }, { "name": "Ruby", "bytes": "6629" } ], "symlink_target": "" }
stop_all_tasks() { cluster_name="${1}" task_arns="$(aws_cli ecs list-tasks --cluster "${cluster_name}" | jq_cli -r '.taskArns[]' )" if [[ "${task_arns}" ]]; then for arn in ${task_arns}; do aws_cli ecs stop-task --cluster "${cluster_name}" --task "$arn" done fi } case "${command}" in aws) ## [options] <command> <subcommand> [<subcommand> ...] [parameters] %% AWS CLI aws_cli "${args}" ;; aws:ecs:stop-all-tasks) ## <cluster-name> %% Stop all running tasks in an ECS cluster stop_all_tasks "${args}" ;; esac
{ "content_hash": "3b80d099c726f42bf0578cd7f9c0f53d", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 93, "avg_line_length": 32.9375, "alnum_prop": 0.6072106261859582, "repo_name": "wheniwork/harpoon", "id": "1dc4e233b34ddddcc05c32232e8724a87246a46a", "size": "548", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tasks/aws/handler.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "902" }, { "name": "Shell", "bytes": "144633" } ], "symlink_target": "" }
Public Class frmStatCalc Private Sub WarCalc_Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WarCalc_Btn.Click frmWarriorCalc.Show() End Sub Private Sub MageCalc_Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MageCalc_Btn.Click frmMageCalc.Show() End Sub Private Sub SeyanCalc_Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SeyanCalc_Btn.Click frmSeyanCalc.Show() End Sub Private Sub EquipCalc_Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EquipCalc_Btn.Click frmEquipmentCalc.Show() End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click frmNPC_Calc.Show() End Sub End Class
{ "content_hash": "ba0d3343f3edaebd35cf382b031b5e18", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 123, "avg_line_length": 38.5, "alnum_prop": 0.7343565525383707, "repo_name": "AstoniaDev/VB_StatCalc", "id": "2df5f89c21f6e5da16f2356d4a586b055871ea38", "size": "849", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vb_calc/StatCalc.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Visual Basic", "bytes": "814214" } ], "symlink_target": "" }
'use strict'; /** * CLI engine * @module lib/CLI */ /* eslint-disable no-console */ const ConsoleReporter = require('./reporters/ConsoleReporter'); const Linter = require('./Linter'); const Options = require('./Options'); const resolvePatterns = require('./util/resolvePatterns'); function lint(files, options) { return Linter.lintFiles(files, options).then(results => { const numErrors = new ConsoleReporter(options).report(results); return numErrors ? 1 : 0; }); } /** * Parse the command line arguments and run the linter * * @memberof module:lib/CLI * @param {string[]} argv - Command line arguments * @return {number|Promise<number>} * A Promise that resolves with a numeric exit code */ function execute(argv) { const opts = Options.parse(argv); if (opts.version) { /* eslint-disable global-require */ console.log(`v${ require('../package.json').version }`); return Promise.resolve(0); } if (opts.help || !opts._.length) { console.log(Options.generateHelp()); return Promise.resolve(0); } return lint(resolvePatterns(opts), opts); } module.exports = { execute };
{ "content_hash": "a8206af036619df47c014ddea2213f36", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 67, "avg_line_length": 24.106382978723403, "alnum_prop": 0.6725507502206531, "repo_name": "Banno/polymer-lint", "id": "2f9f2cf19e1adca5cc4f3819a833d2b1e652f760", "size": "1133", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/CLI.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "10690" }, { "name": "JavaScript", "bytes": "199773" } ], "symlink_target": "" }
/* $Id: siptypes.hpp 4968 2014-12-18 04:40:35Z riza $ */ /* * Copyright (C) 2032 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJSUA2_SIPTYPES_HPP__ #define __PJSUA2_SIPTYPES_HPP__ /** * @file pjsua2/types.hpp * @brief PJSUA2 Base Types */ #include <pjsua2/types.hpp> #include <pjsua2/persistent.hpp> #include <string> #include <vector> /** PJSUA2 API is inside pj namespace */ namespace pj { /** * @defgroup PJSUA2_SIP_Types SIP Types * @ingroup PJSUA2_DS * @{ */ /** * Credential information. Credential contains information to authenticate * against a service. */ struct AuthCredInfo : public PersistentObject { /** * The authentication scheme (e.g. "digest"). */ string scheme; /** * Realm on which this credential is to be used. Use "*" to make * a credential that can be used to authenticate against any challenges. */ string realm; /** * Authentication user name. */ string username; /** * Type of data that is contained in the "data" field. Use 0 if the data * contains plain text password. */ int dataType; /** * The data, which can be a plain text password or a hashed digest. */ string data; /* * Digest AKA credential information. Note that when AKA credential * is being used, the \a data field of this pjsip_cred_info is * not used, but it still must be initialized to an empty string. * Please see PJSIP_AUTH_AKA_API for more information. */ /** Permanent subscriber key. */ string akaK; /** Operator variant key. */ string akaOp; /** Authentication Management Field */ string akaAmf; public: /** Default constructor */ AuthCredInfo(); /** Construct a credential with the specified parameters */ AuthCredInfo(const string &scheme, const string &realm, const string &user_name, const int data_type, const string data); /** * Read this object from a container node. * * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) throw(Error); /** * Write this object to a container node. * * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const throw(Error); }; ////////////////////////////////////////////////////////////////////////////// /** * TLS transport settings, to be specified in TransportConfig. */ struct TlsConfig : public PersistentObject { /** * Certificate of Authority (CA) list file. */ string CaListFile; /** * Public endpoint certificate file, which will be used as client- * side certificate for outgoing TLS connection, and server-side * certificate for incoming TLS connection. */ string certFile; /** * Optional private key of the endpoint certificate to be used. */ string privKeyFile; /** * Password to open private key. */ string password; /** * TLS protocol method from #pjsip_ssl_method. In the future, this field * might be deprecated in favor of <b>proto</b> field. For now, this field * is only applicable only when <b>proto</b> field is set to zero. * * Default is PJSIP_SSL_UNSPECIFIED_METHOD (0), which in turn will * use PJSIP_SSL_DEFAULT_METHOD, which default value is PJSIP_TLSV1_METHOD. */ pjsip_ssl_method method; /** * TLS protocol type from #pj_ssl_sock_proto. Use this field to enable * specific protocol type. Use bitwise OR operation to combine the protocol * type. * * Default is PJSIP_SSL_DEFAULT_PROTO. */ unsigned proto; /** * Ciphers and order preference. The Endpoint::utilSslGetAvailableCiphers() * can be used to check the available ciphers supported by backend. * If the array is empty, then default cipher list of the backend * will be used. */ IntVector ciphers; /** * Specifies TLS transport behavior on the server TLS certificate * verification result: * - If \a verifyServer is disabled, TLS transport will just notify * the application via pjsip_tp_state_callback with state * PJSIP_TP_STATE_CONNECTED regardless TLS verification result. * - If \a verifyServer is enabled, TLS transport will be shutdown * and application will be notified with state * PJSIP_TP_STATE_DISCONNECTED whenever there is any TLS verification * error, otherwise PJSIP_TP_STATE_CONNECTED will be notified. * * In any cases, application can inspect pjsip_tls_state_info in the * callback to see the verification detail. * * Default value is false. */ bool verifyServer; /** * Specifies TLS transport behavior on the client TLS certificate * verification result: * - If \a verifyClient is disabled, TLS transport will just notify * the application via pjsip_tp_state_callback with state * PJSIP_TP_STATE_CONNECTED regardless TLS verification result. * - If \a verifyClient is enabled, TLS transport will be shutdown * and application will be notified with state * PJSIP_TP_STATE_DISCONNECTED whenever there is any TLS verification * error, otherwise PJSIP_TP_STATE_CONNECTED will be notified. * * In any cases, application can inspect pjsip_tls_state_info in the * callback to see the verification detail. * * Default value is PJ_FALSE. */ bool verifyClient; /** * When acting as server (incoming TLS connections), reject incoming * connection if client doesn't supply a TLS certificate. * * This setting corresponds to SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag. * Default value is PJ_FALSE. */ bool requireClientCert; /** * TLS negotiation timeout to be applied for both outgoing and incoming * connection, in milliseconds. If zero, the SSL negotiation doesn't * have a timeout. * * Default: zero */ unsigned msecTimeout; /** * QoS traffic type to be set on this transport. When application wants * to apply QoS tagging to the transport, it's preferable to set this * field rather than \a qosParam fields since this is more portable. * * Default value is PJ_QOS_TYPE_BEST_EFFORT. */ pj_qos_type qosType; /** * Set the low level QoS parameters to the transport. This is a lower * level operation than setting the \a qosType field and may not be * supported on all platforms. * * By default all settings in this structure are disabled. */ pj_qos_params qosParams; /** * Specify if the transport should ignore any errors when setting the QoS * traffic type/parameters. * * Default: PJ_TRUE */ bool qosIgnoreError; public: /** Default constructor initialises with default values */ TlsConfig(); /** Convert to pjsip */ pjsip_tls_setting toPj() const; /** Convert from pjsip */ void fromPj(const pjsip_tls_setting &prm); /** * Read this object from a container node. * * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) throw(Error); /** * Write this object to a container node. * * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const throw(Error); }; /** * Parameters to create a transport instance. */ struct TransportConfig : public PersistentObject { /** * UDP port number to bind locally. This setting MUST be specified * even when default port is desired. If the value is zero, the * transport will be bound to any available port, and application * can query the port by querying the transport info. */ unsigned port; /** * Specify the port range for socket binding, relative to the start * port number specified in \a port. Note that this setting is only * applicable when the start port number is non zero. * * Default value is zero. */ unsigned portRange; /** * Optional address to advertise as the address of this transport. * Application can specify any address or hostname for this field, * for example it can point to one of the interface address in the * system, or it can point to the public address of a NAT router * where port mappings have been configured for the application. * * Note: this option can be used for both UDP and TCP as well! */ string publicAddress; /** * Optional address where the socket should be bound to. This option * SHOULD only be used to selectively bind the socket to particular * interface (instead of 0.0.0.0), and SHOULD NOT be used to set the * published address of a transport (the public_addr field should be * used for that purpose). * * Note that unlike public_addr field, the address (or hostname) here * MUST correspond to the actual interface address in the host, since * this address will be specified as bind() argument. */ string boundAddress; /** * This specifies TLS settings for TLS transport. It is only be used * when this transport config is being used to create a SIP TLS * transport. */ TlsConfig tlsConfig; /** * QoS traffic type to be set on this transport. When application wants * to apply QoS tagging to the transport, it's preferable to set this * field rather than \a qosParam fields since this is more portable. * * Default is QoS not set. */ pj_qos_type qosType; /** * Set the low level QoS parameters to the transport. This is a lower * level operation than setting the \a qosType field and may not be * supported on all platforms. * * Default is QoS not set. */ pj_qos_params qosParams; public: /** Default constructor initialises with default values */ TransportConfig(); /** Convert from pjsip */ void fromPj(const pjsua_transport_config &prm); /** Convert to pjsip */ pjsua_transport_config toPj() const; /** * Read this object from a container node. * * @param node Container to read values from. */ virtual void readObject(const ContainerNode &node) throw(Error); /** * Write this object to a container node. * * @param node Container to write values to. */ virtual void writeObject(ContainerNode &node) const throw(Error); }; /** * This structure describes transport information returned by * Endpoint::transportGetInfo() function. */ struct TransportInfo { /** PJSUA transport identification. */ TransportId id; /** Transport type. */ pjsip_transport_type_e type; /** Transport type name. */ string typeName; /** Transport string info/description. */ string info; /** Transport flags (see pjsip_transport_flags_e). */ unsigned flags; /** Local/bound address. */ SocketAddress localAddress; /** Published address (or transport address name). */ SocketAddress localName; /** Current number of objects currently referencing this transport. */ unsigned usageCount; public: /** Construct from pjsua_transport_info */ void fromPj(const pjsua_transport_info &info); }; ////////////////////////////////////////////////////////////////////////////// /** * This structure describes an incoming SIP message. It corresponds to the * pjsip_rx_data structure in PJSIP library. */ struct SipRxData { /** * A short info string describing the request, which normally contains * the request method and its CSeq. */ string info; /** * The whole message data as a string, containing both the header section * and message body section. */ string wholeMsg; /** * Source address of the message. */ SocketAddress srcAddress; /** * Pointer to original pjsip_rx_data. Only valid when the struct * is constructed from PJSIP's pjsip_rx_data. */ void *pjRxData; public: /** * Default constructor. */ SipRxData(); /** * Construct from PJSIP's pjsip_rx_data */ void fromPj(pjsip_rx_data &rdata); }; /** * This structure describes an outgoing SIP message. It corresponds to the * pjsip_tx_data structure in PJSIP library. */ struct SipTxData { /** * A short info string describing the request, which normally contains * the request method and its CSeq. */ string info; /** * The whole message data as a string, containing both the header section * and message body section. */ string wholeMsg; /** * Destination address of the message. */ SocketAddress dstAddress; /** * Pointer to original pjsip_tx_data. Only valid when the struct * is constructed from PJSIP's pjsip_tx_data. */ void *pjTxData; public: /** * Default constructor. */ SipTxData(); /** * Construct from PJSIP's pjsip_tx_data */ void fromPj(pjsip_tx_data &tdata); }; /** * This structure describes SIP transaction object. It corresponds to the * pjsip_transaction structure in PJSIP library. */ struct SipTransaction { /* Transaction identification. */ pjsip_role_e role; /**< Role (UAS or UAC) */ string method; /**< The method. */ /* State and status. */ int statusCode; /**< Last status code seen. */ string statusText; /**< Last reason phrase. */ pjsip_tsx_state_e state; /**< State. */ /* Messages and timer. */ SipTxData lastTx; /**< Msg kept for retrans. */ /* Original pjsip_transaction. */ void *pjTransaction; /**< pjsip_transaction. */ public: /** * Default constructor. */ SipTransaction(); /** * Construct from PJSIP's pjsip_transaction */ void fromPj(pjsip_transaction &tsx); }; /** * This structure describes timer event. */ struct TimerEvent { TimerEntry entry; /**< The timer entry. */ }; /** * This structure describes transaction state event source. */ struct TsxStateEventSrc { SipRxData rdata; /**< The incoming message. */ SipTxData tdata; /**< The outgoing message. */ TimerEntry timer; /**< The timer. */ pj_status_t status; /**< Transport error status. */ GenericData data; /**< Generic data. */ }; /** * This structure describes transaction state changed event. */ struct TsxStateEvent { TsxStateEventSrc src; /**< Event source. */ SipTransaction tsx; /**< The transaction. */ pjsip_tsx_state_e prevState; /**< Previous state. */ pjsip_event_id_e type; /**< Type of event source: * - PJSIP_EVENT_TX_MSG * - PJSIP_EVENT_RX_MSG, * - PJSIP_EVENT_TRANSPORT_ERROR * - PJSIP_EVENT_TIMER * - PJSIP_EVENT_USER */ }; /** * This structure describes message transmission event. */ struct TxMsgEvent { SipTxData tdata; /**< The transmit data buffer. */ }; /** * This structure describes transmission error event. */ struct TxErrorEvent { SipTxData tdata; /**< The transmit data. */ SipTransaction tsx; /**< The transaction. */ }; /** * This structure describes message arrival event. */ struct RxMsgEvent { SipRxData rdata; /**< The receive data buffer. */ }; /** * This structure describes user event. */ struct UserEvent { GenericData user1; /**< User data 1. */ GenericData user2; /**< User data 2. */ GenericData user3; /**< User data 3. */ GenericData user4; /**< User data 4. */ }; /** * The event body. */ struct SipEventBody { /** * Timer event. */ TimerEvent timer; /** * Transaction state has changed event. */ TsxStateEvent tsxState; /** * Message transmission event. */ TxMsgEvent txMsg; /** * Transmission error event. */ TxErrorEvent txError; /** * Message arrival event. */ RxMsgEvent rxMsg; /** * User event. */ UserEvent user; }; /** * This structure describe event descriptor to fully identify a SIP event. It * corresponds to the pjsip_event structure in PJSIP library. */ struct SipEvent { /** * The event type, can be any value of \b pjsip_event_id_e. */ pjsip_event_id_e type; /** * The event body, which fields depends on the event type. */ SipEventBody body; /** * Pointer to its original pjsip_event. Only valid when the struct is * constructed from PJSIP's pjsip_event. */ void *pjEvent; public: /** * Default constructor. */ SipEvent(); /** * Construct from PJSIP's pjsip_event */ void fromPj(const pjsip_event &ev); }; ////////////////////////////////////////////////////////////////////////////// /** * SIP media type containing type and subtype. For example, for * "application/sdp", the type is "application" and the subtype is "sdp". */ struct SipMediaType { /** Media type. */ string type; /** Media subtype. */ string subType; public: /** * Construct from PJSIP's pjsip_media_type */ void fromPj(const pjsip_media_type &prm); /** * Convert to PJSIP's pjsip_media_type. */ pjsip_media_type toPj() const; }; /** * Simple SIP header. */ struct SipHeader { /** * Header name. */ string hName; /** * Header value. */ string hValue; public: /** * Initiaize from PJSIP header. */ void fromPj(const pjsip_hdr *) throw(Error); /** * Convert to PJSIP header. */ pjsip_generic_string_hdr &toPj() const; private: /** Interal buffer for conversion to PJSIP header */ mutable pjsip_generic_string_hdr pjHdr; }; /** Array of strings */ typedef std::vector<SipHeader> SipHeaderVector; /** * This describes each multipart part. */ struct SipMultipartPart { /** * Optional headers to be put in this multipart part. */ SipHeaderVector headers; /** * The MIME type of the body part of this multipart part. */ SipMediaType contentType; /** * The body part of tthis multipart part. */ string body; public: /** * Initiaize from PJSIP's pjsip_multipart_part. */ void fromPj(const pjsip_multipart_part &prm) throw(Error); /** * Convert to PJSIP's pjsip_multipart_part. */ pjsip_multipart_part& toPj() const; private: /** Interal buffer for conversion to PJSIP pjsip_multipart_part */ mutable pjsip_multipart_part pjMpp; mutable pjsip_msg_body pjMsgBody; }; /** Array of multipart parts */ typedef std::vector<SipMultipartPart> SipMultipartPartVector; /** * Additional options when sending outgoing SIP message. This corresponds to * pjsua_msg_data structure in PJSIP library. */ struct SipTxOption { /** * Optional remote target URI (i.e. Target header). If empty (""), the * target will be set to the remote URI (To header). At the moment this * field is only used when sending initial INVITE and MESSAGE requests. */ string targetUri; /** * Additional message headers to be included in the outgoing message. */ SipHeaderVector headers; /** * MIME type of the message body, if application specifies the messageBody * in this structure. */ string contentType; /** * Optional message body to be added to the message, only when the * message doesn't have a body. */ string msgBody; /** * Content type of the multipart body. If application wants to send * multipart message bodies, it puts the parts in multipartParts and set * the content type in multipartContentType. If the message already * contains a body, the body will be added to the multipart bodies. */ SipMediaType multipartContentType; /** * Array of multipart parts. If application wants to send multipart * message bodies, it puts the parts in \a parts and set the content * type in \a multipart_ctype. If the message already contains a body, * the body will be added to the multipart bodies. */ SipMultipartPartVector multipartParts; public: /** * Check if the options are empty. If the options are set with empty * values, there will be no additional information sent with outgoing * SIP message. * * @return True if the options are empty. */ bool isEmpty() const; /** * Initiaize from PJSUA's pjsua_msg_data. */ void fromPj(const pjsua_msg_data &prm) throw(Error); /** * Convert to PJSUA's pjsua_msg_data. */ void toPj(pjsua_msg_data &msg_data) const; }; ////////////////////////////////////////////////////////////////////////////// /** * This structure contains parameters for sending instance message methods, * e.g: Buddy::sendInstantMessage(), Call:sendInstantMessage(). */ struct SendInstantMessageParam { /** * MIME type. Default is "text/plain". */ string contentType; /** * The message content. */ string content; /** * List of headers etc to be included in outgoing request. */ SipTxOption txOption; /** * User data, which will be given back when the IM callback is called. */ Token userData; public: /** * Default constructor initializes with zero/empty values. */ SendInstantMessageParam(); }; /** * This structure contains parameters for sending typing indication methods, * e.g: Buddy::sendTypingIndication(), Call:sendTypingIndication(). */ struct SendTypingIndicationParam { /** * True to indicate to remote that local person is currently typing an IM. */ bool isTyping; /** * List of headers etc to be included in outgoing request. */ SipTxOption txOption; public: /** * Default constructor initializes with zero/empty values. */ SendTypingIndicationParam(); }; /* Utilities */ #ifndef SWIG //! @cond Doxygen_Suppress void readIntVector( ContainerNode &node, const string &array_name, IntVector &v) throw(Error); void writeIntVector(ContainerNode &node, const string &array_name, const IntVector &v) throw(Error); void readQosParams( ContainerNode &node, pj_qos_params &qos) throw(Error); void writeQosParams( ContainerNode &node, const pj_qos_params &qos) throw(Error); void readSipHeaders( const ContainerNode &node, const string &array_name, SipHeaderVector &headers) throw(Error); void writeSipHeaders(ContainerNode &node, const string &array_name, const SipHeaderVector &headers) throw(Error); //! @endcond #endif // SWIG /** * @} PJSUA2 */ } // namespace pj #endif /* __PJSUA2_SIPTYPES_HPP__ */
{ "content_hash": "31c3012b5efa4a893479d19361c8be31", "timestamp": "", "source": "github", "line_count": 930, "max_line_length": 80, "avg_line_length": 27.940860215053764, "alnum_prop": 0.5801808735809121, "repo_name": "Guicai-Li/PJSIP-iOS", "id": "09c159dc32a251bc91819e627f2812738f9770a5", "size": "25985", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "2.4.5各架构静态包/pjsip/include/pjsua2/siptypes.hpp", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5653226" }, { "name": "C++", "bytes": "783846" }, { "name": "Objective-C", "bytes": "32920" }, { "name": "Ruby", "bytes": "3236" } ], "symlink_target": "" }
package net.logvv.raven.push.umeng; import java.util.Arrays; import java.util.HashSet; import org.json.JSONObject; public abstract class IOSNotification extends UmengNotification { // Keys can be set in the aps level protected static final HashSet<String> APS_KEYS = new HashSet<String>(Arrays.asList(new String[]{ "alert", "badge", "sound", "content-available" })); @Override public boolean setPredefinedKeyValue(String key, Object value) throws Exception { if (ROOT_KEYS.contains(key)) { // This key should be in the root level rootJson.put(key, value); } else if (APS_KEYS.contains(key)) { // This key should be in the aps level JSONObject apsJson = null; JSONObject payloadJson = null; if (rootJson.has("payload")) { payloadJson = rootJson.getJSONObject("payload"); } else { payloadJson = new JSONObject(); rootJson.put("payload", payloadJson); } if (payloadJson.has("aps")) { apsJson = payloadJson.getJSONObject("aps"); } else { apsJson = new JSONObject(); payloadJson.put("aps", apsJson); } apsJson.put(key, value); } else if (POLICY_KEYS.contains(key)) { // This key should be in the body level JSONObject policyJson = null; if (rootJson.has("policy")) { policyJson = rootJson.getJSONObject("policy"); } else { policyJson = new JSONObject(); rootJson.put("policy", policyJson); } policyJson.put(key, value); } else { if (key == "payload" || key == "aps" || key == "policy") { throw new Exception("You don't need to set value for " + key + " , just set values for the sub keys in it."); } else { throw new Exception("Unknownd key: " + key); } } return true; } // Set customized key/value for IOS notification public boolean setCustomizedField(String key, String value) throws Exception { //rootJson.put(key, value); JSONObject payloadJson = null; if (rootJson.has("payload")) { payloadJson = rootJson.getJSONObject("payload"); } else { payloadJson = new JSONObject(); rootJson.put("payload", payloadJson); } payloadJson.put(key, value); return true; } }
{ "content_hash": "4b61d8d8452e509b9324c96772eeb1ff", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 113, "avg_line_length": 29.91549295774648, "alnum_prop": 0.6690207156308852, "repo_name": "marlonwang/raven", "id": "5d4af9a18ae6fe316d794eecfe168ded7365f38e", "size": "2124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/logvv/raven/push/umeng/IOSNotification.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "605964" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.4 Version: 4.0.1 Author: KeenThemes Website: http://www.keenthemes.com/ Contact: support@keenthemes.com Follow: www.twitter.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. --> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8"/> <title>Metronic | Page Layouts - Right Sidebar Page</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta content="" name="description"/> <meta content="" name="author"/> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"/> <link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/> <link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"/> <link href="../../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/> <link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css"/> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN THEME STYLES --> <link href="../../assets/global/css/components.css" id="style_components" rel="stylesheet" type="text/css"/> <link href="../../assets/global/css/plugins.css" rel="stylesheet" type="text/css"/> <link href="../../assets/admin/layout/css/layout.css" rel="stylesheet" type="text/css"/> <link id="style_color" href="../../assets/admin/layout/css/themes/darkblue.css" rel="stylesheet" type="text/css"/> <link href="../../assets/admin/layout/css/custom.css" rel="stylesheet" type="text/css"/> <!-- END THEME STYLES --> <link rel="shortcut icon" href="favicon.ico"/> </head> <!-- END HEAD --> <!-- BEGIN BODY --> <!-- DOC: Apply "page-header-fixed-mobile" and "page-footer-fixed-mobile" class to body element to force fixed header or footer in mobile devices --> <!-- DOC: Apply "page-sidebar-closed" class to the body and "page-sidebar-menu-closed" class to the sidebar menu element to hide the sidebar by default --> <!-- DOC: Apply "page-sidebar-hide" class to the body to make the sidebar completely hidden on toggle --> <!-- DOC: Apply "page-sidebar-closed-hide-logo" class to the body element to make the logo hidden on sidebar toggle --> <!-- DOC: Apply "page-sidebar-hide" class to body element to completely hide the sidebar on sidebar toggle --> <!-- DOC: Apply "page-sidebar-fixed" class to have fixed sidebar --> <!-- DOC: Apply "page-footer-fixed" class to the body element to have fixed footer --> <!-- DOC: Apply "page-sidebar-reversed" class to put the sidebar on the right side --> <!-- DOC: Apply "page-full-width" class to the body element to have full width page without the sidebar menu --> <body class="page-header-fixed page-quick-sidebar-over-content page-sidebar-reversed"> <!-- BEGIN HEADER --> <div class="page-header navbar navbar-fixed-top"> <!-- BEGIN HEADER INNER --> <div class="page-header-inner"> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"> <img src="../../assets/admin/layout/img/logo.png" alt="logo" class="logo-default"/> </a> <div class="menu-toggler sidebar-toggler hide"> <!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header --> </div> </div> <!-- END LOGO --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse"> </a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <!-- BEGIN NOTIFICATION DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-notification" id="header_notification_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-default"> 7 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3><span class="bold">12 pending</span> notifications</h3> <a href="extra_profile.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <!-- BEGIN INBOX DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-inbox" id="header_inbox_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-envelope-open"></i> <span class="badge badge-default"> 4 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <span class="bold">7 New</span> Messages</h3> <a href="page_inbox.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">16 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Bob Nilson </span> <span class="time">2 hrs </span> </span> <span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">40 mins </span> </span> <span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">46 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <!-- BEGIN TODO DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-tasks" id="header_task_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-default"> 3 </span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <span class="bold">12 pending</span> tasks</h3> <a href="page_todo.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span> </span> </a> </li> </ul> </li> </ul> </li> <!-- END TODO DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-user"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <img alt="" class="img-circle" src="../../assets/admin/layout/img/avatar3_small.jpg"/> <span class="username username-hide-on-mobile"> Nick </span> <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu dropdown-menu-default"> <li> <a href="extra_profile.html"> <i class="icon-user"></i> My Profile </a> </li> <li> <a href="page_calendar.html"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li> <a href="page_todo.html"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="extra_lock.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="login.html"> <i class="icon-key"></i> Log Out </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> <!-- BEGIN QUICK SIDEBAR TOGGLER --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-quick-sidebar-toggler"> <a href="javascript:;" class="dropdown-toggle"> <i class="icon-logout"></i> </a> </li> <!-- END QUICK SIDEBAR TOGGLER --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> <!-- END HEADER INNER --> </div> <!-- END HEADER --> <div class="clearfix"> </div> <!-- BEGIN CONTAINER --> <div class="page-container"> <!-- BEGIN SIDEBAR --> <div class="page-sidebar-wrapper"> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed --> <div class="page-sidebar navbar-collapse collapse"> <!-- BEGIN SIDEBAR MENU --> <!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) --> <!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode --> <!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode --> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Set data-keep-expand="true" to keep the submenues expanded --> <!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed --> <ul class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> <!-- DOC: To remove the sidebar toggler from the sidebar you just need to completely remove the below "sidebar-toggler-wrapper" LI element --> <li class="sidebar-toggler-wrapper"> <!-- BEGIN SIDEBAR TOGGLER BUTTON --> <div class="sidebar-toggler"> </div> <!-- END SIDEBAR TOGGLER BUTTON --> </li> <!-- DOC: To remove the search box from the sidebar you just need to completely remove the below "sidebar-search-wrapper" LI element --> <li class="sidebar-search-wrapper"> <!-- BEGIN RESPONSIVE QUICK SEARCH FORM --> <!-- DOC: Apply "sidebar-search-bordered" class the below search form to have bordered search box --> <!-- DOC: Apply "sidebar-search-bordered sidebar-search-solid" class the below search form to have bordered & solid search box --> <form class="sidebar-search " action="extra_search.html" method="POST"> <a href="javascript:;" class="remove"> <i class="icon-close"></i> </a> <div class="input-group"> <input type="text" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a> </span> </div> </form> <!-- END RESPONSIVE QUICK SEARCH FORM --> </li> <li class="start "> <a href="javascript:;"> <i class="icon-home"></i> <span class="title">Dashboard</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="index.html"> <i class="icon-bar-chart"></i> Default Dashboard</a> </li> <li> <a href="index_2.html"> <i class="icon-bulb"></i> New Dashboard #1</a> </li> <li> <a href="index_3.html"> <i class="icon-graph"></i> New Dashboard #2</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-basket"></i> <span class="title">eCommerce</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="ecommerce_index.html"> <i class="icon-home"></i> Dashboard</a> </li> <li> <a href="ecommerce_orders.html"> <i class="icon-basket"></i> Orders</a> </li> <li> <a href="ecommerce_orders_view.html"> <i class="icon-tag"></i> Order View</a> </li> <li> <a href="ecommerce_products.html"> <i class="icon-handbag"></i> Products</a> </li> <li> <a href="ecommerce_products_edit.html"> <i class="icon-pencil"></i> Product Edit</a> </li> </ul> </li> <li class="active open"> <a href="javascript:;"> <i class="icon-rocket"></i> <span class="title">Page Layouts</span> <span class="selected"></span> <span class="arrow open"></span> </a> <ul class="sub-menu"> <li> <a href="layout_horizontal_sidebar_menu.html"> Horizontal & Sidebar Menu</a> </li> <li> <a href="index_horizontal_menu.html"> Dashboard & Mega Menu</a> </li> <li> <a href="layout_horizontal_menu1.html"> Horizontal Mega Menu 1</a> </li> <li> <a href="layout_horizontal_menu2.html"> Horizontal Mega Menu 2</a> </li> <li> <a href="layout_fontawesome_icons.html"> <span class="badge badge-roundless badge-danger">new</span>Layout with Fontawesome Icons</a> </li> <li> <a href="layout_glyphicons.html"> Layout with Glyphicon</a> </li> <li> <a href="layout_full_height_portlet.html"> <span class="badge badge-roundless badge-success">new</span>Full Height Portlet</a> </li> <li> <a href="layout_full_height_content.html"> <span class="badge badge-roundless badge-warning">new</span>Full Height Content</a> </li> <li> <a href="layout_search_on_header1.html"> Search Box On Header 1</a> </li> <li> <a href="layout_search_on_header2.html"> Search Box On Header 2</a> </li> <li> <a href="layout_sidebar_search_option1.html"> Sidebar Search Option 1</a> </li> <li> <a href="layout_sidebar_search_option2.html"> Sidebar Search Option 2</a> </li> <li class="active"> <a href="layout_sidebar_reversed.html"> <span class="badge badge-roundless badge-warning">new</span>Right Sidebar Page</a> </li> <li> <a href="layout_sidebar_fixed.html"> Sidebar Fixed Page</a> </li> <li> <a href="layout_sidebar_closed.html"> Sidebar Closed Page</a> </li> <li> <a href="layout_ajax.html"> Content Loading via Ajax</a> </li> <li> <a href="layout_disabled_menu.html"> Disabled Menu Links</a> </li> <li> <a href="layout_blank_page.html"> Blank Page</a> </li> <li> <a href="layout_boxed_page.html"> Boxed Page</a> </li> <li> <a href="layout_language_bar.html"> Language Switch Bar</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-diamond"></i> <span class="title">UI Features</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="ui_general.html"> General Components</a> </li> <li> <a href="ui_buttons.html"> Buttons</a> </li> <li> <a href="ui_confirmations.html"> Popover Confirmations</a> </li> <li> <a href="ui_icons.html"> <span class="badge badge-roundless badge-danger">new</span>Font Icons</a> </li> <li> <a href="ui_colors.html"> Flat UI Colors</a> </li> <li> <a href="ui_typography.html"> Typography</a> </li> <li> <a href="ui_tabs_accordions_navs.html"> Tabs, Accordions & Navs</a> </li> <li> <a href="ui_tree.html"> <span class="badge badge-roundless badge-danger">new</span>Tree View</a> </li> <li> <a href="ui_page_progress_style_1.html"> <span class="badge badge-roundless badge-warning">new</span>Page Progress Bar</a> </li> <li> <a href="ui_blockui.html"> Block UI</a> </li> <li> <a href="ui_bootstrap_growl.html"> <span class="badge badge-roundless badge-warning">new</span>Bootstrap Growl Notifications</a> </li> <li> <a href="ui_notific8.html"> Notific8 Notifications</a> </li> <li> <a href="ui_toastr.html"> Toastr Notifications</a> </li> <li> <a href="ui_alert_dialog_api.html"> <span class="badge badge-roundless badge-danger">new</span>Alerts & Dialogs API</a> </li> <li> <a href="ui_session_timeout.html"> Session Timeout</a> </li> <li> <a href="ui_idle_timeout.html"> User Idle Timeout</a> </li> <li> <a href="ui_modals.html"> Modals</a> </li> <li> <a href="ui_extended_modals.html"> Extended Modals</a> </li> <li> <a href="ui_tiles.html"> Tiles</a> </li> <li> <a href="ui_datepaginator.html"> <span class="badge badge-roundless badge-success">new</span>Date Paginator</a> </li> <li> <a href="ui_nestable.html"> Nestable List</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-puzzle"></i> <span class="title">UI Components</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="components_pickers.html"> Date & Time Pickers</a> </li> <li> <a href="components_context_menu.html"> Context Menu</a> </li> <li> <a href="components_dropdowns.html"> Custom Dropdowns</a> </li> <li> <a href="components_form_tools.html"> Form Widgets & Tools</a> </li> <li> <a href="components_form_tools2.html"> Form Widgets & Tools 2</a> </li> <li> <a href="components_editors.html"> Markdown & WYSIWYG Editors</a> </li> <li> <a href="components_ion_sliders.html"> Ion Range Sliders</a> </li> <li> <a href="components_noui_sliders.html"> NoUI Range Sliders</a> </li> <li> <a href="components_jqueryui_sliders.html"> jQuery UI Sliders</a> </li> <li> <a href="components_knob_dials.html"> Knob Circle Dials</a> </li> </ul> </li> <!-- BEGIN ANGULARJS LINK --> <li class="tooltips" data-container="body" data-placement="right" data-html="true" data-original-title="AngularJS version demo"> <a href="angularjs" target="_blank"> <i class="icon-paper-plane"></i> <span class="title"> AngularJS Version </span> </a> </li> <!-- END ANGULARJS LINK --> <li class="heading"> <h3 class="uppercase">Features</h3> </li> <li> <a href="javascript:;"> <i class="icon-settings"></i> <span class="title">Form Stuff</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="form_controls_md.html"> <span class="badge badge-roundless badge-danger">new</span>Material Design<br> Form Controls</a> </li> <li> <a href="form_controls.html"> Bootstrap<br> Form Controls</a> </li> <li> <a href="form_icheck.html"> iCheck Controls</a> </li> <li> <a href="form_layouts.html"> Form Layouts</a> </li> <li> <a href="form_editable.html"> <span class="badge badge-roundless badge-warning">new</span>Form X-editable</a> </li> <li> <a href="form_wizard.html"> Form Wizard</a> </li> <li> <a href="form_validation.html"> Form Validation</a> </li> <li> <a href="form_image_crop.html"> <span class="badge badge-roundless badge-danger">new</span>Image Cropping</a> </li> <li> <a href="form_fileupload.html"> Multiple File Upload</a> </li> <li> <a href="form_dropzone.html"> Dropzone File Upload</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-briefcase"></i> <span class="title">Data Tables</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="table_basic.html"> Basic Datatables</a> </li> <li> <a href="table_tree.html"> Tree Datatables</a> </li> <li> <a href="table_responsive.html"> Responsive Datatables</a> </li> <li> <a href="table_managed.html"> Managed Datatables</a> </li> <li> <a href="table_editable.html"> Editable Datatables</a> </li> <li> <a href="table_advanced.html"> Advanced Datatables</a> </li> <li> <a href="table_ajax.html"> Ajax Datatables</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-wallet"></i> <span class="title">Portlets</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="portlet_general.html"> General Portlets</a> </li> <li> <a href="portlet_general2.html"> <span class="badge badge-roundless badge-danger">new</span>New Portlets #1</a> </li> <li> <a href="portlet_general3.html"> <span class="badge badge-roundless badge-danger">new</span>New Portlets #2</a> </li> <li> <a href="portlet_ajax.html"> Ajax Portlets</a> </li> <li> <a href="portlet_draggable.html"> Draggable Portlets</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-bar-chart"></i> <span class="title">Charts</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="charts_amcharts.html"> amChart</a> </li> <li> <a href="charts_flotcharts.html"> Flotchart</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-docs"></i> <span class="title">Pages</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="page_timeline.html"> <i class="icon-paper-plane"></i> <span class="badge badge-warning">2</span>New Timeline</a> </li> <li> <a href="extra_profile.html"> <i class="icon-user-following"></i> <span class="badge badge-success badge-roundless">new</span>New User Profile</a> </li> <li> <a href="page_todo.html"> <i class="icon-check"></i> Todo</a> </li> <li> <a href="inbox.html"> <i class="icon-envelope"></i> <span class="badge badge-danger">4</span>Inbox</a> </li> <li> <a href="extra_faq.html"> <i class="icon-question"></i> FAQ</a> </li> <li> <a href="page_calendar.html"> <i class="icon-calendar"></i> <span class="badge badge-danger">14</span>Calendar</a> </li> <li> <a href="page_coming_soon.html"> <i class="icon-flag"></i> Coming Soon</a> </li> <li> <a href="page_blog.html"> <i class="icon-speech"></i> Blog</a> </li> <li> <a href="page_blog_item.html"> <i class="icon-link"></i> Blog Post</a> </li> <li> <a href="page_news.html"> <i class="icon-eye"></i> <span class="badge badge-success">9</span>News</a> </li> <li> <a href="page_news_item.html"> <i class="icon-bell"></i> News View</a> </li> <li> <a href="page_timeline_old.html"> <i class="icon-paper-plane"></i> <span class="badge badge-warning">2</span>Old Timeline</a> </li> <li> <a href="extra_profile_old.html"> <i class="icon-user"></i> Old User Profile</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-present"></i> <span class="title">Extra</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="page_about.html"> About Us</a> </li> <li> <a href="page_contact.html"> Contact Us</a> </li> <li> <a href="extra_search.html"> Search Results</a> </li> <li> <a href="extra_invoice.html"> Invoice</a> </li> <li> <a href="page_portfolio.html"> Portfolio</a> </li> <li> <a href="extra_pricing_table.html"> Pricing Tables</a> </li> <li> <a href="extra_404_option1.html"> 404 Page Option 1</a> </li> <li> <a href="extra_404_option2.html"> 404 Page Option 2</a> </li> <li> <a href="extra_404_option3.html"> 404 Page Option 3</a> </li> <li> <a href="extra_500_option1.html"> 500 Page Option 1</a> </li> <li> <a href="extra_500_option2.html"> 500 Page Option 2</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-folder"></i> <span class="title">Multi Level Menu</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="javascript:;"> <i class="icon-settings"></i> Item 1 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="javascript:;"> <i class="icon-user"></i> Sample Link 1 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="#"><i class="icon-power"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-paper-plane"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-star"></i> Sample Link 1</a> </li> </ul> </li> <li> <a href="#"><i class="icon-camera"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-link"></i> Sample Link 2</a> </li> <li> <a href="#"><i class="icon-pointer"></i> Sample Link 3</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-globe"></i> Item 2 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="#"><i class="icon-tag"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-pencil"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-graph"></i> Sample Link 1</a> </li> </ul> </li> <li> <a href="#"> <i class="icon-bar-chart"></i> Item 3 </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-user"></i> <span class="title">Login Options</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="login.html"> Login Form 1</a> </li> <li> <a href="login_2.html"> Login Form 2</a> </li> <li> <a href="login_3.html"> Login Form 3</a> </li> <li> <a href="login_soft.html"> Login Form 4</a> </li> <li> <a href="extra_lock.html"> Lock Screen 1</a> </li> <li> <a href="extra_lock2.html"> Lock Screen 2</a> </li> </ul> </li> <li class="heading"> <h3 class="uppercase">More</h3> </li> <li> <a href="javascript:;"> <i class="icon-logout"></i> <span class="title">Quick Sidebar</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="quick_sidebar_push_content.html"> Push Content</a> </li> <li> <a href="quick_sidebar_over_content.html"> Over Content</a> </li> <li> <a href="quick_sidebar_over_content_transparent.html"> Over Content & Transparent</a> </li> <li> <a href="quick_sidebar_on_boxed_layout.html"> Boxed Layout</a> </li> </ul> </li> <li class="last "> <a href="javascript:;"> <i class="icon-pointer"></i> <span class="title">Maps</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="maps_google.html"> Google Maps</a> </li> <li> <a href="maps_vector.html"> Vector Maps</a> </li> </ul> </li> </ul> <!-- END SIDEBAR MENU --> </div> </div> <!-- END SIDEBAR --> <!-- BEGIN CONTENT --> <div class="page-content-wrapper"> <div class="page-content"> <!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM--> <div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> Widget settings form goes here </div> <div class="modal-footer"> <button type="button" class="btn blue">Save changes</button> <button type="button" class="btn default" data-dismiss="modal">Close</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> <!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM--> <!-- BEGIN STYLE CUSTOMIZER --> <div class="theme-panel hidden-xs hidden-sm"> <div class="toggler"> </div> <div class="toggler-close"> </div> <div class="theme-options"> <div class="theme-option theme-colors clearfix"> <span> THEME COLOR </span> <ul> <li class="color-default current tooltips" data-style="default" data-container="body" data-original-title="Default"> </li> <li class="color-darkblue tooltips" data-style="darkblue" data-container="body" data-original-title="Dark Blue"> </li> <li class="color-blue tooltips" data-style="blue" data-container="body" data-original-title="Blue"> </li> <li class="color-grey tooltips" data-style="grey" data-container="body" data-original-title="Grey"> </li> <li class="color-light tooltips" data-style="light" data-container="body" data-original-title="Light"> </li> <li class="color-light2 tooltips" data-style="light2" data-container="body" data-html="true" data-original-title="Light 2"> </li> </ul> </div> <div class="theme-option"> <span> Theme Style </span> <select class="layout-style-option form-control input-sm"> <option value="square" selected="selected">Square corners</option> <option value="rounded">Rounded corners</option> </select> </div> <div class="theme-option"> <span> Layout </span> <select class="layout-option form-control input-sm"> <option value="fluid" selected="selected">Fluid</option> <option value="boxed">Boxed</option> </select> </div> <div class="theme-option"> <span> Header </span> <select class="page-header-option form-control input-sm"> <option value="fixed" selected="selected">Fixed</option> <option value="default">Default</option> </select> </div> <div class="theme-option"> <span> Top Menu Dropdown</span> <select class="page-header-top-dropdown-style-option form-control input-sm"> <option value="light" selected="selected">Light</option> <option value="dark">Dark</option> </select> </div> <div class="theme-option"> <span> Sidebar Mode</span> <select class="sidebar-option form-control input-sm"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </div> <div class="theme-option"> <span> Sidebar Menu </span> <select class="sidebar-menu-option form-control input-sm"> <option value="accordion" selected="selected">Accordion</option> <option value="hover">Hover</option> </select> </div> <div class="theme-option"> <span> Sidebar Style </span> <select class="sidebar-style-option form-control input-sm"> <option value="default" selected="selected">Default</option> <option value="light">Light</option> </select> </div> <div class="theme-option"> <span> Sidebar Position </span> <select class="sidebar-pos-option form-control input-sm"> <option value="left" selected="selected">Left</option> <option value="right">Right</option> </select> </div> <div class="theme-option"> <span> Footer </span> <select class="page-footer-option form-control input-sm"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </div> </div> </div> <!-- END STYLE CUSTOMIZER --> <!-- BEGIN PAGE HEADER--> <h3 class="page-title"> Right Sidebar Page <small>left sidebar page</small> </h3> <div class="page-bar"> <ul class="page-breadcrumb"> <li> <i class="fa fa-home"></i> <a href="index.html">Home</a> <i class="fa fa-angle-right"></i> </li> <li> <a href="#">Page Layouts</a> <i class="fa fa-angle-right"></i> </li> <li> <a href="#">Right Sidebar Page</a> </li> </ul> <div class="page-toolbar"> <div class="btn-group pull-right"> <button type="button" class="btn btn-fit-height grey-salt dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true"> Actions <i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu pull-right" role="menu"> <li> <a href="#">Action</a> </li> <li> <a href="#">Another action</a> </li> <li> <a href="#">Something else here</a> </li> <li class="divider"> </li> <li> <a href="#">Separated link</a> </li> </ul> </div> </div> </div> <!-- END PAGE HEADER--> <!-- BEGIN PAGE CONTENT--> <div class="row"> <div class="col-md-12"> Page content goes here </div> </div> <!-- END PAGE CONTENT--> </div> </div> <!-- END CONTENT --> <!-- BEGIN QUICK SIDEBAR --> <a href="javascript:;" class="page-quick-sidebar-toggler"><i class="icon-close"></i></a> <div class="page-quick-sidebar-wrapper"> <div class="page-quick-sidebar"> <div class="nav-justified"> <ul class="nav nav-tabs nav-justified"> <li class="active"> <a href="#quick_sidebar_tab_1" data-toggle="tab"> Users <span class="badge badge-danger">2</span> </a> </li> <li> <a href="#quick_sidebar_tab_2" data-toggle="tab"> Alerts <span class="badge badge-success">7</span> </a> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> More<i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu pull-right" role="menu"> <li> <a href="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-bell"></i> Alerts </a> </li> <li> <a href="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-info"></i> Notifications </a> </li> <li> <a href="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-speech"></i> Activities </a> </li> <li class="divider"> </li> <li> <a href="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-settings"></i> Settings </a> </li> </ul> </li> </ul> <div class="tab-content"> <div class="tab-pane active page-quick-sidebar-chat" id="quick_sidebar_tab_1"> <div class="page-quick-sidebar-chat-users" data-rail-color="#ddd" data-wrapper-class="page-quick-sidebar-list"> <h3 class="list-heading">Staff</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-success">8</span> </div> <img class="media-object" src="../../assets/admin/layout/img/avatar3.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Bob Nilson</h4> <div class="media-heading-sub"> Project Manager </div> </div> </li> <li class="media"> <img class="media-object" src="../../assets/admin/layout/img/avatar1.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Nick Larson</h4> <div class="media-heading-sub"> Art Director </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">3</span> </div> <img class="media-object" src="../../assets/admin/layout/img/avatar4.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Hubert</h4> <div class="media-heading-sub"> CTO </div> </div> </li> <li class="media"> <img class="media-object" src="../../assets/admin/layout/img/avatar2.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ella Wong</h4> <div class="media-heading-sub"> CEO </div> </div> </li> </ul> <h3 class="list-heading">Customers</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-warning">2</span> </div> <img class="media-object" src="../../assets/admin/layout/img/avatar6.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lara Kunis</h4> <div class="media-heading-sub"> CEO, Loop Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="label label-sm label-success">new</span> </div> <img class="media-object" src="../../assets/admin/layout/img/avatar7.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ernie Kyllonen</h4> <div class="media-heading-sub"> Project Manager,<br> SmartBizz PTL </div> </div> </li> <li class="media"> <img class="media-object" src="../../assets/admin/layout/img/avatar8.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lisa Stone</h4> <div class="media-heading-sub"> CTO, Keort Inc </div> <div class="media-heading-small"> Last seen 13:10 PM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-success">7</span> </div> <img class="media-object" src="../../assets/admin/layout/img/avatar9.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Portalatin</h4> <div class="media-heading-sub"> CFO, H&D LTD </div> </div> </li> <li class="media"> <img class="media-object" src="../../assets/admin/layout/img/avatar10.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Irina Savikova</h4> <div class="media-heading-sub"> CEO, Tizda Motors Inc </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">4</span> </div> <img class="media-object" src="../../assets/admin/layout/img/avatar11.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Maria Gomez</h4> <div class="media-heading-sub"> Manager, Infomatic Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> </ul> </div> <div class="page-quick-sidebar-item"> <div class="page-quick-sidebar-chat-user"> <div class="page-quick-sidebar-nav"> <a href="javascript:;" class="page-quick-sidebar-back-to-list"><i class="icon-arrow-left"></i>Back</a> </div> <div class="page-quick-sidebar-chat-user-messages"> <div class="post out"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> When could you send me the report ? </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:15</span> <span class="body"> Its almost done. I will be sending it shortly </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> Alright. Thanks! :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:16</span> <span class="body"> You are most welcome. Sorry for the delay. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> No probs. Just take your time :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Alright. I just emailed it to you. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Great! Thanks. Will check it right away. </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Please let me know if you have any comment. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Sure. I will check and buzz you if anything needs to be corrected. </span> </div> </div> </div> <div class="page-quick-sidebar-chat-user-form"> <div class="input-group"> <input type="text" class="form-control" placeholder="Type a message here..."> <div class="input-group-btn"> <button type="button" class="btn blue"><i class="icon-paper-clip"></i></button> </div> </div> </div> </div> </div> </div> <div class="tab-pane page-quick-sidebar-alerts" id="quick_sidebar_tab_2"> <div class="page-quick-sidebar-alerts-list"> <h3 class="list-heading">General</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-warning"> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> <h3 class="list-heading">System</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-warning"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-default "> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> </div> </div> <div class="tab-pane page-quick-sidebar-settings" id="quick_sidebar_tab_3"> <div class="page-quick-sidebar-settings-list"> <h3 class="list-heading">General Settings</h3> <ul class="list-items borderless"> <li> Enable Notifications <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Allow Tracking <input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Log Errors <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Auto Sumbit Issues <input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Enable SMS Alerts <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <h3 class="list-heading">System Settings</h3> <ul class="list-items borderless"> <li> Security Level <select class="form-control input-inline input-sm input-small"> <option value="1">Normal</option> <option value="2" selected>Medium</option> <option value="e">High</option> </select> </li> <li> Failed Email Attempts <input class="form-control input-inline input-sm input-small" value="5"/> </li> <li> Secondary SMTP Port <input class="form-control input-inline input-sm input-small" value="3560"/> </li> <li> Notify On System Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Notify On SMTP Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <div class="inner-content"> <button class="btn btn-success"><i class="icon-settings"></i> Save Changes</button> </div> </div> </div> </div> </div> </div> </div> <!-- END QUICK SIDEBAR --> </div> <!-- END CONTAINER --> <!-- BEGIN FOOTER --> <div class="page-footer"> <div class="page-footer-inner"> 2014 &copy; Metronic by keenthemes. <a href="http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Metronic!</a> </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> </div> <!-- END FOOTER --> <!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) --> <!-- BEGIN CORE PLUGINS --> <!--[if lt IE 9]> <script src="../../assets/global/plugins/respond.min.js"></script> <script src="../../assets/global/plugins/excanvas.min.js"></script> <![endif]--> <script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script> <!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip --> <script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script> <script src="../../assets/admin/layout/scripts/layout.js" type="text/javascript"></script> <script src="../../assets/admin/layout/scripts/quick-sidebar.js" type="text/javascript"></script> <script src="../../assets/admin/layout/scripts/demo.js" type="text/javascript"></script> <script> jQuery(document).ready(function() { Metronic.init(); // init metronic core components Layout.init(); // init current layout QuickSidebar.init(); // init quick sidebar Demo.init(); // init demo features }); </script> <script type="text/javascript"> jQuery(document).ready(function() { //Hide the overview when click $('#someid').on('click', function () { $('#OverviewcollapseButton').removeClass("collapse").addClass("expand"); $('#PaymentOverview').hide(); }); }); </script> <!-- END JAVASCRIPTS --> </body> <!-- END BODY --> </html>
{ "content_hash": "1fc9621b1cdbf0d3cf1185ada1e6d630", "timestamp": "", "source": "github", "line_count": 2068, "max_line_length": 256, "avg_line_length": 33.16441005802708, "alnum_prop": 0.5267992534701972, "repo_name": "aniruddha-chakraborty/tax", "id": "2f23665456d9fcdc77496520d9d7c563df4f708d", "size": "68584", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/layout_sidebar_reversed.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "290" }, { "name": "ApacheConf", "bytes": "1019" }, { "name": "CSS", "bytes": "85931" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "HTML", "bytes": "15914223" }, { "name": "JavaScript", "bytes": "13217389" }, { "name": "PHP", "bytes": "598306" }, { "name": "Shell", "bytes": "444" } ], "symlink_target": "" }
#include <cmath> #include <QtWidgets/QWidget> #include <QtWidgets/QLabel> #include <QtWidgets/QLayout> #include <QtGui/QPixmap> #include <QtGui/QImage> #include <QtGui/QPainter> #include <QtGui/QShowEvent> #include <QtGui/QResizeEvent> #include <QtGui/QColor> #include "../../../constants/ColorConstants.h" #include "../../../utils/PixmapUtils.h" namespace Capture3 { class GraphicComponent : public QLabel { Q_OBJECT public: GraphicComponent( const unsigned int width, const unsigned int height ); virtual ~GraphicComponent(); virtual int heightForWidth(int width) const; virtual QSize sizeHint() const; void setBackgroundColor(const unsigned int r, const unsigned int g, const unsigned int b); void setBackgroundImage(QImage image); void redraw(); protected: virtual void draw(QPainter &painter); virtual void showEvent(QShowEvent *event); virtual void resizeEvent(QResizeEvent *event); private: const double ratio; QColor backgroundColor; QImage backgroundImage; }; } #endif // CAPTURE3_GRAPHIC_COMPONENT_H
{ "content_hash": "7e70ce653a1630bfcc645bd98433cee2", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 93, "avg_line_length": 19.79310344827586, "alnum_prop": 0.6855400696864111, "repo_name": "ferdikoomen/capture3", "id": "60abc2cddbbb2a5ddf2285a96e2d269c95c8f1b2", "size": "1224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/application/components/graphic/GraphicComponent.h", "mode": "33261", "license": "mit", "language": [ { "name": "C++", "bytes": "487511" }, { "name": "CMake", "bytes": "7773" }, { "name": "CSS", "bytes": "27757" }, { "name": "GLSL", "bytes": "274" }, { "name": "Shell", "bytes": "1018" } ], "symlink_target": "" }
using namespace llvm; #define DEBUG_TYPE "slotindexes" char SlotIndexes::ID = 0; SlotIndexes::SlotIndexes() : MachineFunctionPass(ID), mf(nullptr) { initializeSlotIndexesPass(*PassRegistry::getPassRegistry()); } SlotIndexes::~SlotIndexes() { // The indexList's nodes are all allocated in the BumpPtrAllocator. indexList.clearAndLeakNodesUnsafely(); } INITIALIZE_PASS(SlotIndexes, DEBUG_TYPE, "Slot index numbering", false, false) STATISTIC(NumLocalRenum, "Number of local renumberings"); void SlotIndexes::getAnalysisUsage(AnalysisUsage &au) const { au.setPreservesAll(); MachineFunctionPass::getAnalysisUsage(au); } void SlotIndexes::releaseMemory() { mi2iMap.clear(); MBBRanges.clear(); idx2MBBMap.clear(); indexList.clear(); ileAllocator.Reset(); } bool SlotIndexes::runOnMachineFunction(MachineFunction &fn) { // Compute numbering as follows: // Grab an iterator to the start of the index list. // Iterate over all MBBs, and within each MBB all MIs, keeping the MI // iterator in lock-step (though skipping it over indexes which have // null pointers in the instruction field). // At each iteration assert that the instruction pointed to in the index // is the same one pointed to by the MI iterator. This // FIXME: This can be simplified. The mi2iMap_, Idx2MBBMap, etc. should // only need to be set up once after the first numbering is computed. mf = &fn; // Check that the list contains only the sentinal. assert(indexList.empty() && "Index list non-empty at initial numbering?"); assert(idx2MBBMap.empty() && "Index -> MBB mapping non-empty at initial numbering?"); assert(MBBRanges.empty() && "MBB -> Index mapping non-empty at initial numbering?"); assert(mi2iMap.empty() && "MachineInstr -> Index mapping non-empty at initial numbering?"); unsigned index = 0; MBBRanges.resize(mf->getNumBlockIDs()); idx2MBBMap.reserve(mf->size()); indexList.push_back(createEntry(nullptr, index)); // Iterate over the function. for (MachineBasicBlock &MBB : *mf) { // Insert an index for the MBB start. SlotIndex blockStartIndex(&indexList.back(), SlotIndex::Slot_Block); for (MachineInstr &MI : MBB) { if (MI.isDebugInstr()) continue; // Insert a store index for the instr. indexList.push_back(createEntry(&MI, index += SlotIndex::InstrDist)); // Save this base index in the maps. mi2iMap.insert(std::make_pair( &MI, SlotIndex(&indexList.back(), SlotIndex::Slot_Block))); } // We insert one blank instructions between basic blocks. indexList.push_back(createEntry(nullptr, index += SlotIndex::InstrDist)); MBBRanges[MBB.getNumber()].first = blockStartIndex; MBBRanges[MBB.getNumber()].second = SlotIndex(&indexList.back(), SlotIndex::Slot_Block); idx2MBBMap.push_back(IdxMBBPair(blockStartIndex, &MBB)); } // Sort the Idx2MBBMap llvm::sort(idx2MBBMap, less_first()); LLVM_DEBUG(mf->print(dbgs(), this)); // And we're done! return false; } void SlotIndexes::removeMachineInstrFromMaps(MachineInstr &MI) { assert(!MI.isBundledWithPred() && "Use removeSingleMachineInstrFromMaps() instread"); Mi2IndexMap::iterator mi2iItr = mi2iMap.find(&MI); if (mi2iItr == mi2iMap.end()) return; SlotIndex MIIndex = mi2iItr->second; IndexListEntry &MIEntry = *MIIndex.listEntry(); assert(MIEntry.getInstr() == &MI && "Instruction indexes broken."); mi2iMap.erase(mi2iItr); // FIXME: Eventually we want to actually delete these indexes. MIEntry.setInstr(nullptr); } void SlotIndexes::removeSingleMachineInstrFromMaps(MachineInstr &MI) { Mi2IndexMap::iterator mi2iItr = mi2iMap.find(&MI); if (mi2iItr == mi2iMap.end()) return; SlotIndex MIIndex = mi2iItr->second; IndexListEntry &MIEntry = *MIIndex.listEntry(); assert(MIEntry.getInstr() == &MI && "Instruction indexes broken."); mi2iMap.erase(mi2iItr); // When removing the first instruction of a bundle update mapping to next // instruction. if (MI.isBundledWithSucc()) { // Only the first instruction of a bundle should have an index assigned. assert(!MI.isBundledWithPred() && "Should have first bundle isntruction"); MachineBasicBlock::instr_iterator Next = std::next(MI.getIterator()); MachineInstr &NextMI = *Next; MIEntry.setInstr(&NextMI); mi2iMap.insert(std::make_pair(&NextMI, MIIndex)); return; } else { // FIXME: Eventually we want to actually delete these indexes. MIEntry.setInstr(nullptr); } } // Renumber indexes locally after curItr was inserted, but failed to get a new // index. void SlotIndexes::renumberIndexes(IndexList::iterator curItr) { // Number indexes with half the default spacing so we can catch up quickly. const unsigned Space = SlotIndex::InstrDist/2; static_assert((Space & 3) == 0, "InstrDist must be a multiple of 2*NUM"); IndexList::iterator startItr = std::prev(curItr); unsigned index = startItr->getIndex(); do { curItr->setIndex(index += Space); ++curItr; // If the next index is bigger, we have caught up. } while (curItr != indexList.end() && curItr->getIndex() <= index); LLVM_DEBUG(dbgs() << "\n*** Renumbered SlotIndexes " << startItr->getIndex() << '-' << index << " ***\n"); ++NumLocalRenum; } // Repair indexes after adding and removing instructions. void SlotIndexes::repairIndexesInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End) { // FIXME: Is this really necessary? The only caller repairIntervalsForRange() // does the same thing. // Find anchor points, which are at the beginning/end of blocks or at // instructions that already have indexes. while (Begin != MBB->begin() && !hasIndex(*Begin)) --Begin; while (End != MBB->end() && !hasIndex(*End)) ++End; bool includeStart = (Begin == MBB->begin()); SlotIndex startIdx; if (includeStart) startIdx = getMBBStartIdx(MBB); else startIdx = getInstructionIndex(*Begin); SlotIndex endIdx; if (End == MBB->end()) endIdx = getMBBEndIdx(MBB); else endIdx = getInstructionIndex(*End); // FIXME: Conceptually, this code is implementing an iterator on MBB that // optionally includes an additional position prior to MBB->begin(), indicated // by the includeStart flag. This is done so that we can iterate MIs in a MBB // in parallel with SlotIndexes, but there should be a better way to do this. IndexList::iterator ListB = startIdx.listEntry()->getIterator(); IndexList::iterator ListI = endIdx.listEntry()->getIterator(); MachineBasicBlock::iterator MBBI = End; bool pastStart = false; while (ListI != ListB || MBBI != Begin || (includeStart && !pastStart)) { assert(ListI->getIndex() >= startIdx.getIndex() && (includeStart || !pastStart) && "Decremented past the beginning of region to repair."); MachineInstr *SlotMI = ListI->getInstr(); MachineInstr *MI = (MBBI != MBB->end() && !pastStart) ? &*MBBI : nullptr; bool MBBIAtBegin = MBBI == Begin && (!includeStart || pastStart); if (SlotMI == MI && !MBBIAtBegin) { --ListI; if (MBBI != Begin) --MBBI; else pastStart = true; } else if (MI && mi2iMap.find(MI) == mi2iMap.end()) { if (MBBI != Begin) --MBBI; else pastStart = true; } else { --ListI; if (SlotMI) removeMachineInstrFromMaps(*SlotMI); } } // In theory this could be combined with the previous loop, but it is tricky // to update the IndexList while we are iterating it. for (MachineBasicBlock::iterator I = End; I != Begin;) { --I; MachineInstr &MI = *I; if (!MI.isDebugInstr() && mi2iMap.find(&MI) == mi2iMap.end()) insertMachineInstrInMaps(MI); } } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void SlotIndexes::dump() const { for (IndexList::const_iterator itr = indexList.begin(); itr != indexList.end(); ++itr) { dbgs() << itr->getIndex() << " "; if (itr->getInstr()) { dbgs() << *itr->getInstr(); } else { dbgs() << "\n"; } } for (unsigned i = 0, e = MBBRanges.size(); i != e; ++i) dbgs() << "%bb." << i << "\t[" << MBBRanges[i].first << ';' << MBBRanges[i].second << ")\n"; } #endif // Print a SlotIndex to a raw_ostream. void SlotIndex::print(raw_ostream &os) const { if (isValid()) os << listEntry()->getIndex() << "Berd"[getSlot()]; else os << "invalid"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) // Dump a SlotIndex to stderr. LLVM_DUMP_METHOD void SlotIndex::dump() const { print(dbgs()); dbgs() << "\n"; } #endif
{ "content_hash": "bc7b6a8e171cef89fd8edd7fc7a14c82", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 80, "avg_line_length": 33.33458646616541, "alnum_prop": 0.6579451900304499, "repo_name": "endlessm/chromium-browser", "id": "6664b58eccf8c7e0f0e49b4007c4a279031ef57a", "size": "9492", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "third_party/swiftshader/third_party/llvm-10.0/llvm/lib/CodeGen/SlotIndexes.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_pass.h" namespace tensorflow { REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 0, MlirImportPass); } // namespace tensorflow
{ "content_hash": "5cd1a33c4da920de58f2b500ee14ceb0", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 78, "avg_line_length": 23.9, "alnum_prop": 0.7322175732217573, "repo_name": "ppwwyyxx/tensorflow", "id": "7855cf6ac685412436b0462fe4993a5a6b440cb7", "size": "907", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tensorflow/compiler/mlir/tensorflow/translate/mlir_import_pass_registration.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "5003" }, { "name": "Batchfile", "bytes": "45318" }, { "name": "C", "bytes": "796611" }, { "name": "C#", "bytes": "8562" }, { "name": "C++", "bytes": "76521274" }, { "name": "CMake", "bytes": "6545" }, { "name": "Dockerfile", "bytes": "81136" }, { "name": "Go", "bytes": "1679107" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "952883" }, { "name": "Jupyter Notebook", "bytes": "567243" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "1254789" }, { "name": "Makefile", "bytes": "61284" }, { "name": "Objective-C", "bytes": "104706" }, { "name": "Objective-C++", "bytes": "297774" }, { "name": "PHP", "bytes": "24055" }, { "name": "Pascal", "bytes": "3752" }, { "name": "Pawn", "bytes": "17546" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "38709528" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "7469" }, { "name": "Shell", "bytes": "643731" }, { "name": "Smarty", "bytes": "34743" }, { "name": "Swift", "bytes": "62814" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Security; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("gdal")] [assembly: AssemblyDescription("GDAL C# Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("gdal.snk")] [assembly: AssemblyKeyName("")] // The AllowPartiallyTrustedCallersAttribute requires the assembly to be signed with a strong name key. // This attribute is necessary since the control is called by either an intranet or Internet // Web page that should be running under restricted permissions. [assembly: AllowPartiallyTrustedCallers] // Use the .NET Framework 2.0 transparency rules (level 1 transparency) as default #if (CLR4) [assembly: SecurityRules(SecurityRuleSet.Level1)] #endif
{ "content_hash": "99d209fc55be8df0c8d79b9a0916e404", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 103, "avg_line_length": 40.49295774647887, "alnum_prop": 0.72, "repo_name": "TUW-GEO/OGRSpatialRef3D", "id": "15227b1c439027a12c87d2ae5507ef26d036cdd8", "size": "4400", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "gdal-1.10.0/swig/csharp/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9944221" }, { "name": "C#", "bytes": "134293" }, { "name": "C++", "bytes": "33482636" }, { "name": "IDL", "bytes": "68" }, { "name": "Java", "bytes": "741034" }, { "name": "Objective-C", "bytes": "42440" }, { "name": "OpenEdge ABL", "bytes": "28024" }, { "name": "PHP", "bytes": "106999" }, { "name": "Perl", "bytes": "41158" }, { "name": "Python", "bytes": "904411" }, { "name": "Shell", "bytes": "592442" }, { "name": "TeX", "bytes": "344" }, { "name": "Visual Basic", "bytes": "49037" } ], "symlink_target": "" }
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var _ = require('lodash'); /* jshint ignore:line */ var Holodeck = require('../../../../holodeck'); /* jshint ignore:line */ var Request = require( '../../../../../../lib/http/request'); /* jshint ignore:line */ var Response = require( '../../../../../../lib/http/response'); /* jshint ignore:line */ var RestException = require( '../../../../../../lib/base/RestException'); /* jshint ignore:line */ var Twilio = require('../../../../../../lib'); /* jshint ignore:line */ var client; var holodeck; describe('DependentHostedNumberOrder', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', { httpClient: holodeck }); }); it('should treat the first each arg as a callback', function(done) { var body = JSON.stringify({ 'meta': { 'first_page_url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0', 'key': 'items', 'next_page_url': null, 'page': 0, 'page_size': 50, 'previous_page_url': null, 'url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0' }, 'items': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'address_sid': 'AD11111111111111111111111111111111', 'call_delay': 15, 'capabilities': { 'sms': true, 'voice': false }, 'cc_emails': [ 'aaa@twilio.com', 'bbb@twilio.com' ], 'date_created': '2017-03-28T20:06:39Z', 'date_updated': '2017-03-28T20:06:39Z', 'email': 'test@twilio.com', 'extension': '1234', 'friendly_name': 'friendly_name', 'incoming_phone_number_sid': 'PN11111111111111111111111111111111', 'phone_number': '+14153608311', 'sid': 'HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'signing_document_sid': 'PX11111111111111111111111111111111', 'status': 'received', 'failure_reason': '', 'unique_name': 'foobar', 'verification_attempts': 0, 'verification_call_sids': [ 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab' ], 'verification_code': '8794', 'verification_document_sid': null, 'verification_type': 'phone-call' } ] }); holodeck.mock(new Response(200, body)); client.preview.hosted_numbers.authorizationDocuments('PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .dependentHostedNumberOrders.each(() => done()); } ); it('should treat the second arg as a callback', function(done) { var body = JSON.stringify({ 'meta': { 'first_page_url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0', 'key': 'items', 'next_page_url': null, 'page': 0, 'page_size': 50, 'previous_page_url': null, 'url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0' }, 'items': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'address_sid': 'AD11111111111111111111111111111111', 'call_delay': 15, 'capabilities': { 'sms': true, 'voice': false }, 'cc_emails': [ 'aaa@twilio.com', 'bbb@twilio.com' ], 'date_created': '2017-03-28T20:06:39Z', 'date_updated': '2017-03-28T20:06:39Z', 'email': 'test@twilio.com', 'extension': '1234', 'friendly_name': 'friendly_name', 'incoming_phone_number_sid': 'PN11111111111111111111111111111111', 'phone_number': '+14153608311', 'sid': 'HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'signing_document_sid': 'PX11111111111111111111111111111111', 'status': 'received', 'failure_reason': '', 'unique_name': 'foobar', 'verification_attempts': 0, 'verification_call_sids': [ 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab' ], 'verification_code': '8794', 'verification_document_sid': null, 'verification_type': 'phone-call' } ] }); holodeck.mock(new Response(200, body)); client.preview.hosted_numbers.authorizationDocuments('PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .dependentHostedNumberOrders.each({pageSize: 20}, () => done()); holodeck.assertHasRequest(new Request({ method: 'GET', url: 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/<%= signingDocumentSid %>/DependentHostedNumberOrders', params: {PageSize: 20}, })); } ); it('should find the callback in the opts object', function(done) { var body = JSON.stringify({ 'meta': { 'first_page_url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0', 'key': 'items', 'next_page_url': null, 'page': 0, 'page_size': 50, 'previous_page_url': null, 'url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0' }, 'items': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'address_sid': 'AD11111111111111111111111111111111', 'call_delay': 15, 'capabilities': { 'sms': true, 'voice': false }, 'cc_emails': [ 'aaa@twilio.com', 'bbb@twilio.com' ], 'date_created': '2017-03-28T20:06:39Z', 'date_updated': '2017-03-28T20:06:39Z', 'email': 'test@twilio.com', 'extension': '1234', 'friendly_name': 'friendly_name', 'incoming_phone_number_sid': 'PN11111111111111111111111111111111', 'phone_number': '+14153608311', 'sid': 'HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'signing_document_sid': 'PX11111111111111111111111111111111', 'status': 'received', 'failure_reason': '', 'unique_name': 'foobar', 'verification_attempts': 0, 'verification_call_sids': [ 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab' ], 'verification_code': '8794', 'verification_document_sid': null, 'verification_type': 'phone-call' } ] }); holodeck.mock(new Response(200, body)); client.preview.hosted_numbers.authorizationDocuments('PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .dependentHostedNumberOrders.each({callback: () => done()}, () => fail('wrong callback!')); } ); it('should generate valid list request', function() { holodeck.mock(new Response(500, '{}')); var promise = client.preview.hosted_numbers.authorizationDocuments('PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .dependentHostedNumberOrders.list(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); }); promise.done(); var solution = {signingDocumentSid: 'PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'}; var url = _.template('https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/<%= signingDocumentSid %>/DependentHostedNumberOrders')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_empty response', function() { var body = JSON.stringify({ 'meta': { 'first_page_url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0', 'key': 'items', 'next_page_url': null, 'page': 0, 'page_size': 50, 'previous_page_url': null, 'url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0' }, 'items': [] }); holodeck.mock(new Response(200, body)); var promise = client.preview.hosted_numbers.authorizationDocuments('PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .dependentHostedNumberOrders.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid read_full response', function() { var body = JSON.stringify({ 'meta': { 'first_page_url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0', 'key': 'items', 'next_page_url': null, 'page': 0, 'page_size': 50, 'previous_page_url': null, 'url': 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0' }, 'items': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'address_sid': 'AD11111111111111111111111111111111', 'call_delay': 15, 'capabilities': { 'sms': true, 'voice': false }, 'cc_emails': [ 'aaa@twilio.com', 'bbb@twilio.com' ], 'date_created': '2017-03-28T20:06:39Z', 'date_updated': '2017-03-28T20:06:39Z', 'email': 'test@twilio.com', 'extension': '1234', 'friendly_name': 'friendly_name', 'incoming_phone_number_sid': 'PN11111111111111111111111111111111', 'phone_number': '+14153608311', 'sid': 'HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'signing_document_sid': 'PX11111111111111111111111111111111', 'status': 'received', 'failure_reason': '', 'unique_name': 'foobar', 'verification_attempts': 0, 'verification_call_sids': [ 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab' ], 'verification_code': '8794', 'verification_document_sid': null, 'verification_type': 'phone-call' } ] }); holodeck.mock(new Response(200, body)); var promise = client.preview.hosted_numbers.authorizationDocuments('PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .dependentHostedNumberOrders.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); });
{ "content_hash": "c24c4986eac09722859b3509a49f129a", "timestamp": "", "source": "github", "line_count": 309, "max_line_length": 180, "avg_line_length": 42.70873786407767, "alnum_prop": 0.5229976509812836, "repo_name": "philnash/twilio-node", "id": "2ac7fabbe3ddf6e13a5f5103be4860985118112f", "size": "13197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/integration/rest/preview/hosted_numbers/authorizationDocument/dependentHostedNumberOrder.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "161" }, { "name": "JavaScript", "bytes": "8949872" }, { "name": "Makefile", "bytes": "872" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes"> <title>uvalib-chat</title> <script src="../webcomponentsjs/webcomponents-lite.js"></script> <link rel="import" href="../iron-component-page/iron-component-page.html"> </head> <body> <iron-component-page src="uvalib-chat.html"></iron-component-page> </body> </html>
{ "content_hash": "a1e7cb3d8d62e13662782093296034cb", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 108, "avg_line_length": 28.625, "alnum_prop": 0.665938864628821, "repo_name": "uvalib/staff-directory", "id": "5a0dffe550daad12d255c80a39ca09cc1de4109a", "size": "458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bower_components/uvalib-chat/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11215" }, { "name": "HTML", "bytes": "30603" }, { "name": "JavaScript", "bytes": "16865" }, { "name": "Ruby", "bytes": "3065" }, { "name": "Shell", "bytes": "104" } ], "symlink_target": "" }
<?php get_header(); ?> <div class="container-fluid" id="overview"> <?php $blog_hero = of_get_option('blog_hero'); if ($blog_hero){ ?> <div class="clearfix row"> <div class="jumbotron"> <h1><?php bloginfo('title'); ?></h1> <p><?php bloginfo('description'); ?></p> </div> </div> <?php } ?> <div id="content" class="clearfix row"> <div id="main" class="col-sm-9 col-md-9 col-lg-9 clearfix cards-pf" role="main"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php if (function_exists('page_navi')) { // if expirimental feature is active ?> <?php page_navi(); // use the page navi function ?> <?php } else { // if it is disabled, display regular wp prev & next links ?> <nav class="wp-prev-next"> <ul class="clearfix list-unstyled"> <li class="prev-link"><?php next_posts_link(_e('&laquo; Older Entries', "bonestheme")) ?></li> <li class="next-link"><?php previous_posts_link(_e('Newer Entries &raquo;', "bonestheme")) ?></li> </ul> </nav> <?php } ?> <?php else : ?> <article id="post-not-found"> <header> <h1><?php _e("Not Found", "bonestheme"); ?></h1> </header> <section class="post_content"> <p><?php _e("Sorry, but the requested resource was not found on this site.", "bonestheme"); ?></p> </section> </article> <?php endif; ?> </div> <!-- end #main --> <?php get_sidebar(); // sidebar 1 ?> </div> <!-- end #content --> <?php get_footer(); ?> </div> <!-- end #overiew -->
{ "content_hash": "5c5b6018222306912689196d76afe628", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 108, "avg_line_length": 27.661290322580644, "alnum_prop": 0.5265306122448979, "repo_name": "patternfly/patternfly-blog", "id": "8304373c30cd1a98198dbebf38790fa13a5b0203", "size": "1715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "906196" }, { "name": "CoffeeScript", "bytes": "16833" }, { "name": "HTML", "bytes": "613999" }, { "name": "JavaScript", "bytes": "1131948" }, { "name": "PHP", "bytes": "159748" }, { "name": "Ruby", "bytes": "687" }, { "name": "Shell", "bytes": "1028" } ], "symlink_target": "" }
from . tasks import * from . import qp
{ "content_hash": "69e11624fcab4db0fce1aea4d9b268fb", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 21, "avg_line_length": 19.5, "alnum_prop": 0.6923076923076923, "repo_name": "jrl-umi3218/Tasks", "id": "a5ea9dd42f0f8b46ebfaa05a8372c4abdd48d434", "size": "39", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "binding/python/tasks/__init__.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "461588" }, { "name": "CMake", "bytes": "117745" }, { "name": "Cython", "bytes": "179171" }, { "name": "Python", "bytes": "76685" }, { "name": "Shell", "bytes": "1056" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head><meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>HylaFAXClientConnectionFactory xref</title> <link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../../apidocs/org/fax4j/spi/hylafax/HylaFAXClientConnectionFactory.html">View Javadoc</a></div><pre> <a class="jxr_linenumber" name="L1" href="#L1">1</a> <strong class="jxr_keyword">package</strong> org.fax4j.spi.hylafax; <a class="jxr_linenumber" name="L2" href="#L2">2</a> <a class="jxr_linenumber" name="L3" href="#L3">3</a> <strong class="jxr_keyword">import</strong> gnu.hylafax.HylaFAXClient; <a class="jxr_linenumber" name="L4" href="#L4">4</a> <strong class="jxr_keyword">import</strong> org.fax4j.util.ConnectionFactory; <a class="jxr_linenumber" name="L5" href="#L5">5</a> <a class="jxr_linenumber" name="L6" href="#L6">6</a> <em class="jxr_javadoccomment">/**</em> <a class="jxr_linenumber" name="L7" href="#L7">7</a> <em class="jxr_javadoccomment"> * This interface defines the HaylaFAX connection factory.</em> <a class="jxr_linenumber" name="L8" href="#L8">8</a> <em class="jxr_javadoccomment"> * </em> <a class="jxr_linenumber" name="L9" href="#L9">9</a> <em class="jxr_javadoccomment"> * @author Sagie Gur-Ari</em> <a class="jxr_linenumber" name="L10" href="#L10">10</a> <em class="jxr_javadoccomment"> * @version 1.01</em> <a class="jxr_linenumber" name="L11" href="#L11">11</a> <em class="jxr_javadoccomment"> * @since 0.39a</em> <a class="jxr_linenumber" name="L12" href="#L12">12</a> <em class="jxr_javadoccomment"> */</em> <a class="jxr_linenumber" name="L13" href="#L13">13</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">interface</strong> <a name="HylaFAXClientConnectionFactory" href="../../../../org/fax4j/spi/hylafax/HylaFAXClientConnectionFactory.html#HylaFAXClientConnectionFactory">HylaFAXClientConnectionFactory</a> <strong class="jxr_keyword">extends</strong> ConnectionFactory&lt;HylaFAXClient&gt; { <a class="jxr_linenumber" name="L14" href="#L14">14</a> <em class="jxr_comment">// empty (everything defined in parent interfaces)</em> <a class="jxr_linenumber" name="L15" href="#L15">15</a> } </pre> <hr/> <div id="footer">Copyright &#169; 2009&#x2013;2020 <a href="https://github.com/sagiegurari/fax4j">fax4j</a>. All rights reserved.</div> </body> </html>
{ "content_hash": "8de99db9de25c2288d311aa9dffb1b44", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 417, "avg_line_length": 92.67857142857143, "alnum_prop": 0.6882466281310212, "repo_name": "sagiegurari/fax4j", "id": "f640d562527203c1b1032d5290f3d231c52fffe0", "size": "2595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/xref/org/fax4j/spi/hylafax/HylaFAXClientConnectionFactory.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "340" }, { "name": "C", "bytes": "5384" }, { "name": "C++", "bytes": "28759" }, { "name": "CMake", "bytes": "42888" }, { "name": "HTML", "bytes": "245" }, { "name": "Java", "bytes": "1258648" }, { "name": "Shell", "bytes": "24" }, { "name": "VBScript", "bytes": "5882" } ], "symlink_target": "" }
if [ ! -f deploy.key ]; then exit; fi eval `ssh-agent -s` ssh-add deploy.key git clone -b master git@github.com:the-tricktionary/the-tricktionary.github.io.git .deploy || exit 1 cd .deploy || exit 1 git config user.name travis git config user.email travis@nowhere cp -R ../app/build/outputs/apk/debug/app-debug.apk "./apps/app-${TRAVIS_BRANCH/\//-}.apk" git add -A git commit -m "travis: ${TRAVIS_COMMIT}" git push || exit 1 cd ..
{ "content_hash": "0f5339cdad1d1c80d401ac1426718922", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 100, "avg_line_length": 33.23076923076923, "alnum_prop": 0.7037037037037037, "repo_name": "the-tricktionary/android", "id": "6bac273ccfb1056466b0a50fdd508798138f2dff", "size": "507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deploy.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1375" }, { "name": "Java", "bytes": "425562" }, { "name": "Shell", "bytes": "957" } ], "symlink_target": "" }
@implementation MHPinchGestureRecognizer @end @interface MHImageViewController () @property (nonatomic, strong) UIButton *moviewPlayerButtonBehinde; @property (nonatomic, strong) UIToolbar *moviePlayerToolBarTop; @property (nonatomic, strong) UISlider *slider; @property (nonatomic, strong) UIProgressView *videoProgressView; @property (nonatomic, strong) UILabel *leftSliderLabel; @property (nonatomic, strong) UILabel *rightSliderLabel; @property (nonatomic, strong) NSTimer *movieTimer; @property (nonatomic, strong) NSTimer *movieDownloadedTimer; @property (nonatomic, strong) UIPanGestureRecognizer *pan; @property (nonatomic, strong) MHPinchGestureRecognizer *pinch; @property (nonatomic) NSInteger wholeTimeMovie; @property (nonatomic) CGPoint pointToCenterAfterResize; @property (nonatomic) CGFloat scaleToRestoreAfterResize; @property (nonatomic) CGPoint startPoint; @property (nonatomic) CGPoint lastPoint; @property (nonatomic) CGPoint lastPointPop; @property (nonatomic) BOOL shouldPlayVideo; @end @interface MHGalleryImageViewerViewController() @property (nonatomic, strong) UIBarButtonItem *shareBarButton; @property (nonatomic, strong) UIBarButtonItem *leftBarButton; @property (nonatomic, strong) UIBarButtonItem *rightBarButton; @property (nonatomic, strong) UIBarButtonItem *playStopBarButton; @end @implementation MHGalleryImageViewerViewController - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; self.navigationController.delegate = self; } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; [self setNeedsStatusBarAppearanceUpdate]; [UIApplication.sharedApplication setStatusBarStyle:self.galleryViewController.preferredStatusBarStyleMH animated:YES]; if (![self.titleViewBackground isDescendantOfView:self.view]) { [self.view addSubview:self.titleViewBackground]; } if (![self.titleView isDescendantOfView:self.view]) { [self.view addSubview:self.titleView]; } if (![self.descriptionViewBackground isDescendantOfView:self.view]) { [self.view addSubview:self.descriptionViewBackground]; } if (![self.descriptionView isDescendantOfView:self.view]) { [self.view addSubview:self.descriptionView]; } if (![self.toolbar isDescendantOfView:self.view]) { [self.view addSubview:self.toolbar]; } [self.pageViewController.view.subviews.firstObject setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; } - (UIStatusBarStyle)preferredStatusBarStyle{ return self.galleryViewController.preferredStatusBarStyleMH; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; if (self.navigationController.delegate == self) { self.navigationController.delegate = nil; } } -(void)donePressed{ MHImageViewController *imageViewer = self.pageViewController.viewControllers.firstObject; if (imageViewer.moviePlayer) { [imageViewer removeAllMoviePlayerViewsAndNotifications]; } MHTransitionDismissMHGallery *dismissTransiton = [MHTransitionDismissMHGallery new]; dismissTransiton.orientationTransformBeforeDismiss = [(NSNumber *)[self.navigationController.view valueForKeyPath:@"layer.transform.rotation.z"] floatValue]; dismissTransiton.finishButtonAction = YES; imageViewer.interactiveTransition = dismissTransiton; MHGalleryController *galleryViewController = [self galleryViewController]; if (galleryViewController.finishedCallback) { galleryViewController.finishedCallback(self.pageIndex,imageViewer.imageView.image,dismissTransiton,self.viewModeForBarStyle); } } -(MHGalleryViewMode)viewModeForBarStyle{ if (self.isHiddingToolBarAndNavigationBar) { return MHGalleryViewModeImageViewerNavigationBarHidden; } return MHGalleryViewModeImageViewerNavigationBarShown; } -(void)viewDidLoad{ [super viewDidLoad]; self.UICustomization = self.galleryViewController.UICustomization; self.transitionCustomization = self.galleryViewController.transitionCustomization; if (!self.UICustomization.showOverView) { self.navigationItem.hidesBackButton = YES; }else{ if (self.galleryViewController.UICustomization.backButtonState == MHBackButtonStateWithoutBackArrow) { UIBarButtonItem *backBarButton = [UIBarButtonItem.alloc initWithImage:MHTemplateImage(@"ic_square") style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonAction)]; self.navigationItem.hidesBackButton = YES; self.navigationItem.leftBarButtonItem = backBarButton; } } UIBarButtonItem *doneBarButton = [UIBarButtonItem.alloc initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donePressed)]; self.navigationItem.rightBarButtonItem = doneBarButton; self.view.backgroundColor = [self.UICustomization MHGalleryBackgroundColorForViewMode:MHGalleryViewModeImageViewerNavigationBarShown]; self.pageViewController = [UIPageViewController.alloc initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:@{ UIPageViewControllerOptionInterPageSpacingKey : @30.f }]; self.pageViewController.delegate = self; self.pageViewController.dataSource = self; self.pageViewController.automaticallyAdjustsScrollViewInsets =NO; MHGalleryItem *item = [self itemForIndex:self.pageIndex]; MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:item viewController:self]; imageViewController.pageIndex = self.pageIndex; [self.pageViewController setViewControllers:@[imageViewController] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil]; [self addChildViewController:self.pageViewController]; [self.pageViewController didMoveToParentViewController:self]; [self.view addSubview:self.pageViewController.view]; self.toolbar = [UIToolbar.alloc initWithFrame:CGRectMake(0, self.view.frame.size.height-44, self.view.frame.size.width, 44)]; if(self.currentOrientation == UIInterfaceOrientationLandscapeLeft || self.currentOrientation == UIInterfaceOrientationLandscapeRight){ if (self.view.bounds.size.height > self.view.bounds.size.width) { self.toolbar.frame = CGRectMake(0, self.view.frame.size.width-44, self.view.frame.size.height, 44); } } self.toolbar.tintColor = self.UICustomization.barButtonsTintColor; self.toolbar.tag = 307; self.toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin; self.playStopBarButton = [UIBarButtonItem.alloc initWithImage:MHGalleryImage(@"play") style:UIBarButtonItemStyleBordered target:self action:@selector(playStopButtonPressed)]; self.leftBarButton = [UIBarButtonItem.alloc initWithImage:MHGalleryImage(@"left_arrow") style:UIBarButtonItemStyleBordered target:self action:@selector(leftPressed:)]; self.rightBarButton = [UIBarButtonItem.alloc initWithImage:MHGalleryImage(@"right_arrow") style:UIBarButtonItemStyleBordered target:self action:@selector(rightPressed:)]; self.shareBarButton = [UIBarButtonItem.alloc initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(sharePressed)]; if (self.UICustomization.hideShare) { self.shareBarButton = [UIBarButtonItem.alloc initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil]; self.shareBarButton.width = 30; } [self updateToolBarForItem:item]; self.titleViewBackground = [UIToolbar.alloc initWithFrame:CGRectZero]; self.titleViewBackground.alpha = 0.4; self.titleView = [UITextView.alloc initWithFrame:CGRectZero]; [self configureTextView:self.titleView]; self.titleView.text = item.titleString; self.descriptionViewBackground = [UIToolbar.alloc initWithFrame:CGRectZero]; self.descriptionView = [UITextView.alloc initWithFrame:CGRectZero]; [self configureTextView:self.descriptionView]; self.descriptionView.text = item.descriptionString; self.toolbar.barTintColor = self.UICustomization.barTintColor; self.toolbar.barStyle = self.UICustomization.barStyle; self.titleViewBackground.barTintColor = self.UICustomization.barTintColor; self.titleViewBackground.barStyle = self.UICustomization.barStyle; self.descriptionViewBackground.barTintColor = self.UICustomization.barTintColor; self.descriptionViewBackground.barStyle = self.UICustomization.barStyle; [self updateDescriptionViewSizeAndPosition]; [(UIScrollView*)self.pageViewController.view.subviews[0] setDelegate:self]; [(UIGestureRecognizer*)[[self.pageViewController.view.subviews[0] gestureRecognizers] firstObject] setDelegate:self]; [self updateTitleForIndex:self.pageIndex]; } -(void)configureTextView:(UITextView*)textView { textView.backgroundColor = [UIColor clearColor]; textView.font = [UIFont systemFontOfSize:15]; textView.textColor = [UIColor blackColor]; textView.scrollEnabled = NO; textView.editable = NO; textView.delegate = self; } -(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { if ([self.galleryViewController.galleryDelegate respondsToSelector:@selector(galleryController:shouldHandleURL:)]) { return [self.galleryViewController.galleryDelegate galleryController:self.galleryViewController shouldHandleURL:URL]; } return YES; } -(void)enableOrDisbaleBarbButtons{ self.leftBarButton.enabled = YES; self.rightBarButton.enabled = YES; if (self.pageIndex == 0) { self.leftBarButton.enabled =NO; } if(self.pageIndex == self.numberOfGalleryItems-1){ self.rightBarButton.enabled =NO; } } -(void)backButtonAction{ [self.navigationController popToRootViewControllerAnimated:YES]; } -(UIInterfaceOrientation)currentOrientation{ return UIApplication.sharedApplication.statusBarOrientation; } -(NSInteger)numberOfGalleryItems{ return [self.galleryViewController.dataSource numberOfItemsInGallery:self.galleryViewController]; } -(MHGalleryItem*)itemForIndex:(NSInteger)index{ return [self.galleryViewController.dataSource itemForIndex:index]; } -(MHGalleryController*)galleryViewController{ if ([self.navigationController isKindOfClass:MHGalleryController.class]) { return (MHGalleryController*)self.navigationController; } return nil; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { if ([touch.view isKindOfClass:UIButton.class]) { if (touch.view.tag != 508) { return YES; } } return ([touch.view isKindOfClass:UIControl.class] == NO); } -(void)changeToPlayButton{ self.playStopBarButton.image = MHGalleryImage(@"play"); } -(void)changeToPauseButton{ self.playStopBarButton.image = MHGalleryImage(@"pause"); } -(void)playStopButtonPressed{ for (MHImageViewController *imageViewController in self.pageViewController.viewControllers) { if (imageViewController.pageIndex == self.pageIndex) { if (imageViewController.isPlayingVideo) { [imageViewController stopMovie]; [self changeToPlayButton]; }else{ [imageViewController playButtonPressed]; } } } } -(void)sharePressed{ if (self.UICustomization.showMHShareViewInsteadOfActivityViewController) { MHShareViewController *share = [MHShareViewController new]; share.pageIndex = self.pageIndex; share.galleryItems = self.galleryItems; [self.navigationController pushViewController:share animated:YES]; }else{ MHImageViewController *imageViewController = (MHImageViewController*)self.pageViewController.viewControllers.firstObject; if (imageViewController.imageView.image != nil) { UIActivityViewController *act = [UIActivityViewController.alloc initWithActivityItems:@[imageViewController.imageView.image] applicationActivities:nil]; [self presentViewController:act animated:YES completion:nil]; if ([act respondsToSelector:@selector(popoverPresentationController)]) { act.popoverPresentationController.barButtonItem = self.shareBarButton; } } } } -(void)updateTitleLabelForIndex:(NSInteger)index{ if (index < self.numberOfGalleryItems) { MHGalleryItem *item = [self itemForIndex:index]; self.titleView.text = item.titleString; if (item.attributedString) { self.titleView.attributedText = item.attributedTitle; } [self updateTitleViewSizeAndPosition]; } } -(void)updateDescriptionLabelForIndex:(NSInteger)index{ if (index < self.numberOfGalleryItems) { MHGalleryItem *item = [self itemForIndex:index]; self.descriptionView.text = item.descriptionString; if (item.attributedString) { self.descriptionView.attributedText = item.attributedString; } [self updateDescriptionViewSizeAndPosition]; } } -(void)updateTitleViewSizeAndPosition { //CGSize size = [self.titleView sizeThatFits:CGSizeMake(self.view.frame.size.width-20, 30)]; CGSize size = [self.titleView sizeThatFits:CGSizeMake(self.view.frame.size.width-20, MAXFLOAT)]; MHGalleryItem *item = [self itemForIndex:self.pageIndex]; MHImageViewController *controller = [MHImageViewController imageViewControllerForMHMediaItem:item viewController:self]; CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame); if (controller.moviePlayerToolBarTop) { y += CGRectGetHeight(controller.moviePlayerToolBarTop.frame); } self.titleView.frame = CGRectMake(10, self.view.frame.size.height - 44 - self.descriptionViewBackground.frame.size.height - size.height, self.view.frame.size.width-20, size.height); //self.titleView.frame = CGRectMake(10, y, self.view.frame.size.width-20, size.height); if (self.titleView.text.length >0) { //self.titleViewBackground.frame = CGRectMake(0, y, self.view.frame.size.width, size.height); self.titleViewBackground.frame = CGRectMake(0, self.view.frame.size.height - 44 - self.descriptionViewBackground.frame.size.height - size.height, self.view.frame.size.width, size.height); self.titleViewBackground.hidden = NO; } else { self.titleViewBackground.hidden = YES; } } -(void)updateDescriptionViewSizeAndPosition { CGSize size = [self.descriptionView sizeThatFits:CGSizeMake(self.view.frame.size.width-20, MAXFLOAT)]; CGFloat y = CGRectGetMinY(self.toolbar.frame) - size.height; self.descriptionView.frame = CGRectMake(10, y, self.view.frame.size.width-20, size.height); if (self.descriptionView.text.length >0) { self.descriptionViewBackground.frame = CGRectMake(0, y, self.view.frame.size.width, size.height); self.descriptionViewBackground.hidden = NO; } else { self.descriptionViewBackground.hidden = YES; } } -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ self.userScrolls = NO; [self updateTitleAndDescriptionForScrollView:scrollView]; } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ self.userScrolls = YES; } -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ [self updateTitleAndDescriptionForScrollView:scrollView]; } -(void)updateTitleAndDescriptionForScrollView:(UIScrollView*)scrollView{ NSInteger pageIndex = self.pageIndex; if (scrollView.contentOffset.x > (self.view.frame.size.width+self.view.frame.size.width/2)) { pageIndex++; } if (scrollView.contentOffset.x < self.view.frame.size.width/2) { pageIndex--; } [self updateDescriptionLabelForIndex:pageIndex]; [self updateTitleLabelForIndex:pageIndex]; [self updateTitleForIndex:pageIndex]; } -(void)updateTitleForIndex:(NSInteger)pageIndex{ NSString *localizedString = MHGalleryLocalizedString(@"imagedetail.title.current"); self.navigationItem.title = [NSString stringWithFormat:localizedString,@(pageIndex+1),@(self.numberOfGalleryItems)]; } -(void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{ self.pageIndex = [pageViewController.viewControllers.firstObject pageIndex]; [self showCurrentIndex:self.pageIndex]; if (finished) { for (MHImageViewController *imageViewController in previousViewControllers) { [self removeVideoPlayerForVC:imageViewController]; } } if (completed) { [self updateToolBarForItem:[self itemForIndex:self.pageIndex]]; } } -(void)removeVideoPlayerForVC:(MHImageViewController*)vc{ if (vc.pageIndex != self.pageIndex) { if (vc.moviePlayer) { if (vc.item.galleryType == MHGalleryTypeVideo) { if (vc.isPlayingVideo) { [vc stopMovie]; } vc.currentTimeMovie =0; } } } } -(void)updateToolBarForItem:(MHGalleryItem*)item{ UIBarButtonItem *flex = [UIBarButtonItem.alloc initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; UIBarButtonItem *fixed = [UIBarButtonItem.alloc initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil]; fixed.width = 30; [self enableOrDisbaleBarbButtons]; UIBarButtonItem *customItem = self.UICustomization.customBarButtonItem; if (!customItem) { customItem = fixed; } if (item.galleryType == MHGalleryTypeVideo) { MHImageViewController *imageViewController = self.pageViewController.viewControllers.firstObject; if (imageViewController.isPlayingVideo) { [self changeToPauseButton]; }else{ [self changeToPlayButton]; } self.toolbar.items = @[self.shareBarButton,flex,self.leftBarButton,flex,self.playStopBarButton,flex,self.rightBarButton,flex,customItem]; }else{ self.toolbar.items =@[self.shareBarButton,flex,self.leftBarButton,flex,self.rightBarButton,flex,customItem]; } } - (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController { if ([animationController isKindOfClass:MHTransitionShowOverView.class]) { MHImageViewController *imageViewController = self.pageViewController.viewControllers.firstObject; return imageViewController.interactiveOverView; }else { return nil; } } - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC { MHImageViewController *theCurrentViewController = self.pageViewController.viewControllers.firstObject; if (theCurrentViewController.moviePlayer) { [theCurrentViewController removeAllMoviePlayerViewsAndNotifications]; } if ([toVC isKindOfClass:MHShareViewController.class]) { MHTransitionShowShareView *present = MHTransitionShowShareView.new; present.present = YES; return present; } if ([toVC isKindOfClass:MHOverviewController.class]) { return MHTransitionShowOverView.new; } return nil; } -(void)leftPressed:(id)sender{ self.rightBarButton.enabled = YES; MHImageViewController *theCurrentViewController = self.pageViewController.viewControllers.firstObject; if (theCurrentViewController.moviePlayer) { [theCurrentViewController removeAllMoviePlayerViewsAndNotifications]; } NSUInteger indexPage = theCurrentViewController.pageIndex; MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:[self itemForIndex:indexPage-1] viewController:self]; imageViewController.pageIndex = indexPage-1; if (indexPage-1 == 0) { self.leftBarButton.enabled = NO; } if (!imageViewController) { return; } __weak typeof(self) weakSelf = self; [self.pageViewController setViewControllers:@[imageViewController] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:^(BOOL finished) { weakSelf.pageIndex = imageViewController.pageIndex; [weakSelf updateToolBarForItem:[weakSelf itemForIndex:weakSelf.pageIndex]]; [weakSelf showCurrentIndex:weakSelf.pageIndex]; }]; } -(void)rightPressed:(id)sender{ self.leftBarButton.enabled =YES; MHImageViewController *theCurrentViewController = self.pageViewController.viewControllers.firstObject; if (theCurrentViewController.moviePlayer) { [theCurrentViewController removeAllMoviePlayerViewsAndNotifications]; } NSUInteger indexPage = theCurrentViewController.pageIndex; MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:[self itemForIndex:indexPage+1] viewController:self]; imageViewController.pageIndex = indexPage+1; if (indexPage+1 == self.numberOfGalleryItems-1) { self.rightBarButton.enabled = NO; } if (!imageViewController) { return; } __weak typeof(self) weakSelf = self; [self.pageViewController setViewControllers:@[imageViewController] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished) { weakSelf.pageIndex = imageViewController.pageIndex; [weakSelf updateToolBarForItem:[weakSelf itemForIndex:weakSelf.pageIndex]]; [weakSelf showCurrentIndex:weakSelf.pageIndex]; }]; } -(void)showCurrentIndex:(NSInteger)currentIndex{ if ([self.galleryViewController.galleryDelegate respondsToSelector:@selector(galleryController:didShowIndex:)]) { [self.galleryViewController.galleryDelegate galleryController:self.galleryViewController didShowIndex:currentIndex]; } } - (UIViewController *)pageViewController:(UIPageViewController *)pvc viewControllerBeforeViewController:(MHImageViewController *)vc{ NSInteger indexPage = vc.pageIndex; if (self.numberOfGalleryItems !=1 && self.numberOfGalleryItems-1 != indexPage) { self.leftBarButton.enabled =YES; self.rightBarButton.enabled =YES; } [self removeVideoPlayerForVC:vc]; if (indexPage ==0) { self.leftBarButton.enabled = NO; MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:nil viewController:self]; imageViewController.pageIndex = 0; return imageViewController; } MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:[self itemForIndex:indexPage-1] viewController:self]; imageViewController.pageIndex = indexPage-1; return imageViewController; } -(MHImageViewController*)imageViewControllerWithItem:(MHGalleryItem*)item pageIndex:(NSInteger)pageIndex{ MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:[self itemForIndex:pageIndex] viewController:self]; imageViewController.pageIndex = pageIndex; return imageViewController; } - (UIViewController *)pageViewController:(UIPageViewController *)pvc viewControllerAfterViewController:(MHImageViewController *)vc{ NSInteger indexPage = vc.pageIndex; if (self.numberOfGalleryItems !=1 && indexPage !=0) { self.leftBarButton.enabled = YES; self.rightBarButton.enabled = YES; } [self removeVideoPlayerForVC:vc]; if (indexPage ==self.numberOfGalleryItems-1) { self.rightBarButton.enabled = NO; MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:nil viewController:self]; imageViewController.pageIndex = self.numberOfGalleryItems-1; return imageViewController; } MHImageViewController *imageViewController =[MHImageViewController imageViewControllerForMHMediaItem:[self itemForIndex:indexPage+1] viewController:self]; imageViewController.pageIndex = indexPage+1; return imageViewController; } -(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{ self.toolbar.frame = CGRectMake(0, self.view.frame.size.height-44, self.view.frame.size.width, 44); self.pageViewController.view.bounds = self.view.bounds; [self.pageViewController.view.subviews.firstObject setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) ]; } @end @implementation MHImageViewController +(MHImageViewController *)imageViewControllerForMHMediaItem:(MHGalleryItem*)item viewController:(MHGalleryImageViewerViewController*)viewController{ if (item) { return [self.alloc initWithMHMediaItem:item viewController:viewController]; } return nil; } -(CGFloat)checkProgressValue:(CGFloat)progress{ CGFloat progressChecked =progress; if (progressChecked <0) { progressChecked = -progressChecked; } if (progressChecked >=1) { progressChecked =0.99; } return progressChecked; } -(void)userDidPinch:(UIPinchGestureRecognizer*)recognizer{ if (recognizer.state == UIGestureRecognizerStateBegan) { if (recognizer.scale <1) { self.imageView.frame = self.scrollView.frame; self.lastPointPop = [recognizer locationInView:self.view]; self.interactiveOverView = [MHTransitionShowOverView new]; [self.navigationController popViewControllerAnimated:YES]; }else{ recognizer.cancelsTouchesInView = YES; } }else if (recognizer.state == UIGestureRecognizerStateChanged) { if (recognizer.numberOfTouches <2) { recognizer.enabled =NO; recognizer.enabled =YES; } CGPoint point = [recognizer locationInView:self.view]; self.interactiveOverView.scale = recognizer.scale; self.interactiveOverView.changedPoint = CGPointMake(self.lastPointPop.x - point.x, self.lastPointPop.y - point.y) ; [self.interactiveOverView updateInteractiveTransition:1-recognizer.scale]; self.lastPointPop = point; }else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) { if (recognizer.scale < 0.65) { [self.interactiveOverView finishInteractiveTransition]; }else{ [self.interactiveOverView cancelInteractiveTransition]; } self.interactiveOverView = nil; } } -(void)userDidPan:(UIPanGestureRecognizer*)recognizer{ BOOL userScrolls = self.viewController.userScrolls; if (self.viewController.transitionCustomization.dismissWithScrollGestureOnFirstAndLastImage) { if (!self.interactiveTransition) { if (self.viewController.numberOfGalleryItems ==1) { userScrolls = NO; self.viewController.userScrolls = NO; }else{ if (self.pageIndex ==0) { if ([recognizer translationInView:self.view].x >=0) { userScrolls =NO; self.viewController.userScrolls = NO; }else{ recognizer.cancelsTouchesInView = YES; recognizer.enabled =NO; recognizer.enabled =YES; } } if ((self.pageIndex == self.viewController.numberOfGalleryItems-1)) { if ([recognizer translationInView:self.view].x <=0) { userScrolls =NO; self.viewController.userScrolls = NO; }else{ recognizer.cancelsTouchesInView = YES; recognizer.enabled =NO; recognizer.enabled =YES; } } } }else{ userScrolls = NO; } } if (!userScrolls || recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) { CGFloat progressY = (self.startPoint.y - [recognizer translationInView:self.view].y)/(self.view.frame.size.height/2); progressY = [self checkProgressValue:progressY]; CGFloat progressX = (self.startPoint.x - [recognizer translationInView:self.view].x)/(self.view.frame.size.width/2); progressX = [self checkProgressValue:progressX]; if (recognizer.state == UIGestureRecognizerStateBegan) { self.startPoint = [recognizer translationInView:self.view]; }else if (recognizer.state == UIGestureRecognizerStateChanged) { if (!self.interactiveTransition ) { self.startPoint = [recognizer translationInView:self.view]; self.lastPoint = [recognizer translationInView:self.view]; self.interactiveTransition = [MHTransitionDismissMHGallery new]; if(UIApplication.sharedApplication.statusBarOrientation == UIInterfaceOrientationLandscapeLeft){ self.interactiveTransition.orientationTransformBeforeDismiss = -M_PI/2; }else if(UIApplication.sharedApplication.statusBarOrientation == UIInterfaceOrientationLandscapeRight){ self.interactiveTransition.orientationTransformBeforeDismiss = M_PI/2; }else{ self.interactiveTransition.orientationTransformBeforeDismiss = 0; } self.interactiveTransition.interactive = YES; self.interactiveTransition.moviePlayer = self.moviePlayer; MHGalleryController *galleryViewController = [self.viewController galleryViewController]; if (galleryViewController.finishedCallback) { galleryViewController.finishedCallback(self.pageIndex,self.imageView.image,self.interactiveTransition,self.viewController.viewModeForBarStyle); } }else{ CGPoint currentPoint = [recognizer translationInView:self.view]; if (self.viewController.transitionCustomization.fixXValueForDismiss) { self.interactiveTransition.changedPoint = CGPointMake(self.startPoint.x, self.lastPoint.y-currentPoint.y); }else{ self.interactiveTransition.changedPoint = CGPointMake(self.lastPoint.x-currentPoint.x, self.lastPoint.y-currentPoint.y); } progressY = [self checkProgressValue:progressY]; progressX = [self checkProgressValue:progressX]; if (!self.viewController.transitionCustomization.fixXValueForDismiss) { if (progressX> progressY) { progressY = progressX; } } [self.interactiveTransition updateInteractiveTransition:progressY]; self.lastPoint = [recognizer translationInView:self.view]; } }else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) { if (self.interactiveTransition) { CGFloat velocityY = [recognizer velocityInView:self.view].y; if (velocityY <0) { velocityY = -velocityY; } if (!self.viewController.transitionCustomization.fixXValueForDismiss) { if (progressX> progressY) { progressY = progressX; } } if (progressY > 0.35 || velocityY >700) { MHStatusBar().alpha = MHShouldShowStatusBar() ? 1 : 0; [self.interactiveTransition finishInteractiveTransition]; }else { [self setNeedsStatusBarAppearanceUpdate]; [self.interactiveTransition cancelInteractiveTransition]; } self.interactiveTransition = nil; } } } } - (id)initWithMHMediaItem:(MHGalleryItem*)mediaItem viewController:(MHGalleryImageViewerViewController*)viewController{ self = [super initWithNibName:nil bundle:nil]; if (self) { self.changeIsLocked = YES; __weak typeof(self) weakSelf = self; self.viewController = viewController; self.view.backgroundColor = [UIColor blackColor]; self.shouldPlayVideo = NO; self.item = mediaItem; self.scrollView = [UIScrollView.alloc initWithFrame:self.view.bounds]; self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin; self.scrollView.delegate = self; self.scrollView.tag = 406; self.scrollView.maximumZoomScale =3; self.scrollView.minimumZoomScale= 1; self.scrollView.userInteractionEnabled = YES; [self.view addSubview:self.scrollView]; self.imageView = [UIImageView.alloc initWithFrame:self.view.bounds]; self.imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin; self.imageView.contentMode = UIViewContentModeScaleAspectFit; self.imageView.clipsToBounds = YES; self.imageView.tag = 506; [self.scrollView addSubview:self.imageView]; self.pinch = [MHPinchGestureRecognizer.alloc initWithTarget:self action:@selector(userDidPinch:)]; self.pinch.delegate = self; self.pan = [UIPanGestureRecognizer.alloc initWithTarget:self action:@selector(userDidPan:)]; UITapGestureRecognizer *doubleTap = [UITapGestureRecognizer.alloc initWithTarget:self action:@selector(handleDoubleTap:)]; doubleTap.numberOfTapsRequired =2; UITapGestureRecognizer *imageTap =[UITapGestureRecognizer.alloc initWithTarget:self action:@selector(handelImageTap:)]; imageTap.numberOfTapsRequired =1; [self.imageView addGestureRecognizer:doubleTap]; self.pan.delegate = self; if(self.viewController.transitionCustomization.interactiveDismiss){ [self.imageView addGestureRecognizer:self.pan]; self.pan.maximumNumberOfTouches =1; self.pan.delaysTouchesBegan = YES; } if (self.viewController.UICustomization.showOverView) { [self.scrollView addGestureRecognizer:self.pinch]; } [self.view addGestureRecognizer:imageTap]; self.act = [UIActivityIndicatorView.alloc initWithFrame:self.view.bounds]; [self.act startAnimating]; self.act.hidesWhenStopped =YES; self.act.tag =507; self.act.autoresizingMask =UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth; [self.scrollView addSubview:self.act]; if (self.item.galleryType != MHGalleryTypeImage) { [self addPlayButtonToView]; self.moviePlayerToolBarTop = [UIToolbar.alloc initWithFrame:CGRectMake(0, self.navigationController.navigationBar.bounds.size.height+([UIApplication sharedApplication].statusBarHidden?0:20), self.view.frame.size.width, 44)]; self.moviePlayerToolBarTop.autoresizingMask =UIViewAutoresizingFlexibleWidth; self.moviePlayerToolBarTop.alpha =0; self.moviePlayerToolBarTop.barTintColor = self.viewController.UICustomization.barTintColor; [self.view addSubview:self.moviePlayerToolBarTop]; self.currentTimeMovie =0; self.wholeTimeMovie =0; self.videoProgressView = [UIProgressView.alloc initWithFrame:CGRectMake(57, 21, self.view.frame.size.width-114, 3)]; self.videoProgressView.layer.borderWidth =0.5; self.videoProgressView.layer.borderColor =[UIColor colorWithWhite:0 alpha:0.3].CGColor; self.videoProgressView.trackTintColor =[UIColor clearColor]; self.videoProgressView.progressTintColor = [self.viewController.UICustomization.videoProgressTintColor colorWithAlphaComponent:0.3f]; self.videoProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth; [self.moviePlayerToolBarTop addSubview:self.videoProgressView]; self.slider = [UISlider.alloc initWithFrame:CGRectMake(55, 0, self.view.frame.size.width-110, 44)]; self.slider.maximumValue =10; self.slider.minimumValue =0; self.slider.minimumTrackTintColor = self.viewController.UICustomization.videoProgressTintColor; self.slider.maximumTrackTintColor = [self.viewController.UICustomization.videoProgressTintColor colorWithAlphaComponent:0.2f]; [self.slider setThumbImage:MHGalleryImage(@"sliderPoint") forState:UIControlStateNormal]; [self.slider addTarget:self action:@selector(sliderDidChange:) forControlEvents:UIControlEventValueChanged]; [self.slider addTarget:self action:@selector(sliderDidDragExit:) forControlEvents:UIControlEventTouchUpInside]; self.slider.autoresizingMask =UIViewAutoresizingFlexibleWidth; [self.moviePlayerToolBarTop addSubview:self.slider]; self.leftSliderLabel = [UILabel.alloc initWithFrame:CGRectMake(8, 0, 40, 43)]; self.leftSliderLabel.font =[UIFont systemFontOfSize:14]; self.leftSliderLabel.text = @"00:00"; self.leftSliderLabel.textColor = self.viewController.UICustomization.videoProgressTintColor; [self.moviePlayerToolBarTop addSubview:self.leftSliderLabel]; self.rightSliderLabel = [UILabel.alloc initWithFrame:CGRectZero]; self.rightSliderLabel.frame = CGRectMake(self.viewController.view.frame.size.width-50, 0, 50, 43); self.rightSliderLabel.font = [UIFont systemFontOfSize:14]; self.rightSliderLabel.text = @"-00:00"; self.rightSliderLabel.textColor = self.viewController.UICustomization.videoProgressTintColor; self.rightSliderLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin; [self.moviePlayerToolBarTop addSubview:self.rightSliderLabel]; self.scrollView.maximumZoomScale = 1; self.scrollView.minimumZoomScale =1; } self.imageView.userInteractionEnabled = YES; [imageTap requireGestureRecognizerToFail: doubleTap]; if (self.item.galleryType == MHGalleryTypeImage) { [self.imageView setImageForMHGalleryItem:self.item imageType:MHImageTypeFull successBlock:^(UIImage *image, NSError *error) { if (!image) { weakSelf.scrollView.maximumZoomScale =1; [weakSelf changeToErrorImage]; } [weakSelf.act stopAnimating]; }]; }else{ [MHGallerySharedManager.sharedManager startDownloadingThumbImage:self.item.URLString successBlock:^(UIImage *image,NSUInteger videoDuration,NSError *error) { if (!error) { [weakSelf handleGeneratedThumb:image videoDuration:videoDuration urlString:self.item.URLString]; }else{ [weakSelf changeToErrorImage]; } [weakSelf.act stopAnimating]; }]; } } return self; } -(void)setImageForImageViewWithImage:(UIImage*)image error:(NSError*)error{ if (!image) { self.scrollView.maximumZoomScale =1; [self changeToErrorImage]; }else{ self.imageView.image = image; } [self.act stopAnimating]; } -(void)changeToErrorImage{ self.imageView.image = MHGalleryImage(@"error"); } -(void)changePlayButtonToUnPlay{ [self.playButton setImage:MHGalleryImage(@"unplay") forState:UIControlStateNormal]; } -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; __weak typeof(self) weakSelf = self; if (self.item.galleryType == MHGalleryTypeVideo) { if (self.moviePlayer) { [weakSelf autoPlayVideo]; return; } [[MHGallerySharedManager sharedManager] getURLForMediaPlayer:self.item.URLString successBlock:^(NSURL *URL, NSError *error) { if (error || URL == nil) { [weakSelf changePlayButtonToUnPlay]; }else{ [weakSelf addMoviePlayerToViewWithURL:URL]; [weakSelf autoPlayVideo]; } }]; } } -(void)autoPlayVideo{ if (self.viewController.galleryViewController.autoplayVideos){ [self playButtonPressed]; } } -(void)handleGeneratedThumb:(UIImage*)image videoDuration:(NSInteger)videoDuration urlString:(NSString*)urlString{ self.wholeTimeMovie = videoDuration; self.rightSliderLabel.text = [MHGallerySharedManager stringForMinutesAndSeconds:videoDuration addMinus:YES]; self.slider.maximumValue = videoDuration; [self.view viewWithTag:508].hidden =NO; self.imageView.image = image; self.playButton.frame = CGRectMake(self.viewController.view.frame.size.width/2-36, self.viewController.view.frame.size.height/2-36, 72, 72); self.playButton.hidden = NO; [self.act stopAnimating]; } -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ if (self.interactiveOverView) { if ([gestureRecognizer isKindOfClass:MHPinchGestureRecognizer.class]) { return YES; } return NO; } if (self.interactiveTransition) { if ([gestureRecognizer isEqual:self.pan]) { return YES; } return NO; } if (self.viewController.transitionCustomization.dismissWithScrollGestureOnFirstAndLastImage) { if ((self.pageIndex ==0 || self.pageIndex == self.viewController.numberOfGalleryItems -1)) { if ([gestureRecognizer isKindOfClass:UIPanGestureRecognizer.class]|| [otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewDelayedTouchesBeganGestureRecognizer")] ) { return YES; } } } return NO; } -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{ if (self.interactiveOverView) { if ([gestureRecognizer isKindOfClass:MHPinchGestureRecognizer.class]) { return YES; }else{ return NO; } }else{ if ([gestureRecognizer isKindOfClass:MHPinchGestureRecognizer.class]) { if ([gestureRecognizer isKindOfClass:MHPinchGestureRecognizer.class] && self.scrollView.zoomScale ==1) { return YES; }else{ return NO; } } } if (self.viewController.isUserScrolling) { if ([gestureRecognizer isEqual:self.pan]) { return NO; } } if ([gestureRecognizer isEqual:self.pan] && self.scrollView.zoomScale !=1) { return NO; } if (self.interactiveTransition) { if ([gestureRecognizer isEqual:self.pan]) { return YES; } return NO; } if (self.viewController.transitionCustomization.dismissWithScrollGestureOnFirstAndLastImage) { if ((self.pageIndex ==0 || self.pageIndex == self.viewController.numberOfGalleryItems -1) && [gestureRecognizer isKindOfClass:UIPanGestureRecognizer.class]) { return YES; } } return YES; } -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ if (self.interactiveOverView || self.interactiveTransition) { return NO; } if ([otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewDelayedTouchesBeganGestureRecognizer")]|| [otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewPanGestureRecognizer")] ) { return YES; } if ([gestureRecognizer isKindOfClass:MHPinchGestureRecognizer.class]) { return YES; } if (self.viewController.transitionCustomization.dismissWithScrollGestureOnFirstAndLastImage) { if ((self.pageIndex ==0 || self.pageIndex == self.viewController.numberOfGalleryItems -1) && [gestureRecognizer isKindOfClass:UIPanGestureRecognizer.class]) { return YES; } } return NO; } -(void)sliderDidDragExit:(UISlider*)slider{ if (self.playingVideo) { [self.moviePlayer play]; } } -(void)sliderDidChange:(UISlider*)slider{ if (self.moviePlayer) { [self.moviePlayer pause]; self.moviePlayer.currentPlaybackTime = slider.value; self.currentTimeMovie = slider.value; [self updateTimerLabels]; } } -(void)stopMovie{ self.shouldPlayVideo = NO; [self stopTimer]; self.playingVideo = NO; [self.moviePlayer pause]; [self.view bringSubviewToFront:self.playButton]; [self.view bringSubviewToFront:self.moviePlayerToolBarTop]; [self.viewController changeToPlayButton]; } -(void)changeToPlayable{ self.videoWasPlayable = YES; if(!self.viewController.isHiddingToolBarAndNavigationBar){ self.moviePlayerToolBarTop.alpha =1; } self.moviePlayer.view.hidden =NO; [self.view bringSubviewToFront:self.moviePlayer.view]; self.moviewPlayerButtonBehinde = [UIButton.alloc initWithFrame:self.view.bounds]; [self.moviewPlayerButtonBehinde addTarget:self action:@selector(handelImageTap:) forControlEvents:UIControlEventTouchUpInside]; self.moviewPlayerButtonBehinde.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; [self.view bringSubviewToFront:self.scrollView]; [self.view addSubview:self.moviewPlayerButtonBehinde]; [self.view bringSubviewToFront:self.moviePlayerToolBarTop]; [self.view bringSubviewToFront:self.playButton]; if(self.viewController.transitionCustomization.interactiveDismiss){ [self.moviewPlayerButtonBehinde addGestureRecognizer:self.pan]; } if(self.playingVideo){ [self bringMoviePlayerToFront]; } if (self.shouldPlayVideo) { self.shouldPlayVideo = NO; if (self.pageIndex == self.viewController.pageIndex) { [self playButtonPressed]; } } } - (void)loadStateDidChange:(NSNotification *)notification{ MPMoviePlayerController *player = notification.object; MPMovieLoadState loadState = player.loadState; if (loadState & MPMovieLoadStatePlayable){ if (!self.videoWasPlayable) { [self performSelectorOnMainThread:@selector(changeToPlayable) withObject:nil waitUntilDone:YES]; } } if (loadState & MPMovieLoadStatePlaythroughOK){ self.videoDownloaded = YES; } if (loadState & MPMovieLoadStateStalled){ [self performSelectorOnMainThread:@selector(stopMovie) withObject:nil waitUntilDone:YES]; } } -(void)updateTimerLabels{ if (self.currentTimeMovie <=0) { self.leftSliderLabel.text =@"00:00"; self.rightSliderLabel.text = [MHGallerySharedManager stringForMinutesAndSeconds:self.wholeTimeMovie addMinus:YES]; }else{ self.leftSliderLabel.text = [MHGallerySharedManager stringForMinutesAndSeconds:self.currentTimeMovie addMinus:NO]; self.rightSliderLabel.text = [MHGallerySharedManager stringForMinutesAndSeconds:self.wholeTimeMovie-self.currentTimeMovie addMinus:YES]; } } -(void)changeProgressBehinde:(NSTimer*)timer{ if (self.moviePlayer.playableDuration !=0) { [self.videoProgressView setProgress:self.moviePlayer.playableDuration/self.moviePlayer.duration]; if ((self.moviePlayer.playableDuration == self.moviePlayer.duration)&& (self.moviePlayer.duration !=0)) { [self stopMovieDownloadTimer]; } } } -(void)movieTimerChanged:(NSTimer*)timer{ self.currentTimeMovie = self.moviePlayer.currentPlaybackTime; if (!self.slider.isTracking) { [self.slider setValue:self.moviePlayer.currentPlaybackTime animated:NO]; } [self updateTimerLabels]; } -(void)addPlayButtonToView{ if (self.playButton) { [self.playButton removeFromSuperview]; } self.playButton = [UIButton.alloc initWithFrame:self.viewController.view.bounds]; self.playButton.frame = CGRectMake(self.viewController.view.frame.size.width/2-36, self.viewController.view.frame.size.height/2-36, 72, 72); [self.playButton setImage:MHGalleryImage(@"playButton") forState:UIControlStateNormal]; self.playButton.tag =508; self.playButton.hidden =YES; [self.playButton addTarget:self action:@selector(playButtonPressed) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.playButton]; } -(void)stopMovieDownloadTimer{ [self.movieDownloadedTimer invalidate]; self.movieDownloadedTimer = nil; } -(void)removeAllMoviePlayerViewsAndNotifications{ self.videoDownloaded = NO; self.currentTimeMovie =0; [self stopTimer]; [self stopMovieDownloadTimer]; self.playingVideo =NO; [NSNotificationCenter.defaultCenter removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:self.moviePlayer]; [NSNotificationCenter.defaultCenter removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer]; [NSNotificationCenter.defaultCenter removeObserver:self name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer]; [self.moviePlayer stop]; [self.moviePlayer.view removeFromSuperview]; self.moviePlayer = nil; [self addPlayButtonToView]; self.playButton.hidden =NO; self.playButton.frame = CGRectMake(self.viewController.view.frame.size.width/2-36, self.viewController.view.frame.size.height/2-36, 72, 72); [self.moviewPlayerButtonBehinde removeFromSuperview]; [self.viewController changeToPlayButton]; [self updateTimerLabels]; [self.slider setValue:0 animated:NO]; } -(void)moviePlayBackDidFinish:(NSNotification *)notification{ self.playingVideo = NO; [self.viewController changeToPlayButton]; self.playButton.hidden =NO; [self.view bringSubviewToFront:self.playButton]; [self stopTimer]; self.moviePlayer.currentPlaybackTime =0; [self movieTimerChanged:nil]; [self updateTimerLabels]; } -(void)stopTimer{ [self.movieTimer invalidate]; self.movieTimer = nil; } -(void)addMoviePlayerToViewWithURL:(NSURL*)URL{ self.videoWasPlayable = NO; self.moviePlayer = MPMoviePlayerController.new; self.moviePlayer.backgroundView.backgroundColor = [self.viewController.UICustomization MHGalleryBackgroundColorForViewMode:[self currentViewMode]]; self.moviePlayer.view.backgroundColor = [self.viewController.UICustomization MHGalleryBackgroundColorForViewMode:[self currentViewMode]]; self.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming; self.moviePlayer.controlStyle = MPMovieControlStyleNone; self.moviePlayer.contentURL = URL; [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(loadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:self.moviePlayer]; [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer]; self.moviePlayer.shouldAutoplay = NO; self.moviePlayer.view.frame = self.view.bounds; self.moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; self.moviePlayer.view.hidden = YES; [self.view addSubview:self.moviePlayer.view]; self.playingVideo =NO; self.movieDownloadedTimer = [NSTimer timerWithTimeInterval:0.06f target:self selector:@selector(changeProgressBehinde:) userInfo:nil repeats:YES]; [NSRunLoop.currentRunLoop addTimer:self.movieDownloadedTimer forMode:NSRunLoopCommonModes]; [self changeToPlayable]; } -(void)bringMoviePlayerToFront{ [self.view bringSubviewToFront:self.moviePlayer.view]; [self.view bringSubviewToFront:self.moviewPlayerButtonBehinde]; [self.view bringSubviewToFront:self.moviePlayerToolBarTop]; } -(void)playButtonPressed{ if (!self.playingVideo) { [self bringMoviePlayerToFront]; self.playButton.hidden = YES; self.playingVideo =YES; if (self.moviePlayer) { [self.moviePlayer play]; [self.viewController changeToPauseButton]; }else{ UIActivityIndicatorView *act = [UIActivityIndicatorView.alloc initWithFrame:self.view.bounds]; act.tag = 304; [self.view addSubview:act]; [act startAnimating]; self.shouldPlayVideo = YES; } if (!self.movieTimer) { self.movieTimer = [NSTimer timerWithTimeInterval:0.01f target:self selector:@selector(movieTimerChanged:) userInfo:nil repeats:YES]; [NSRunLoop.currentRunLoop addTimer:self.movieTimer forMode:NSRunLoopCommonModes]; } }else{ [self stopMovie]; } } -(MHGalleryViewMode)currentViewMode{ if (self.viewController.isHiddingToolBarAndNavigationBar) { return MHGalleryViewModeImageViewerNavigationBarHidden; } return MHGalleryViewModeImageViewerNavigationBarShown; } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; self.moviePlayer.backgroundView.backgroundColor = [self.viewController.UICustomization MHGalleryBackgroundColorForViewMode:[self currentViewMode]]; self.scrollView.backgroundColor = [self.viewController.UICustomization MHGalleryBackgroundColorForViewMode:[self currentViewMode]]; if (self.viewController.isHiddingToolBarAndNavigationBar) { self.act.color = [UIColor whiteColor]; self.moviePlayerToolBarTop.alpha =0; }else{ if (self.moviePlayerToolBarTop) { if (self.item.galleryType == MHGalleryTypeVideo) { if (self.videoWasPlayable && self.wholeTimeMovie >0) { self.moviePlayerToolBarTop.alpha =1; } } } self.act.color = [UIColor blackColor]; } if (self.item.galleryType == MHGalleryTypeVideo) { if (self.moviePlayer) { [self.slider setValue:self.moviePlayer.currentPlaybackTime animated:NO]; } if (self.imageView.image) { self.playButton.frame = CGRectMake(self.viewController.view.frame.size.width/2-36, self.viewController.view.frame.size.height/2-36, 72, 72); } self.leftSliderLabel.frame = CGRectMake(8, 0, 40, 43); self.rightSliderLabel.frame =CGRectMake(self.viewController.view.bounds.size.width-50, 0, 50, 43); if(UIApplication.sharedApplication.statusBarOrientation != UIInterfaceOrientationPortrait){ if (self.view.bounds.size.width < self.view.bounds.size.height) { self.rightSliderLabel.frame =CGRectMake(self.view.bounds.size.height-50, 0, 50, 43); if (self.imageView.image) { self.playButton.frame = CGRectMake(self.view.bounds.size.height/2-36, self.view.bounds.size.width/2-36, 72, 72); } } } self.moviePlayerToolBarTop.frame =CGRectMake(0,44+([UIApplication sharedApplication].statusBarHidden?0:20), self.view.frame.size.width, 44); if (!MHISIPAD) { if (UIApplication.sharedApplication.statusBarOrientation != UIInterfaceOrientationPortrait) { self.moviePlayerToolBarTop.frame =CGRectMake(0,32+([UIApplication sharedApplication].statusBarHidden?0:20), self.view.frame.size.width, 44); } } } } -(void)changeUIForViewMode:(MHGalleryViewMode)viewMode{ float alpha = 0; if (viewMode == MHGalleryViewModeImageViewerNavigationBarShown) { alpha = 1; } self.moviePlayer.backgroundView.backgroundColor = [self.viewController.UICustomization MHGalleryBackgroundColorForViewMode:viewMode]; self.scrollView.backgroundColor = [self.viewController.UICustomization MHGalleryBackgroundColorForViewMode:viewMode]; self.viewController.pageViewController.view.backgroundColor = [self.viewController.UICustomization MHGalleryBackgroundColorForViewMode:viewMode]; self.navigationController.navigationBar.alpha = alpha; self.viewController.toolbar.alpha = alpha; self.viewController.titleView.alpha = alpha; self.viewController.titleViewBackground.alpha = alpha; self.viewController.descriptionView.alpha = alpha; self.viewController.descriptionViewBackground.alpha = alpha; if (!MHShouldShowStatusBar()) { alpha = 0; } MHStatusBar().alpha = alpha; } -(void)handelImageTap:(UIGestureRecognizer *)gestureRecognizer{ if (_changeIsLocked) { return; } if (!self.viewController.isHiddingToolBarAndNavigationBar) { if ([gestureRecognizer respondsToSelector:@selector(locationInView:)]) { CGPoint tappedLocation = [gestureRecognizer locationInView:self.view]; if (CGRectContainsPoint(self.moviePlayerToolBarTop.frame, tappedLocation)) { return; } } [UIView animateWithDuration:0.3 animations:^{ if (self.moviePlayerToolBarTop) { self.moviePlayerToolBarTop.alpha =0; } [self changeUIForViewMode:MHGalleryViewModeImageViewerNavigationBarHidden]; } completion:^(BOOL finished) { self.viewController.hiddingToolBarAndNavigationBar = YES; self.navigationController.navigationBar.hidden =YES; self.viewController.toolbar.hidden =YES; }]; }else{ self.navigationController.navigationBar.hidden = NO; self.viewController.toolbar.hidden = NO; [UIView animateWithDuration:0.3 animations:^{ [self changeUIForViewMode:MHGalleryViewModeImageViewerNavigationBarShown]; if (self.moviePlayerToolBarTop) { if (self.item.galleryType == MHGalleryTypeVideo) { self.moviePlayerToolBarTop.alpha =1; } } } completion:^(BOOL finished) { self.viewController.hiddingToolBarAndNavigationBar = NO; }]; } } - (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer { if (([self.imageView.image isEqual:MHGalleryImage(@"error")]) || (self.item.galleryType == MHGalleryTypeVideo)) { return; } if (self.scrollView.zoomScale >1) { [self.scrollView setZoomScale:1 animated:YES]; return; } [self centerImageView]; CGRect zoomRect; CGFloat newZoomScale = (self.scrollView.maximumZoomScale); CGPoint touchPoint = [gestureRecognizer locationInView:gestureRecognizer.view]; zoomRect.size.height = [self.imageView frame].size.height / newZoomScale; zoomRect.size.width = [self.imageView frame].size.width / newZoomScale; touchPoint = [self.scrollView convertPoint:touchPoint fromView:self.imageView]; zoomRect.origin.x = touchPoint.x - ((zoomRect.size.width / 2.0)); zoomRect.origin.y = touchPoint.y - ((zoomRect.size.height / 2.0)); [self.scrollView zoomToRect:zoomRect animated:YES]; } -(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{ return [scrollView.subviews firstObject]; } - (void)prepareToResize{ CGPoint boundsCenter = CGPointMake(CGRectGetMidX(self.scrollView.bounds), CGRectGetMidY(self.scrollView.bounds)); self.pointToCenterAfterResize = [self.scrollView convertPoint:boundsCenter toView:self.imageView]; self.scaleToRestoreAfterResize = self.scrollView.zoomScale; } - (void)recoverFromResizing{ self.scrollView.zoomScale = MIN(self.scrollView.maximumZoomScale, MAX(self.scrollView.minimumZoomScale, _scaleToRestoreAfterResize)); CGPoint boundsCenter = [self.scrollView convertPoint:self.pointToCenterAfterResize fromView:self.imageView]; CGPoint offset = CGPointMake(boundsCenter.x - self.scrollView.bounds.size.width / 2.0, boundsCenter.y - self.scrollView.bounds.size.height / 2.0); CGPoint maxOffset = [self maximumContentOffset]; CGPoint minOffset = [self minimumContentOffset]; offset.x = MAX(minOffset.x, MIN(maxOffset.x, offset.x)); offset.y = MAX(minOffset.y, MIN(maxOffset.y, offset.y)); self.scrollView.contentOffset = offset; } - (CGPoint)maximumContentOffset{ CGSize contentSize = self.scrollView.contentSize; CGSize boundsSize = self.scrollView.bounds.size; return CGPointMake(contentSize.width - boundsSize.width, contentSize.height - boundsSize.height); } - (CGPoint)minimumContentOffset{ return CGPointZero; } -(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{ if (self.moviePlayerToolBarTop) { self.moviePlayerToolBarTop.frame = CGRectMake(0, self.navigationController.navigationBar.bounds.size.height+([UIApplication sharedApplication].statusBarHidden?0:20), self.view.frame.size.width,44); self.leftSliderLabel.frame = CGRectMake(8, 0, 40, 43); self.rightSliderLabel.frame = CGRectMake(self.view.frame.size.width-20, 0, 50, 43); } self.playButton.frame = CGRectMake(self.viewController.view.frame.size.width/2-36, self.viewController.view.frame.size.height/2-36, 72, 72); self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width*self.scrollView.zoomScale, self.view.bounds.size.height*self.scrollView.zoomScale); self.imageView.frame = CGRectMake(0,0 , self.scrollView.contentSize.width,self.scrollView.contentSize.height); } -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{ [self prepareToResize]; [self recoverFromResizing]; [self centerImageView]; } -(void)centerImageView{ if(self.imageView.image){ CGRect frame = AVMakeRectWithAspectRatioInsideRect(self.imageView.image.size,CGRectMake(0, 0, self.scrollView.contentSize.width, self.scrollView.contentSize.height)); if (self.scrollView.contentSize.width==0 && self.scrollView.contentSize.height==0) { frame = AVMakeRectWithAspectRatioInsideRect(self.imageView.image.size,self.scrollView.bounds); } CGSize boundsSize = self.scrollView.bounds.size; CGRect frameToCenter = CGRectMake(0,0 , frame.size.width, frame.size.height); if (frameToCenter.size.width < boundsSize.width){ frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2; }else{ frameToCenter.origin.x = 0; }if (frameToCenter.size.height < boundsSize.height){ frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2; }else{ frameToCenter.origin.y = 0; } self.imageView.frame = frameToCenter; } } -(void)scrollViewDidZoom:(UIScrollView *)scrollView{ [self centerImageView]; } -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ } @end
{ "content_hash": "8ab887e21c4e94c2324e3a10418844e5", "timestamp": "", "source": "github", "line_count": 1601, "max_line_length": 259, "avg_line_length": 43.369144284821985, "alnum_prop": 0.6624852377797621, "repo_name": "santangeli/MHVideoPhotoGallery", "id": "9ec054e1101d18431212cfa50ea7721049771796", "size": "69802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MHVideoPhotoGallery/MMHVideoPhotoGallery/MHGalleryImageViewerViewController/MHGalleryImageViewerViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "514061" }, { "name": "Ruby", "bytes": "784" } ], "symlink_target": "" }
module CoreExtensions module Object def is_numeric? true if Float(self) rescue false end end end Object.send(:include, CoreExtensions::Object)
{ "content_hash": "9274189b4b394055d1206188c816a948", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 45, "avg_line_length": 18, "alnum_prop": 0.7160493827160493, "repo_name": "zombiepaladin/smartfarm", "id": "76f9cf7b0b1239397f6be21257fa04a8975c6658", "size": "162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/core_extensions/object.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8709" }, { "name": "CoffeeScript", "bytes": "33211" }, { "name": "JavaScript", "bytes": "117395" }, { "name": "Ruby", "bytes": "72137" }, { "name": "Shell", "bytes": "13387" } ], "symlink_target": "" }
from __future__ import print_function # Kill this instance if another copy is running. from tendo import singleton me = singleton.SingleInstance() # Will sys.exit(-1) if other instance is running # Aether modules import globals from globals import FROZEN, PROFILE_DIR, PLATFORM, BASEDIR, AETHER_VERSION from GUI.guiElements import * from ORM import Hermes from urllib import urlopen import re app = Aether() #Python imports import os if FROZEN: del sys.modules['twisted.internet.reactor'] import qt5reactor qt5reactor.install() from twisted.internet import reactor from InputOutput.Charon import Charon from twisted.web.client import getPage from twisted.internet import threads if globals.userProfile.get('debugDetails', 'debugLogging'): from twisted.python import log from twisted.python.logfile import DailyLogFile log.startLogging(DailyLogFile.fromFullPath(PROFILE_DIR+'/Logs/interface.log')) globals.logSystemDetails() else: def print(*a, **kwargs): pass baseurl = os.getcwd()+'/' if len(sys.argv) > 1 and sys.argv[1] == '-openatlogin': globals.APP_STARTED_AT_SYSTEM_STARTUP = True if PLATFORM == 'OSX': import objc import AppKit if FROZEN: class NSObjCApp(AppKit.AppKit.NSObject): @objc.signature('B@:#B') def applicationShouldHandleReopen_hasVisibleWindows_(self, nsAppObject, flag): app.onClickOnDock() return True else: class NSObjCApp(AppKit.NSObject): @objc.signature('B@:#B') def applicationShouldHandleReopen_hasVisibleWindows_(self, nsAppObject, flag): app.onClickOnDock() return True cls = objc.lookUpClass('NSApplication') appInstance = cls.sharedApplication() # I'm doing some real crazy runtime shit there. ta = NSObjCApp.alloc().init() appInstance.setDelegate_(ta) if PLATFORM == 'LNX': app.setStyle("Fusion") # This is a fix to 'CRITICAL: GTK_IS_WIDGET (widget)' failed' bug on Debian / Ubuntu. # Visually it doesn't change anything, it's just an explicit declaration to help Unity. def main(): global reactor from twisted.internet import reactor print('Spawning the networking daemon...') # Spawn the networking daemon. from InputOutput import interprocessChildProt from ampoule_aether import pool from InputOutput import interprocessParentProt from ampoule_aether import main as ampouleMain if FROZEN: procStarter = ampouleMain.ProcessStarter() else: procStarter = ampouleMain.ProcessStarter(bootstrap=interprocessChildProt.childBootstrap) global pp pp = pool.ProcessPool(interprocessChildProt.NetworkingProcessProtocol, ampParent=interprocessParentProt.MainProcessProtocol, starter=procStarter, recycleAfter=0, min=1, max=1) pp.start() pp.ampParent.processPool = pp # Self referential much? # Networking daemon spawnage ends here. print('Networking daemon spawned.') hermes = Hermes.Hermes(pp) charon = Charon(hermes) view = AetherMainWindow(charon, reactor, baseurl, app) if PLATFORM == 'OSX' or PLATFORM == 'WIN': trayIcon = SystemTrayIcon(BASEDIR, app, view) # trayIcon.protInstance = protInstance # protInstance.trayIcon = trayIcon ef = ModifierEventFilter() app.view = view ef.view = view view.pp = pp if PLATFORM == 'OSX' or PLATFORM == 'WIN': app.trayIcon = trayIcon view.trayIcon = trayIcon ef.trayIcon = trayIcon charon.trayIcon = trayIcon trayIcon.webView = view trayIcon.show() app.installEventFilter(ef) # Attach the items to the parent protocol, so it can react on the events arriving from networking daemon. pp.ampParent.Hermes = hermes if PLATFORM == 'OSX' or PLATFORM == 'WIN': pp.ampParent.trayIcon = trayIcon pp.ampParent.JSContext = view.JSContext if globals.userProfile.get('debugDetails', 'enableWebkitInspector'): from PyQt5.QtWebKit import QWebSettings QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) inspect = QWebInspector() inspect.resize(1450, 300) inspect.move(0,0) inspect.setPage(view.webView.page()) view.setContextMenuPolicy(Qt.DefaultContextMenu) inspect.show() splash.finish(view) if globals.APP_STARTED_AT_SYSTEM_STARTUP: if PLATFORM == 'LNX': # Because there is no tray icon on Linux, app starts minimised ( (-) state). view.showMinimized() elif PLATFORM == 'OSX' or PLATFORM == 'WIN': pass # Do nothing, there is already a tray icon in place. else: # If not started at boot view.show() def checkForUpdates(): # One catch, any result available out of this will only be visible after next boot of the app. d = getPage('http://www.getaether.net/updatecheck') def processReceivedVersion(reply): if int(reply[:3]) > AETHER_VERSION: globals.userProfile.set('machineDetails', 'updateAvailable', True) print('There is an update available, local version is %d and gathered version is %s.' % (AETHER_VERSION, reply)) else: globals.userProfile.set('machineDetails', 'updateAvailable', False) print('There is no update available') return d.addCallback(processReceivedVersion) if globals.userProfile.get('machineDetails', 'checkForUpdates'): d = checkForUpdates() d.addErrback(print, 'Checking for updates failed. Either the server is down, or the internet connection is not available.') def setPublicIPAddress(): # For privacy reasons, this can be disabled by setting 'allowPublicIPLookup' to false at your user profile json. # The only use case for this is to show you your IP address in the settings, so you can give your IP address # and port to your friend to use you as the bootstrap node. If you can read this, you don't need that. Disable. data = str(urlopen('http://checkip.dyndns.com/').read()) result = re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) globals.userProfile.set('machineDetails', 'externalIP', result) print('Public IP of this machine is %s' % result) return True if globals.userProfile.get('machineDetails', 'allowPublicIPLookup'): d2 = threads.deferToThread(setPublicIPAddress) # d2.addErrback(print, 'The public IP address could not be found. The internet connection is not available.') reactor.run() if __name__ == "__main__": pixmap = QtGui.QPixmap(BASEDIR+'Assets/splash.png') splash = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint) print('profiledir:') print(PROFILE_DIR) if not globals.APP_STARTED_AT_SYSTEM_STARTUP: splash.show() main() if reactor.threadpool is not None: reactor.threadpool.stop() reactor.stop() sys.exit()
{ "content_hash": "61babb964d5f212d4ee87c5f52b7ae3a", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 112, "avg_line_length": 29.841346153846153, "alnum_prop": 0.7725149025294022, "repo_name": "filinggettingrk/Thefirst", "id": "4119d7ee27fe439a2203a23b6ad5b16f136ee8b7", "size": "6207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "haha.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "6207" } ], "symlink_target": "" }
<h4> your password has been changed successfully</h4> <h5> Please <a href='<?= WEBSITE ?>login/login_form'>Click here</a> to login again</h5> <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ ?>
{ "content_hash": "d4001124377bbb98b6ccd731af40ef20", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 87, "avg_line_length": 19.692307692307693, "alnum_prop": 0.671875, "repo_name": "kdgupta/lms", "id": "dda370ad9b2ce252671791ad18e7ac36f82f79e4", "size": "256", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/view_after_change_pass.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "96" }, { "name": "PHP", "bytes": "1316311" } ], "symlink_target": "" }
class ProjectDescendantsRecalculator include Sidekiq::Worker sidekiq_options queue: :high # Executes this worker. # # @param [Fixnum] project_id The ID of a Project. def perform(project_id) project = Project.find(project_id) # the readiness hooks were all disabled, so now we need to go through and calculate readiness. Key.batch_recalculate_ready!(project) project.commits.find_each do |commit| CommitRecalculator.perform_once(commit.id) end project.articles.find_each do |article| ArticleRecalculator.perform_once(article.id) end project.assets.find_each do |asset| AssetRecalculator.perform_once(asset.id) end end include SidekiqLocking end
{ "content_hash": "d4f1b7019c66cdbd467078def2a865b3", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 98, "avg_line_length": 24.862068965517242, "alnum_prop": 0.7212205270457698, "repo_name": "square/shuttle", "id": "38ab6b9778d7ed6b2e41bf43f72af1150800e6f7", "size": "2030", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/workers/project_descendants_recalculator.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1321" }, { "name": "CoffeeScript", "bytes": "109642" }, { "name": "Dockerfile", "bytes": "699" }, { "name": "HTML", "bytes": "69426" }, { "name": "JavaScript", "bytes": "3652" }, { "name": "Mustache", "bytes": "7387" }, { "name": "Procfile", "bytes": "115" }, { "name": "Ruby", "bytes": "2005291" }, { "name": "SCSS", "bytes": "99725" }, { "name": "Shell", "bytes": "3784" }, { "name": "Slim", "bytes": "185134" } ], "symlink_target": "" }
class CreateRules < ActiveRecord::Migration def self.up create_table :rules, :id => false do |t| t.string :id t.string :rule_number t.integer :condition_id t.integer :action_id t.timestamps end execute "ALTER TABLE rules ADD PRIMARY KEY (id)" end def self.down drop_table :rules end end
{ "content_hash": "b01f2270d9c071032f45008547f218ab", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 52, "avg_line_length": 20.176470588235293, "alnum_prop": 0.6355685131195336, "repo_name": "sizzlelab/asi", "id": "8efa5e381a035457a4f4d53f5491733262a0de1b", "size": "343", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20091020132002_create_rules.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "20818" }, { "name": "Ruby", "bytes": "494610" }, { "name": "Shell", "bytes": "46" } ], "symlink_target": "" }
Repo will hold information about a Pomodoro Timer Project To run the app install the virtual environment and `requirements.txt` ###What is a pomodoro timer?? This is a timer that counts time periods each with a default interval of 25 minutes but the interval can be adjusted. There is a short break between each cycle with a default time of 5 minutes but its adjustable After the third cycle the user is forced into a long break that has a default time 15 minutes but it is also adjustable This app is built use __cliff__ command line framework that the implementer the right to have an almost simmilar to commmandline applications like *git* To run this app input command `python PomodoroTime.py` The pomodoro Timer application has the following commands: 1. pomodoro create\*<title> this creates a timer object with the *title* implemented as `pomodoro create*Presentation2` 2. pomodoro config_time\*<hrs:min:sec> this command modifies the default duration time `pomodoro config_time*1:34:20` the interval is 1 hr 34 minutes and 20 secs 3. pomodoro config_shortbreak\*<hrs:min:sec> `pomodoro config_shortbreak*7:0` the shortbreak time is 7 minutes 0 seconds 4. pomodoro config_longbreak*<hrs:min:sec> `pomodoro config_longbreak*20:0` the longbreak time is 20 minutes 0 seconds 5. pomodoro config_sound\*<on/off> Command sets the sound to either ring or not `pomodoro config_sound*on` set sound on 6. pomodoro timer\*<hrs:min:sec> command set time from which the timer should start counting default time is now `pomodoro timer*1:30:0` command sets to start the timer to start in 1hr and 30min 7. pomodoro start\*<title> command pushes all the data of a created task to the database `pomodoro start*Presentation2` presentation2 has been set active and timer is countinng or its waiting to start counting 8.pomodoro pause\*<title> command moves a task that is in status active to status pending which means its timer has been stopped temporarirly `pomodoro pause*Presentation2` 9.pomodoro stop\*<title> task is moved at status finished. At this status a task is considered permanently stopped or its timer rang `pomodoro stop*Presentation` 10. listitems This command list all the data in the database`listitems` 11. listitems byday\*<dd:mm:YYYY> This command Lists all task with the start time equal to the given parameter `listitems byday*28:08:2016` check all the command with the start date as 28th August 2016 __To do List__ * command 6 * command 8 * command 11 * command 9 Done by __Migwi Ndung'u__ @ ###0703764266
{ "content_hash": "649efbe962af541668bf60ae4a3a00f7", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 168, "avg_line_length": 50.905660377358494, "alnum_prop": 0.737583395107487, "repo_name": "Migwi-Ndungu/bc-9-Pomodoro-Timer", "id": "a0490e12e05289b52ac44af4243131013c2e4697", "size": "2723", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "22713" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_91) on Mon Jun 06 14:51:22 EDT 2016 --> <title>Uses of Interface org.apache.cassandra.io.util.ChunkReader (apache-cassandra API)</title> <meta name="date" content="2016-06-06"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.apache.cassandra.io.util.ChunkReader (apache-cassandra API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/io/util/class-use/ChunkReader.html" target="_top">Frames</a></li> <li><a href="ChunkReader.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.apache.cassandra.io.util.ChunkReader" class="title">Uses of Interface<br>org.apache.cassandra.io.util.ChunkReader</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.cassandra.cache">org.apache.cassandra.cache</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.apache.cassandra.io.util">org.apache.cassandra.io.util</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.cassandra.cache"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a> in <a href="../../../../../../org/apache/cassandra/cache/package-summary.html">org.apache.cassandra.cache</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/cassandra/cache/package-summary.html">org.apache.cassandra.cache</a> with parameters of type <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../org/apache/cassandra/io/util/RebuffererFactory.html" title="interface in org.apache.cassandra.io.util">RebuffererFactory</a></code></td> <td class="colLast"><span class="typeNameLabel">ChunkCache.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/cache/ChunkCache.html#maybeWrap-org.apache.cassandra.io.util.ChunkReader-">maybeWrap</a></span>(<a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a>&nbsp;file)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/cassandra/io/util/RebuffererFactory.html" title="interface in org.apache.cassandra.io.util">RebuffererFactory</a></code></td> <td class="colLast"><span class="typeNameLabel">ChunkCache.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/cache/ChunkCache.html#wrap-org.apache.cassandra.io.util.ChunkReader-">wrap</a></span>(<a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a>&nbsp;file)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.cassandra.io.util"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a> in <a href="../../../../../../org/apache/cassandra/io/util/package-summary.html">org.apache.cassandra.io.util</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../org/apache/cassandra/io/util/package-summary.html">org.apache.cassandra.io.util</a> that implement <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/io/util/CompressedSegmentedFile.CompressedChunkReader.html" title="class in org.apache.cassandra.io.util">CompressedSegmentedFile.CompressedChunkReader</a></span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../org/apache/cassandra/io/util/package-summary.html">org.apache.cassandra.io.util</a> declared as <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></code></td> <td class="colLast"><span class="typeNameLabel">BufferManagingRebufferer.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/io/util/BufferManagingRebufferer.html#source">source</a></span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/cassandra/io/util/package-summary.html">org.apache.cassandra.io.util</a> that return <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></code></td> <td class="colLast"><span class="typeNameLabel">CompressedSegmentedFile.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/io/util/CompressedSegmentedFile.html#chunkReader-org.apache.cassandra.io.util.ChannelProxy-org.apache.cassandra.io.compress.CompressionMetadata-org.apache.cassandra.io.util.MmappedRegions-">chunkReader</a></span>(<a href="../../../../../../org/apache/cassandra/io/util/ChannelProxy.html" title="class in org.apache.cassandra.io.util">ChannelProxy</a>&nbsp;channel, <a href="../../../../../../org/apache/cassandra/io/compress/CompressionMetadata.html" title="class in org.apache.cassandra.io.compress">CompressionMetadata</a>&nbsp;metadata, <a href="../../../../../../org/apache/cassandra/io/util/MmappedRegions.html" title="class in org.apache.cassandra.io.util">MmappedRegions</a>&nbsp;regions)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/cassandra/io/util/package-summary.html">org.apache.cassandra.io.util</a> with parameters of type <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../org/apache/cassandra/io/util/BufferManagingRebufferer.html" title="class in org.apache.cassandra.io.util">BufferManagingRebufferer</a></code></td> <td class="colLast"><span class="typeNameLabel">BufferManagingRebufferer.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/io/util/BufferManagingRebufferer.html#on-org.apache.cassandra.io.util.ChunkReader-">on</a></span>(<a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a>&nbsp;wrapped)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../../org/apache/cassandra/io/util/package-summary.html">org.apache.cassandra.io.util</a> with parameters of type <a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/io/util/BufferManagingRebufferer.Aligned.html#Aligned-org.apache.cassandra.io.util.ChunkReader-">Aligned</a></span>(<a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a>&nbsp;wrapped)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/io/util/BufferManagingRebufferer.html#BufferManagingRebufferer-org.apache.cassandra.io.util.ChunkReader-">BufferManagingRebufferer</a></span>(<a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a>&nbsp;wrapped)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/cassandra/io/util/BufferManagingRebufferer.Unaligned.html#Unaligned-org.apache.cassandra.io.util.ChunkReader-">Unaligned</a></span>(<a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">ChunkReader</a>&nbsp;wrapped)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/io/util/ChunkReader.html" title="interface in org.apache.cassandra.io.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/io/util/class-use/ChunkReader.html" target="_top">Frames</a></li> <li><a href="ChunkReader.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2016 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "c4705d55ae1b4c1431d497b303bab67e", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 526, "avg_line_length": 60.57831325301205, "alnum_prop": 0.6685892336250332, "repo_name": "jasonwee/videoOnCloud", "id": "415b155f725814186f3273160a176dff4b3eeefe", "size": "15084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/cassandra/apache-cassandra-3.7/javadoc/org/apache/cassandra/io/util/class-use/ChunkReader.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "116270" }, { "name": "C", "bytes": "2209717" }, { "name": "C++", "bytes": "375267" }, { "name": "CSS", "bytes": "1134648" }, { "name": "Dockerfile", "bytes": "1656" }, { "name": "HTML", "bytes": "306558398" }, { "name": "Java", "bytes": "1465506" }, { "name": "JavaScript", "bytes": "9028509" }, { "name": "Jupyter Notebook", "bytes": "30907" }, { "name": "Less", "bytes": "107003" }, { "name": "PHP", "bytes": "856" }, { "name": "PowerShell", "bytes": "77807" }, { "name": "Pug", "bytes": "2968" }, { "name": "Python", "bytes": "1001861" }, { "name": "R", "bytes": "7390" }, { "name": "Roff", "bytes": "3553" }, { "name": "Shell", "bytes": "206191" }, { "name": "Thrift", "bytes": "80564" }, { "name": "XSLT", "bytes": "4740" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?><testsuite> <test id="ID_JIL_xhr_ports_100" src="test_base_xhr_ports.wgt">xhr Call to HTTP site Instructions: Follow the instructions on the screen. Expected behaviour: See green colored line on the device screen.</test> <test id="ID_JIL_xhr_ports_200" src="test_base_xhr_ports.wgt">xhr Call to HTTPS site Instructions: Follow the instructions on the screen. Expected behaviour: See green colored line on the device screen.</test> <test id="ID_JIL_xhr_ports_300" src="test_base_xhr_ports.wgt">xhr Call to HTTPS site with credentials Instructions: Follow the instructions on the screen. Expected behaviour: See green colored line on the device screen.</test> <test id="ID_JIL_xhr_ports_400" src="test_base_xhr_ports.wgt">xhr Page which runs on port 8000 Instructions: Follow the instructions on the screen. Expected behaviour: See green colored line on the device screen.</test> </testsuite>
{ "content_hash": "324b7bc7b1ca0b4afdde7e7d4f5fb8ba", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 105, "avg_line_length": 31.766666666666666, "alnum_prop": 0.751311647429171, "repo_name": "vf/web-testsuite-runner", "id": "d7d0094a2fed40f69401ec59bbe3d1acc1880c46", "size": "953", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "exporter/wac/dist/description-test_base_xhr_ports.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "564600" }, { "name": "Shell", "bytes": "1430" } ], "symlink_target": "" }
package io.cdap.directives.parser; import com.google.gson.Gson; import io.cdap.cdap.api.annotation.Description; import io.cdap.cdap.api.annotation.Name; import io.cdap.cdap.api.annotation.Plugin; import io.cdap.wrangler.api.Arguments; import io.cdap.wrangler.api.Directive; import io.cdap.wrangler.api.DirectiveExecutionException; import io.cdap.wrangler.api.DirectiveParseException; import io.cdap.wrangler.api.ExecutorContext; import io.cdap.wrangler.api.Row; import io.cdap.wrangler.api.annotations.Categories; import io.cdap.wrangler.api.lineage.Lineage; import io.cdap.wrangler.api.lineage.Many; import io.cdap.wrangler.api.lineage.Mutation; import io.cdap.wrangler.api.parser.ColumnName; import io.cdap.wrangler.api.parser.TokenType; import io.cdap.wrangler.api.parser.UsageDefinition; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.util.Utf8; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * A step to parse AVRO File. */ @Plugin(type = Directive.TYPE) @Name("parse-as-avro-file") @Categories(categories = { "parser", "avro"}) @Description("parse-as-avro-file <column>.") public class ParseAvroFile implements Directive, Lineage { public static final String NAME = "parse-as-avro-file"; private String column; private Gson gson; @Override public UsageDefinition define() { UsageDefinition.Builder builder = UsageDefinition.builder(NAME); builder.define("column", TokenType.COLUMN_NAME); return builder.build(); } @Override public void initialize(Arguments args) throws DirectiveParseException { this.column = ((ColumnName) args.value("column")).value(); gson = new Gson(); } @Override public void destroy() { // no-op } @Override public List<Row> execute(List<Row> rows, final ExecutorContext context) throws DirectiveExecutionException { List<Row> results = new ArrayList<>(); for (Row row : rows) { int idx = row.find(column); if (idx != -1) { Object object = row.getValue(idx); if (object instanceof byte[]) { DataFileReader<GenericRecord> reader = null; try { reader = new DataFileReader<>(new SeekableByteArrayInput((byte[]) object), new GenericDatumReader<>()); while (reader.hasNext()) { Row newRow = new Row(); add(reader.next(), newRow, null); results.add(newRow); } } catch (IOException e) { throw new DirectiveExecutionException(NAME, "Failed to parse Avro data file. " + e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Nothing can be done. } } } } else { throw new DirectiveExecutionException( NAME, String.format("Column '%s' is of invalid type. It should be of type 'byte array'.", column)); } } } return results; } @Override public Mutation lineage() { return Mutation.builder() .readable("Parsed column '%s' as a Avro file", column) .all(Many.columns(column)) .build(); } /** * Flattens the {@link GenericRecord}. * * @param genericRecord to be flattened. * @param row to be flattened into * @param name of the field to be flattened. */ private void add(GenericRecord genericRecord, Row row, String name) { List<Schema.Field> fields = genericRecord.getSchema().getFields(); String colname; for (Schema.Field field : fields) { Object v = genericRecord.get(field.name()); if (name != null) { colname = String.format("%s_%s", name, field.name()); } else { colname = field.name(); } if (v instanceof GenericRecord) { add((GenericRecord) v, row, colname); } else if (v instanceof Map || v instanceof List) { row.add(colname, gson.toJson(v)); } else if (v instanceof Utf8) { row.add(colname, v.toString()); } else { row.add(colname, genericRecord.get(field.name())); } } } }
{ "content_hash": "2bdba87d11065c836fab9368e45f4f91", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 112, "avg_line_length": 32, "alnum_prop": 0.6505474452554745, "repo_name": "data-integrations/wrangler", "id": "c59dfbb2540d06f6ce6072d9b9e67f3cae9ccfb6", "size": "4996", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "wrangler-core/src/main/java/io/cdap/directives/parser/ParseAvroFile.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "5185" }, { "name": "Java", "bytes": "2283216" } ], "symlink_target": "" }
Fractal ======= **A versatile CMS for Laravel 5.** [![Latest Stable Version](https://poser.pugx.org/regulus/fractal/v/stable.svg)](https://packagist.org/packages/regulus/fractal) [![License](https://poser.pugx.org/regulus/fractal/license.svg)](https://packagist.org/packages/regulus/fractal) > **Note:** For Laravel 4, you may use <a href="https://github.com/Regulus343/Fractal/tree/v0.8.2">version 0.8.2</a>. ![Screenshot](resources/screenshot.png) Fractal is a content management system for Laravel which maintains freedom and easy access to customization, to a range of different degrees. You can do all of this out of the box: - Manage content pages for website - Create as many separate content areas as you like and create content in Markdown or an HTML WYSIWYG editor - Use the layout template system to re-use standardized and custom layouts across pages - Re-use content areas across multiple pages - Manage files - Upload files - Resize images - Create thumbnail images - Manage blog articles - Make use of the same versatile content area system as content pages uses - Manage media items (images, video, audio, and more...) - Manage website / web application settings - Manage all menus via database, for both front-end website (optional of course) and admin/CMS area - Manage users - Customize routes, controllers, and subdomains (by default, "blog" and "media" subdomains are used) - Use built-in front-end views and Blade layouts or use your own Please keep in mind though that there are a variety of different levels of customization available from using all or a partial set of custom controllers (Fractal's controller and method routes are set in `config.php` for easy modification), using custom views, or even just customizing any of the many available config settings or database-stored settings in the CMS' Settings page. The level of control of your website or web application that you wish to externalize from Fractal is entirely up to you. A couple more things that should be mentioned before we get started with the Table of Contents: - Fractal uses the [Identify](https://github.com/Regulus343/Identify) authorization / authentication package and uses Twitter Bootstrap 3 as its CSS framework. - You may view [Fractal on Trello](https://trello.com/b/ZaGw8Jly/fractal) to see what's on the bug fixing and feature implementation roadmap. ## Table of Contents - [Installation](#installation) - [Installation: Authentication](#auth-installation) - [First Log In](#first-log-in) - [Basic Usage](#basic-usage) <a name="installation"></a> ## Installation **Install composer package:** To install Fractal, make sure "regulus/fractal" has been added to Laravel 5's `composer.json` file. "require": { "regulus/fractal": "0.9.*" }, Then run `php composer.phar update` from the command line. Composer will install the Fractal package. **Register service provider and set up alias:** Now, all you have to do is register the service provider, set up Fractal's alias in `config/app.php`, publish the assets, and run the install command. Add this to the `providers` array: Regulus\Fractal\FractalServiceProvider::class, And add this to the `aliases` array: 'Fractal' => Regulus\Fractal\Facade::class, **Add middleware to the `routeMiddleware` array in `app/Http/Kernal.php`:** 'auth.permissions' => \Regulus\Identify\Middleware\Authorize::class, 'auth.fractal' => \Regulus\Fractal\Middleware\Authenticate::class, **Add and run the install command:** Add the following to the `commands` array in `app/Console/Kernel.php`: \Regulus\Identify\Commands\Install::class, \Regulus\Identify\Commands\CreateUser::class, \Regulus\Fractal\Commands\Install::class, **Set the sessions domain:** Set the `domain` variable in `config/sessions.php` to ensure that session data is carried across subdomains: 'domain' => '.website.com', Then run the following command: php artisan fractal:install Fractal (along with Identify) will now be installed. This includes all necessary DB migrations, DB seeding, config publishing, and asset publishing. The config file that is published for Identify is `auth.php` and will overwrite Laravel 5's default auth configuration. The default table names are prefixed with `auth_`, but you may alter the users table name by adding a `--user-tables-prefix` option to the install line: php artisan fractal:install --user-tables-prefix=none php artisan fractal:install --user-tables-prefix=identify The former example will remove the prefix from all of the table names, so you will get `users`, `roles`, etc. The latter example will change the default table prefix of `auth` to `identify` so your table names will be `identify_users`, `identify_roles`, etc. You should now have 4 users, `Admin`, `TestUser`, `TestUser2`, and `TestUser3`. All of the default passwords are simply `password` and the usernames are case insensitive, so you may simply type `admin` and `password` to log in. The 3 initial roles are `Administrator`, `Moderator`, and `Member`. `Admin` has the `Administrator` role, `TestUser` has the `Moderator` role, and the final 2 users have the `Member` role. The install command will also attempt to automatically add a singleton to `bootstrap/app.php` which swaps out Laravel's default `LoadConfiguration` class to allow delaying the loading of certain config files until after Fractal's service provider runs. If the install command is not able to add the singleton, go into `bootstrap/app.php` and add this after the other singletons under the "Bind Important Interfaces" heading: $app->singleton( Illuminate\Foundation\Bootstrap\LoadConfiguration::class, Regulus\Fractal\Libraries\LoadConfiguration::class ); <a name="auth-installation"></a> ## Installation for Authentication **Install Composer package:** To install Identify, make sure "regulus/identify" has been added to Laravel 5's `composer.json` file. "require": { "regulus/identify": "dev-master" }, Then run `php composer.phar update` from the command line. Composer will install the Identify package. **Register service provider and set up alias:** Add this to the `providers` array in `config/app.php`: 'Regulus\Identify\IdentifyServiceProvider', <a name="first-log-in"></a> ## First Log In **Logging in:** To log in, go to `website.com/admin` where "website.com" is the name of the site you have installed Fractal on. Type "Admin" and "password" as your username and password and click "Log In". You should now be logged in to Fractal for the first time. You should now be able to manage the CMS and the settings of the website or web application. **Enabling Developer Mode:** To set a `developer` session variable to `true`, go to `website.com/admin/developer`. This will identify you as the web developer for Fractal and you may be able to see more information and manage extra settings. To turn off Developer Mode, go to `website.com/admin/developer/off`. <a name="basic-usage"></a> ## Basic Usage **Adjusting Fractal's base URI:** By default, Fractal's base URI is `admin` making your URLs like `website.com/admin/pages/home/edit`. You may adjust this in the `base_uri` variable in `config.php`. **Adding additional controllers:** You may add additional controllers or point existing defined controllers to alternates in the `controllers` array in `config.php`. Use `standard` for standard Laravel controllers and `resource` for resource controllers. **Other configuration options:** Look around in the various config files such as `config`, `blogs`, `media`, `tables`, and `social` to see what other configuration options can easily be customized as well. Most config variables have detailed descriptions that should help you to understand how different things can be customized. The config files `menus` and `settings`, however, are exported from the database automatically to minimize a Fractal-driven website's need to make certain database queries on each page load. **Get Bootstrap-ready menu markup for a view:** echo Fractal::getMenuMarkup(); //get "Main" menu markup echo Fractal::getMenuMarkup('Footer'); //get "Footer" menu markup echo Fractal::getMenuMarkup('Footer', ['class' => 'nav nav-pills']); //set class attribute for menu **Getting an array of menu items:** $menu = Fractal::getMenuArray(); //get "Main" menu array $menu = Fractal::getMenuArray('Footer'); //get "Footer" menu array **Setting a page title:** Fractal already uses [SolidSite](https://github.com/Regulus343/SolidSite) to handle page titles, breadcrumb trails, and some other things which means that if you are using Fractal's public layout for your website, you may set page titles using the following code. //title HTML tag may look like "A Page Title :: Website.com" depending on config Site::set('title', 'A Page Title'); //this can be used to differentiate the title that actually appears on the page from the primary title Site::set('titleHeading', 'Alternate Title in Content'); //you may show the title using these echo Site::title(); echo Site::titleHeading(); //will use "titleHeading" if it is set and if not will default to "title"
{ "content_hash": "0bbddb20af9307fa8c0fee4d471de85b", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 503, "avg_line_length": 49.766304347826086, "alnum_prop": 0.7602926722725784, "repo_name": "Regulus343/Fractal", "id": "35996e5ce9d647cf4120c80aa1280438736babde", "size": "9157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "readme.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "97697" }, { "name": "HTML", "bytes": "173207" }, { "name": "JavaScript", "bytes": "577189" }, { "name": "PHP", "bytes": "630284" } ], "symlink_target": "" }
package json import ( "encoding/json" "log" ) type Msg struct { Status string `json:"status"` Result interface{} `json:"data"` } type Result struct { Image []Fid `json:"image"` } type Fid struct { Field string `json:"field"` Value string `json:"value"` } func Message(status string, result interface{}) []byte { m := Msg{ Status: status, Result: result, } b, err := json.Marshal(m) if err != nil { log.Println("Unable to json.Marshal ", err) } return b }
{ "content_hash": "92b70e5c1fe1c30241a6867a3b6e9db3", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 56, "avg_line_length": 15.125, "alnum_prop": 0.6384297520661157, "repo_name": "kamoljan/sushiobrol", "id": "209ad11ef4a9fd4644028b0c0d52f5fff9856144", "size": "484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "json/json.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "7085" } ], "symlink_target": "" }
I represent either the start or end of text. My size is always ZERO and i have only a single valid position (spanPosition = 0)
{ "content_hash": "77c687185a2f74db4c4ac6bea181592b", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 81, "avg_line_length": 42.333333333333336, "alnum_prop": 0.7716535433070866, "repo_name": "zecke/pharo", "id": "1dabbc65af6592c7fef6caddb8213f5d0cb534c8", "size": "127", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/TxText-Model.package/TxTerminalSpan.class/README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.ovirt.engine.core.bll.storage.domain; import static org.ovirt.engine.core.bll.MultiLevelAdministrationHandler.SYSTEM_OBJECT_ID; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.profiles.DiskProfileHelper; import org.ovirt.engine.core.bll.storage.connection.StorageHelperDirector; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.WipeAfterDeleteUtils; import org.ovirt.engine.core.bll.validator.storage.StorageDomainToPoolRelationValidator; import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.StorageDomainManagementParameter; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainDynamic; import org.ovirt.engine.core.common.businessentities.StorageDomainStatic; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StorageFormatType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.StorageServerConnections; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.constants.StorageConstants; import org.ovirt.engine.core.common.errors.EngineError; import org.ovirt.engine.core.common.errors.EngineFault; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.VersionStorageFormatUtil; import org.ovirt.engine.core.common.validation.group.CreateEntity; import org.ovirt.engine.core.common.vdscommands.CreateStorageDomainVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.GetStorageDomainStatsVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.StorageServerConnectionManagementVDSParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.transaction.TransactionSupport; public abstract class AddStorageDomainCommand<T extends StorageDomainManagementParameter> extends StorageDomainManagementCommandBase<T> { protected AddStorageDomainCommand(T parameters) { super(parameters); } protected AddStorageDomainCommand(Guid commandId) { super(commandId); } public AddStorageDomainCommand(T parameters, CommandContext commandContext) { super(parameters, commandContext); } protected void initializeStorageDomain() { getStorageDomain().setId(Guid.newGuid()); updateStaticDataDefaults(); } protected void updateStaticDataDefaults() { updateStorageDomainWipeAfterDelete(); updateSpaceThresholds(); } private void updateStorageDomainWipeAfterDelete() { if(getStorageDomain().getStorageStaticData().getWipeAfterDelete() == null) { getStorageDomain().getStorageStaticData().setWipeAfterDelete( WipeAfterDeleteUtils.getDefaultWipeAfterDeleteFlag( getStorageDomain().getStorageStaticData().getStorageType())); } } private void updateSpaceThresholds() { if(getStorageDomain().getWarningLowSpaceIndicator() == null) { getStorageDomain().setWarningLowSpaceIndicator(Config.<Integer>getValue(ConfigValues.WarningLowSpaceIndicator)); } if(getStorageDomain().getCriticalSpaceActionBlocker() == null) { getStorageDomain().setCriticalSpaceActionBlocker(Config.<Integer>getValue(ConfigValues.CriticalSpaceActionBlocker)); } } protected boolean addStorageDomainInIrs() { // No need to run in separate transaction - counting on rollback of external transaction wrapping the command return runVdsCommand( VDSCommandType.CreateStorageDomain, new CreateStorageDomainVDSCommandParameters(getVds().getId(), getStorageDomain() .getStorageStaticData(), getStorageArgs())).getSucceeded(); } protected void addStorageDomainInDb() { TransactionSupport.executeInNewTransaction(() -> { StorageDomainStatic storageStaticData = getStorageDomain().getStorageStaticData(); DbFacade.getInstance().getStorageDomainStaticDao().save(storageStaticData); // create default disk profile for type master or data storage domains if (storageStaticData.getStorageDomainType().isDataDomain()) { getDiskProfileDao().save(DiskProfileHelper.createDiskProfile(storageStaticData.getId(), storageStaticData.getStorageName())); } getCompensationContext().snapshotNewEntity(storageStaticData); StorageDomainDynamic newStorageDynamic = new StorageDomainDynamic(null, getStorageDomain().getId(), null); getReturnValue().setActionReturnValue(getStorageDomain().getId()); DbFacade.getInstance().getStorageDomainDynamicDao().save(newStorageDynamic); getCompensationContext().snapshotNewEntity(newStorageDynamic); getCompensationContext().stateChanged(); return null; }); } protected void updateStorageDomainDynamicFromIrs() { final StorageDomain sd = (StorageDomain) runVdsCommand(VDSCommandType.GetStorageDomainStats, new GetStorageDomainStatsVDSCommandParameters(getVds().getId(), getStorageDomain().getId())) .getReturnValue(); TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntity(getStorageDomain().getStorageDynamicData()); DbFacade.getInstance().getStorageDomainDynamicDao().update(sd.getStorageDynamicData()); getCompensationContext().stateChanged(); return null; }); } @Override protected void executeCommand() { initializeStorageDomain(); addStorageDomainInDb(); // check connection to storage Pair<Boolean, Integer> connectReturnValue = connectStorage(); if (!connectReturnValue.getFirst()) { EngineFault fault = new EngineFault(); fault.setError(EngineError.forValue(connectReturnValue.getSecond())); getReturnValue().setFault(fault); setSucceeded(false); } else if (addStorageDomainInIrs()) { updateStorageDomainDynamicFromIrs(); setSucceeded(true); } } protected Pair<Boolean, Integer> connectStorage() { String connectionId = getStorageDomain().getStorage(); StorageServerConnections connection = getStorageServerConnectionDao().get(connectionId); Map<String, String> result = (Map<String, String>) runVdsCommand( VDSCommandType.ConnectStorageServer, new StorageServerConnectionManagementVDSParameters(getParameters().getVdsId(), Guid.Empty, connection.getStorageType(), new ArrayList<>(Collections.singletonList(connection)))) .getReturnValue(); return new Pair<>(StorageHelperDirector.getInstance() .getItem(connection.getStorageType()) .isConnectSucceeded(result, Collections.singletonList(connection)), Integer.parseInt(result.values().iterator().next())); } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_ADD_STORAGE_DOMAIN : AuditLogType.USER_ADD_STORAGE_DOMAIN_FAILED; } @Override protected boolean validate() { if (!super.validate() || !initializeVds() || !checkStorageDomainNameLengthValid()) { return false; } if (isStorageWithSameNameExists()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NAME_ALREADY_EXIST); } if (getStorageDomain().getStorageDomainType() == StorageDomainType.ISO && !getStorageDomain().getStorageType().isFileDomain()) { addValidationMessageVariable("domainType", StorageConstants.ISO); addValidationMessageVariable("storageTypes", StorageConstants.FILE); return failValidation(EngineMessage.ACTION_TYPE_FAILED_DOMAIN_TYPE_CAN_BE_CREATED_ONLY_ON_SPECIFIC_STORAGE_DOMAINS); } if (getStorageDomain().getStorageDomainType() == StorageDomainType.ImportExport && getStorageDomain().getStorageType().isBlockDomain()) { addValidationMessageVariable("domainType", StorageConstants.EXPORT); addValidationMessageVariable("storageTypes", StorageConstants.FILE); return failValidation(EngineMessage.ACTION_TYPE_FAILED_DOMAIN_TYPE_CAN_BE_CREATED_ONLY_ON_SPECIFIC_STORAGE_DOMAINS); } if (getStorageDomain().getStorageDomainType() == StorageDomainType.Master) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); } if (!Guid.isNullOrEmpty(getParameters().getStoragePoolId()) && getTargetStoragePool() == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); } ensureStorageFormatInitialized(); StorageDomainToPoolRelationValidator storageDomainToPoolRelationValidator = getAttachDomainValidator(); StorageDomainValidator sdValidator = getStorageDomainValidator(); if ( !validate(storageDomainToPoolRelationValidator.isStorageDomainFormatCorrectForDC()) || !validate(sdValidator.isStorageFormatCompatibleWithDomain()) ) { return false; } return canAddDomain(); } private void ensureStorageFormatInitialized() { StorageDomain sd = getStorageDomain(); if (sd.getStorageFormat() == null) { if (sd.getStorageDomainType().isDataDomain()) { StoragePool sp = getTargetStoragePool(); if (sp != null) { sd.setStorageFormat(VersionStorageFormatUtil.getPreferredForVersion( sp.getCompatibilityVersion(), sd.getStorageType()) ); } } else { sd.setStorageFormat(StorageFormatType.V1); } } } private StoragePool getTargetStoragePool() { StoragePool targetStoragePool = getStoragePool(); if (targetStoragePool == null) { targetStoragePool = getStoragePoolDao().get(getVds().getStoragePoolId()); } return targetStoragePool; } protected String getStorageArgs() { return getStorageDomain().getStorage(); } protected abstract boolean canAddDomain(); @Override public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.singletonList(new PermissionSubject(SYSTEM_OBJECT_ID, VdcObjectType.System, getActionType().getActionGroup())); } @Override protected List<Class<?>> getValidationGroups() { addValidationGroup(CreateEntity.class); return super.getValidationGroups(); } @Override protected void setActionMessageParameters() { super.setActionMessageParameters(); addValidationMessage(EngineMessage.VAR__ACTION__ADD); } public StorageDomainToPoolRelationValidator getAttachDomainValidator() { return new StorageDomainToPoolRelationValidator(getStorageDomain().getStorageStaticData(), getTargetStoragePool()); } public StorageDomainValidator getStorageDomainValidator() { return new StorageDomainValidator(getStorageDomain()); } }
{ "content_hash": "ad7afab89b518319e88551c68de02674", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 164, "avg_line_length": 46.774809160305345, "alnum_prop": 0.701264789881681, "repo_name": "OpenUniversity/ovirt-engine", "id": "68e0e578cec70e29779842d12a8d60997ca71551", "size": "12255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/domain/AddStorageDomainCommand.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "8958" }, { "name": "CSS", "bytes": "60941" }, { "name": "Groff", "bytes": "7443" }, { "name": "HTML", "bytes": "16218" }, { "name": "Java", "bytes": "33662996" }, { "name": "JavaScript", "bytes": "1034" }, { "name": "Makefile", "bytes": "22589" }, { "name": "PLSQL", "bytes": "257864" }, { "name": "PLpgSQL", "bytes": "78999" }, { "name": "Python", "bytes": "903984" }, { "name": "SQLPL", "bytes": "203816" }, { "name": "Shell", "bytes": "153157" }, { "name": "XSLT", "bytes": "54683" } ], "symlink_target": "" }
#tracerPlugin textarea, #tracerPlugin input, #tracerPlugin button { /* Remove blue input highlight */ outline: none; } #tracerPlugin .control-bar { background: rgba(0, 0, 0, 0.05); height: 31px; border-bottom: solid 1px #ccc; padding: 4px 10px; overflow: hidden; } #tracerPlugin .control-bar * { margin-bottom: 10px; } #tracerPlugin .control-bar .control-url-filter input[type=text], #tracerPlugin .control-bar .control-search-filter input[type=text] { width: 120px; padding: 3px 5px; } #tracerPlugin .control-bar .control-max-requests input[type=number] { width: 50px; padding: 3px 5px; } #tracerPlugin .control-bar .control-url-filter, #tracerPlugin .control-bar .control-search-filter, #tracerPlugin .control-bar .control-max-requests { margin-right: 8px; } #tracerPlugin input[type="button"], #tracerPlugin button { border: solid 1px #ccc; background-color: white; border-radius: 3px; } #tracerPlugin input[type="button"]:active, #tracerPlugin button:active { background-color: #d9d9d9; } #tracerPlugin .tab-filter-wrapper input { height: 1.3rem; padding: 0 .25rem; float: left; width: 40%; } #tracerPlugin .request-info { overflow: hidden; text-overflow: ellipsis; } #tracerPlugin .download-button { margin-left: 0; float: left; margin-right: 1rem; } #tracerPlugin input.tracer-set--package { width: 400px !important; } #tracerPlugin .tracer-log-list--entry--caller-button { color: #999; margin-bottom: .25rem; margin-right: .25rem; } #tracerPlugin .tracer-log-list--entry--caller-button:active { color: #666; } #tracerPlugin .tracer-log-list--entry--caller { display: none; list-style: none; margin: .5rem 0 0 0; padding-left: .5rem; } #tracerPlugin .tracer-log-list--entry--caller li { border: 0; padding: .25rem; font-size: .95em; } #tracerPlugin .logger-names--list { list-style: none; margin: .5rem 0; padding: 0; } #tracerPlugin .logger-names--list li { list-style: none; margin: .5rem; } /* Mini Options */ #tracerPlugin .mini-options--button { float: right; } #tracerPlugin #mini-options { position: absolute; padding: 1em; background-color: #eee; color: black; z-index: 100000; right: 0; top: 0; border-top: dashed 1px #9B9B9B; border-left: solid 1px #9B9B9B; width: 720px; height: 100%; overflow-y: auto; } #tracerPlugin #mini-options .mini-options--close { float: right; } #tracerPlugin #mini-options .tracer-set { margin: .25rem 0; } #tracerPlugin #mini-options .field-wrapper label { display: inline-block; width: 150px; } #tracerPlugin #mini-options .field-wrapper input[type=text] { width: 280px; padding: 2px; } #tracerPlugin #mini-options .field-wrapper .tracer-set input[type=text] { width: 500px; padding: 2px; } #tracerPlugin #mini-options .tracer-set--add { margin-top: .5rem; } #tracerPlugin .tracer-log-list p { padding: 0; margin: 0 0 .5rem 0; line-height: 1.2rem; } #tracerPlugin .tracer-log-list li { border-bottom: dotted 1px #eee; padding: 10px 0; margin-left: 1rem; } #tracerPlugin .tracer-log-list li li { padding: .25rem 0; border-bottom-width: 0; } #tracerPlugin .tracer-log-list .params-list { margin-left: -10px; padding-bottom: 0; margin-bottom: 0; } #tracerPlugin .cta { color: white; background-color: forestgreen; border: 0; border-radius: 2rem; padding: .75rem 1.5rem; font-size: 1rem; cursor: pointer; box-shadow: 0 1px 2px #666; margin-bottom: 2px; } #tracerPlugin .cta:active { margin-top: 2px; margin-bottom: 0; box-shadow: 0 0 0 white; background-color: forestgreen; } /* Error overlay */ .error-overlay { border-top: solid 1px #666; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.80); color: white; z-index: 1000000000; } .error-overlay a { color: forestgreen; } .error-overlay .error-message { background-color: #fcfcfc; margin: 3rem auto 0 auto; color: #333; width: 800px; font-size: .8rem; padding: .5rem 2rem 2.5rem 2rem; border-radius: 3px; border: solid 1px #333; }
{ "content_hash": "05e6b3f694f40bed7c2438084abef571", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 73, "avg_line_length": 18.915555555555557, "alnum_prop": 0.6585996240601504, "repo_name": "Adobe-Consulting-Services/aem-chrome-plugin", "id": "5a6defeb669fd8ea4bb752c55fdcccfd28262256", "size": "4894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/stylesheets/tracer-plugin/tracer.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17159" }, { "name": "HTML", "bytes": "41316" }, { "name": "JavaScript", "bytes": "116038" } ], "symlink_target": "" }
package io.datalayer.data.yaml.resolver; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.resolver.Resolver; public class CustomResolver extends Resolver { /* * do not resolve float and timestamp */ protected void addImplicitResolvers() { addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO"); // addImplicitResolver(Tags.FLOAT, FLOAT, "-+0123456789."); addImplicitResolver(Tag.INT, INT, "-+0123456789"); addImplicitResolver(Tag.MERGE, MERGE, "<"); addImplicitResolver(Tag.NULL, NULL, "~nN\0"); addImplicitResolver(Tag.NULL, EMPTY, null); // addImplicitResolver(Tags.TIMESTAMP, TIMESTAMP, "0123456789"); addImplicitResolver(Tag.VALUE, VALUE, "="); } }
{ "content_hash": "a274b6928a2311dfaafcfd12279b17f2", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 72, "avg_line_length": 34.18181818181818, "alnum_prop": 0.675531914893617, "repo_name": "echalkpad/t4f-data", "id": "7a0c1578b08c2c16a7eea7a438cf9caf5bdca8ea", "size": "1940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "structure/yaml/src/test/java/io/datalayer/data/yaml/resolver/CustomResolver.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "21510" }, { "name": "C", "bytes": "4224" }, { "name": "C++", "bytes": "11388421" }, { "name": "CSS", "bytes": "38929" }, { "name": "Clojure", "bytes": "13986" }, { "name": "Emacs Lisp", "bytes": "15596" }, { "name": "Erlang", "bytes": "11979" }, { "name": "Java", "bytes": "9263765" }, { "name": "JavaScript", "bytes": "386783" }, { "name": "Makefile", "bytes": "423433" }, { "name": "PHP", "bytes": "7959" }, { "name": "Perl", "bytes": "62480" }, { "name": "PigLatin", "bytes": "4125" }, { "name": "Prolog", "bytes": "8643" }, { "name": "Python", "bytes": "1435440" }, { "name": "R", "bytes": "120761" }, { "name": "Ruby", "bytes": "17850" }, { "name": "Scala", "bytes": "444582" }, { "name": "Shell", "bytes": "3247622" }, { "name": "TeX", "bytes": "10853" }, { "name": "Thrift", "bytes": "5968" }, { "name": "VimL", "bytes": "7505" }, { "name": "Visual Basic", "bytes": "1223" }, { "name": "XSLT", "bytes": "19271" } ], "symlink_target": "" }
// TypeScript Version: 2.0 /** * Computes the hypotenuse avoiding overflow and underflow (single-precision). * * @param x - number * @param y - number * @returns hypotenuse * * @example * var h = hypotf( -5.0, 12.0 ); * // returns 13.0 * * @example * var h = hypotf( NaN, 12.0 ); * // returns NaN * * @example * var h = hypotf( -0.0, -0.0 ); * // returns 0.0 */ declare function hypotf( x: number, y: number ): number; // EXPORTS // export = hypotf;
{ "content_hash": "4222bd2b8a4ef9da10f11fdd50dc20e9", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 77, "avg_line_length": 15.724137931034482, "alnum_prop": 0.6118421052631579, "repo_name": "stdlib-js/stdlib", "id": "e03bbf81bcfd55c2148e07d442b10df82e2ba4f1", "size": "1071", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/node_modules/@stdlib/math/base/special/hypotf/docs/types/index.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "21739" }, { "name": "C", "bytes": "15336495" }, { "name": "C++", "bytes": "1349482" }, { "name": "CSS", "bytes": "58039" }, { "name": "Fortran", "bytes": "198059" }, { "name": "HTML", "bytes": "56181" }, { "name": "Handlebars", "bytes": "16114" }, { "name": "JavaScript", "bytes": "85975525" }, { "name": "Julia", "bytes": "1508654" }, { "name": "Makefile", "bytes": "4806816" }, { "name": "Python", "bytes": "3343697" }, { "name": "R", "bytes": "576612" }, { "name": "Shell", "bytes": "559315" }, { "name": "TypeScript", "bytes": "19309407" }, { "name": "WebAssembly", "bytes": "5980" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="da" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Swiscoin</source> <translation>Om Swiscoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Swiscoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Swiscoin&lt;/b&gt; version</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> Dette program er ekperimentielt. Det er gjort tilgængeligt under MIT/X11-softwarelicensen. Se den tilhørende fil &quot;COPYING&quot; eller http://www.opensource.org/licenses/mit-license.php. Produktet indeholder software som er udviklet af OpenSSL Project til brug i OpenSSL Toolkit (http://www.openssl.org/), kryptografisk software skrevet af Eric Young (eay@cryptsoft.com) og UPnP-software skrevet af Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The Swiscoin developers</source> <translation>Swiscoin-udviklerne</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adressebog</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dobbeltklik for at redigere adresse eller mærkat</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Opret en ny adresse</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopier den valgte adresse til systemets udklipsholder</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>Ny adresse</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Swiscoin 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>Dette er dine Swiscoin-adresser til at modtage betalinger med. Du kan give en forskellig adresse til hver afsender, så du kan holde styr på, hvem der betaler dig.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>Kopier adresse</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Vis QR-kode</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Swiscoin address</source> <translation>Underskriv en besked for at bevise, at en Swiscoin-adresse tilhører dig</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Underskriv besked</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Slet den markerede adresse fra listen</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Eksportér den aktuelle visning til en fil</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>Eksporter</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Swiscoin address</source> <translation>Efterprøv en besked for at sikre, at den er underskrevet med den angivne Swiscoin-adresse</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Efterprøv besked</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>Slet</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Swiscoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Disse er dine Swiscoin-adresser for at sende betalinger. Tjek altid beløb og modtageradresse, inden du sender swiscoins.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopier mærkat</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>Rediger</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Send swiscoins</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Eksporter adressebogsdata</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommasepareret fil (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Fejl under eksport</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til filen %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Mærkat</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ingen mærkat)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Adgangskodedialog</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Indtast adgangskode</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Ny adgangskode</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Gentag ny adgangskode</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>Indtast den nye adgangskode til tegnebogen.&lt;br/&gt;Brug venligst en adgangskode på &lt;b&gt;10 eller flere tilfældige tegn&lt;/b&gt; eller &lt;b&gt;otte eller flere ord&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Krypter tegnebog</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Denne funktion har brug for din tegnebogs adgangskode for at låse tegnebogen op.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Lås tegnebog op</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Denne funktion har brug for din tegnebogs adgangskode for at dekryptere tegnebogen.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dekrypter tegnebog</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Skift adgangskode</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Indtast den gamle og den nye adgangskode til tegnebogen.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bekræft tegnebogskryptering</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 SWISCOINS&lt;/b&gt;!</source> <translation>Advarsel: Hvis du krypterer din tegnebog og mister din adgangskode, vil du &lt;b&gt;MISTE ALLE DINE SWISCOINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Er du sikker på, at du ønsker at kryptere din tegnebog?</translation> </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>VIGTIGT: Enhver tidligere sikkerhedskopi, som du har lavet af tegnebogsfilen, bør blive erstattet af den nyligt genererede, krypterede tegnebogsfil. Af sikkerhedsmæssige årsager vil tidligere sikkerhedskopier af den ikke-krypterede tegnebogsfil blive ubrugelig i det øjeblik, du starter med at anvende den nye, krypterede tegnebog.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Advarsel: Caps Lock-tasten er aktiveret!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Tegnebog krypteret</translation> </message> <message> <location line="-56"/> <source>Swiscoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your swiscoins from being stolen by malware infecting your computer.</source> <translation>Swiscoin vil nu lukke for at gennemføre krypteringsprocessen. Husk på, at kryptering af din tegnebog vil ikke beskytte dine swiscoins fuldt ud mod at blive stjålet af malware på din computer.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Tegnebogskryptering mislykkedes</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Tegnebogskryptering mislykkedes på grund af en intern fejl. Din tegnebog blev ikke krypteret.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>De angivne adgangskoder stemmer ikke overens.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Tegnebogsoplåsning mislykkedes</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Den angivne adgangskode for tegnebogsdekrypteringen er forkert.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Tegnebogsdekryptering mislykkedes</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Tegnebogens adgangskode blev ændret.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Underskriv besked...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synkroniserer med netværk...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>Oversigt</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Vis generel oversigt over tegnebog</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>Transaktioner</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Gennemse transaktionshistorik</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Rediger listen over gemte adresser og mærkater</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Vis listen over adresser for at modtage betalinger</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Luk</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Afslut program</translation> </message> <message> <location line="+4"/> <source>Show information about Swiscoin</source> <translation>Vis informationer om Swiscoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Om Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Vis informationer om Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>Indstillinger...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>Krypter tegnebog...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Sikkerhedskopier tegnebog...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Skift adgangskode...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importerer blokke fra disken...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Genindekserer blokke på disken...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Swiscoin address</source> <translation>Send swiscoins til en Swiscoin-adresse</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Swiscoin</source> <translation>Rediger konfigurationsindstillinger af Swiscoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Lav sikkerhedskopi af tegnebogen til et andet sted</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Skift adgangskode anvendt til tegnebogskryptering</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Fejlsøgningsvindue</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Åbn fejlsøgnings- og diagnosticeringskonsollen</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Efterprøv besked...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Swiscoin</source> <translation>Swiscoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Tegnebog</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>Send</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>Modtag</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>Adresser</translation> </message> <message> <location line="+22"/> <source>&amp;About Swiscoin</source> <translation>Om Swiscoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Vis/skjul</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Vis eller skjul hovedvinduet</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Krypter de private nøgler, der hører til din tegnebog</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Swiscoin addresses to prove you own them</source> <translation>Underskriv beskeder med dine Swiscoin-adresser for at bevise, at de tilhører dig</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Swiscoin addresses</source> <translation>Efterprøv beskeder for at sikre, at de er underskrevet med de(n) angivne Swiscoin-adresse(r)</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>Fil</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>Indstillinger</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>Hjælp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Faneværktøjslinje</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnetværk]</translation> </message> <message> <location line="+47"/> <source>Swiscoin client</source> <translation>Swiscoin-klient</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Swiscoin network</source> <translation><numerusform>%n aktiv(e) forbindelse(r) til Swiscoin-netværket</numerusform><numerusform>%n aktiv(e) forbindelse(r) til Swiscoin-netværket</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Ingen blokkilde tilgængelig...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>%1 ud af %2 (estimeret) blokke af transaktionshistorikken er blevet behandlet.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>%1 blokke af transaktionshistorikken er blevet behandlet.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n time(r)</numerusform><numerusform>%n time(r)</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dag(e)</numerusform><numerusform>%n dag(e)</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n uge(r)</numerusform><numerusform>%n uge(r)</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 bagefter</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Senest modtagne blok blev genereret for %1 siden.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transaktioner herefter vil endnu ikke være synlige.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Fejl</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Advarsel</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Information</translation> </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>Transaktionen overskrider størrelsesgrænsen. Du kan stadig sende den for et gebyr på %1, hvilket går til de knuder, der behandler din transaktion og hjælper med at understøtte netværket. Vil du betale gebyret?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Opdateret</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Indhenter...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Bekræft transaktionsgebyr</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Afsendt transaktion</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Indgående transaktion</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dato: %1 Beløb: %2 Type: %3 Adresse: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI-håndtering</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Swiscoin address or malformed URI parameters.</source> <translation>URI kan ikke fortolkes! Dette kan skyldes en ugyldig Swiscoin-adresse eller misdannede URI-parametre.</translation> </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>Tegnebog er &lt;b&gt;krypteret&lt;/b&gt; og i øjeblikket &lt;b&gt;ulåst&lt;/b&gt;</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>Tegnebog er &lt;b&gt;krypteret&lt;/b&gt; og i øjeblikket &lt;b&gt;låst&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Swiscoin can no longer continue safely and will quit.</source> <translation>Der opstod en fatal fejl. Swiscoin kan ikke længere fortsætte sikkert og vil afslutte.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Netværksadvarsel</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Rediger adresse</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>Mærkat</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Mærkaten forbundet med denne post i adressebogen</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>Adresse</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>Adressen tilknyttet til denne post i adressebogen. Dette kan kun ændres for afsendelsesadresser.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Ny modtagelsesadresse</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Ny afsendelsesadresse</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Rediger modtagelsesadresse</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Rediger afsendelsesadresse</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Den indtastede adresse &quot;%1&quot; er allerede i adressebogen.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Swiscoin address.</source> <translation>Den indtastede adresse &quot;%1&quot; er ikke en gyldig Swiscoin-adresse.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kunne ikke låse tegnebog op.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Ny nøglegenerering mislykkedes.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Swiscoin-Qt</source> <translation>Swiscoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>version</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Anvendelse:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>kommandolinjetilvalg</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Brugergrænsefladeindstillinger</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Angiv sprog, f.eks &quot;de_DE&quot; (standard: systemlokalitet)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Start minimeret</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Vis opstartsbillede ved start (standard: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Indstillinger</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>Generelt</translation> </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>Valgfrit transaktionsgebyr pr. kB, der hjælper dine transaktioner med at blive behandlet hurtigt. De fleste transaktioner er på 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betal transaktionsgebyr</translation> </message> <message> <location line="+31"/> <source>Automatically start Swiscoin after logging in to the system.</source> <translation>Start Swiscoin automatisk, når der logges ind på systemet</translation> </message> <message> <location line="+3"/> <source>&amp;Start Swiscoin on system login</source> <translation>Start Swiscoin, når systemet startes</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Nulstil alle klientindstillinger til deres standard.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Nulstil indstillinger</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>Netværk</translation> </message> <message> <location line="+6"/> <source>Automatically open the Swiscoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Åbn Swiscoin-klientens port på routeren automatisk. Dette virker kun, når din router understøtter UPnP og UPnP er aktiveret.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Konfigurer port vha. UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Swiscoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Opret forbindelse til Swiscoin-netværket via en SOCKS-proxy (f.eks. ved tilslutning gennem Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Forbind gennem SOCKS-proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy-IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-adressen på proxyen (f.eks. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porten på proxyen (f.eks. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS-version</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS-version af proxyen (f.eks. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>Vindue</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Vis kun et statusikon efter minimering af vinduet.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>Minimer til statusfeltet i stedet for proceslinjen</translation> </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>Minimer i stedet for at afslutte programmet, når vinduet lukkes. Når denne indstilling er valgt, vil programmet kun blive lukket, når du har valgt Afslut i menuen.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Minimer ved lukning</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Visning</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Brugergrænsefladesprog:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Swiscoin.</source> <translation>Brugergrænsefladesproget kan angives her. Denne indstilling træder først i kraft, når Swiscoin genstartes.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>Enhed at vise beløb i:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Vælg den standard underopdelingsenhed, som skal vises i brugergrænsefladen og ved afsendelse af swiscoins.</translation> </message> <message> <location line="+9"/> <source>Whether to show Swiscoin addresses in the transaction list or not.</source> <translation>Afgør hvorvidt Swiscoin-adresser skal vises i transaktionslisten eller ej.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Vis adresser i transaktionsliste</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>Annuller</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>Anvend</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>standard</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Bekræft nulstilling af indstillinger</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Nogle indstillinger kan kræve, at klienten genstartes, før de træder i kraft.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Ønsker du at fortsætte?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Advarsel</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Swiscoin.</source> <translation>Denne indstilling træder i kraft, efter Swiscoin genstartes.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Ugyldig proxy-adresse</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formular</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Swiscoin network after a connection is established, but this process has not completed yet.</source> <translation>Den viste information kan være forældet. Din tegnebog synkroniserer automatisk med Swiscoin-netværket, når en forbindelse etableres, men denne proces er ikke gennemført endnu.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Ubekræftede:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Tegnebog</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Umodne:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Udvunden saldo, som endnu ikke er modnet</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Nyeste transaktioner&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Din nuværende saldo</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>Summen af transaktioner, der endnu ikke er bekræftet og endnu ikke er inkluderet i den nuværende saldo</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>ikke synkroniseret</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start swiscoin: click-to-pay handler</source> <translation>Kan ikke starte swiscoin: click-to-pay-håndtering</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-kode-dialog</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Anmod om betaling</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Beløb:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Mærkat:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Besked:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Gem som...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Fejl ved kodning fra URI til QR-kode</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Det indtastede beløb er ugyldig, tjek venligst.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulterende URI var for lang; prøv at forkorte teksten til mærkaten/beskeden.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Gem QR-kode</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-billeder (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Klientnavn</translation> </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>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Klientversion</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>Information</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Anvendt OpenSSL-version</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Opstartstid</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Netværk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Antal forbindelser</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Tilsluttet testnetværk</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokkæde</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Nuværende antal blokke</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Estimeret antal blokke</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tidsstempel for seneste blok</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>Åbn</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Kommandolinjetilvalg</translation> </message> <message> <location line="+7"/> <source>Show the Swiscoin-Qt help message to get a list with possible Swiscoin command-line options.</source> <translation>Vis Swiscoin-Qt-hjælpebeskeden for at få en liste over de tilgængelige Swiscoin-kommandolinjeindstillinger.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Vis</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Konsol</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Byggedato</translation> </message> <message> <location line="-104"/> <source>Swiscoin - Debug window</source> <translation>Swiscoin - Fejlsøgningsvindue</translation> </message> <message> <location line="+25"/> <source>Swiscoin Core</source> <translation>Swiscoin Core</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Fejlsøgningslogfil</translation> </message> <message> <location line="+7"/> <source>Open the Swiscoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Åbn Swiscoin-fejlsøgningslogfilen fra det nuværende datakatalog. Dette kan tage nogle få sekunder for en store logfiler.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Ryd konsol</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Swiscoin RPC console.</source> <translation>Velkommen til Swiscoin RPC-konsollen</translation> </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>Brug op og ned-piletasterne til at navigere historikken og &lt;b&gt;Ctrl-L&lt;/b&gt; til at rydde skærmen.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Tast &lt;b&gt;help&lt;/b&gt; for en oversigt over de tilgængelige kommandoer.</translation> </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>Send swiscoins</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Send til flere modtagere på en gang</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Tilføj modtager</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Fjern alle transaktionsfelter</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Ryd alle</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</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>Bekræft afsendelsen</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>Afsend</translation> </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; til %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bekræft afsendelse af swiscoins</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Er du sikker på, at du vil sende %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> og </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Modtagerens adresse er ikke gyldig. Tjek venligst adressen igen.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Beløbet til betaling skal være større end 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Beløbet overstiger din saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totalen overstiger din saldo, når %1 transaktionsgebyr er inkluderet.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Duplikeret adresse fundet. Du kan kun sende til hver adresse en gang pr. afsendelse.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Fejl: Oprettelse af transaktionen mislykkedes!</translation> </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>Fejl: Transaktionen blev afvist. Dette kan ske, hvis nogle af dine swiscoins i din tegnebog allerede er brugt, som hvis du brugte en kopi af wallet.dat og dine swiscoins er blevet brugt i kopien, men ikke er markeret som brugt her.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formular</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Beløb:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betal til:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</source> <translation>Swiscoin-adressen som betalingen skal sendes til (f.eks. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</translation> </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>Indtast en mærkat for denne adresse for at føje den til din adressebog</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Mærkat:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Vælg adresse fra adressebog</translation> </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>Indsæt adresse fra udklipsholderen</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>Fjern denne modtager</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Swiscoin address (e.g. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</source> <translation>Indtast en Swiscoin-adresse (f.eks. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Underskrifter - Underskriv/efterprøv en besked</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>Underskriv besked</translation> </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>Du kan underskrive beskeder med dine Swiscoin-adresser for at bevise, at de tilhører dig. Pas på ikke at underskrive noget vagt, da phisingangreb kan narre dig til at overdrage din identitet. Underskriv kun fuldt detaljerede udsagn, du er enig i.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</source> <translation>Swiscoin-adressen som beskeden skal underskrives med (f.eks. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Vælg adresse fra adressebog</translation> </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>Indsæt adresse fra udklipsholderen</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>Indtast beskeden, du ønsker at underskrive</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Underskrift</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopier den nuværende underskrift til systemets udklipsholder</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Swiscoin address</source> <translation>Underskriv denne besked for at bevise, at Swiscoin-adressen tilhører dig</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Underskriv besked</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Nulstil alle underskriv besked-indtastningsfelter</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Ryd alle</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Efterprøv besked</translation> </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>Indtast den underskrevne adresse, beskeden (inkluder linjeskift, mellemrum mv. nøjagtigt, som de fremgår) og underskriften for at efterprøve beskeden. Vær forsigtig med ikke at lægge mere i underskriften end besked selv, så du undgår at blive narret af et man-in-the-middle-angreb.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</source> <translation>Swiscoin-adressen som beskeden er underskrevet med (f.eks. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Swiscoin address</source> <translation>Efterprøv beskeden for at sikre, at den er underskrevet med den angivne Swiscoin-adresse</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Efterprøv besked</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Nulstil alle efterprøv besked-indtastningsfelter</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Swiscoin address (e.g. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</source> <translation>Indtast en Swiscoin-adresse (f.eks. Sc32qcrCnU1nQwNHCwFGtzDaTJh32tMe67)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klik &quot;Underskriv besked&quot; for at generere underskriften</translation> </message> <message> <location line="+3"/> <source>Enter Swiscoin signature</source> <translation>Indtast Swiscoin-underskriften</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Den indtastede adresse er ugyldig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Tjek venligst adressen, og forsøg igen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Den indtastede adresse henviser ikke til en nøgle.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Tegnebogsoplåsning annulleret.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Den private nøgle for den indtastede adresse er ikke tilgængelig.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Underskrivning af besked mislykkedes.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Besked underskrevet.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Underskriften kunne ikke afkodes.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Tjek venligst underskriften, og forsøg igen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Underskriften matcher ikke beskedens indhold.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Efterprøvelse af besked mislykkedes.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Besked efterprøvet.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Swiscoin developers</source> <translation>Swiscoin-udviklerne</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Åben indtil %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/ubekræftet</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bekræftelser</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitteret igennem %n knude(r)</numerusform><numerusform>, transmitteret igennem %n knude(r)</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Kilde</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Genereret</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Fra</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Til</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>egen adresse</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>mærkat</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kredit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>modner efter yderligere %n blok(ke)</numerusform><numerusform>modner efter yderligere %n blok(ke)</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>ikke accepteret</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transaktionsgebyr</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Nettobeløb</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Besked</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Kommentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaktionens ID</translation> </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>Genererede swiscoins skal vente 120 blokke, før de kan blive brugt. Da du genererede denne blok, blev den transmitteret til netværket for at blive føjet til blokkæden. Hvis det mislykkes at komme ind i kæden, vil den skifte til &quot;ikke godkendt&quot; og ikke blive kunne bruges. Dette kan lejlighedsvis ske, hvis en anden knude genererer en blok inden for få sekunder af din.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Fejlsøgningsinformation</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transaktion</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Beløb</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>sand</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falsk</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, er ikke blevet transmitteret endnu</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Åben %n blok yderligere</numerusform><numerusform>Åben %n blokke yderligere</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>ukendt</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transaktionsdetaljer</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Denne rude viser en detaljeret beskrivelse af transaktionen</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Beløb</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Åben %n blok(ke) yderligere</numerusform><numerusform>Åben %n blok(ke) yderligere</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Åben indtil %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 bekræftelser)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Ubekræftet (%1 af %2 bekræftelser)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Bekræftet (%1 bekræftelser)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Udvunden saldo, som vil være tilgængelig, når den modner efter yderligere %n blok(ke)</numerusform><numerusform>Udvunden saldo, som vil være tilgængelig, når den modner efter yderligere %n blok(ke)</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>Denne blok blev ikke modtaget af nogen andre knuder og vil formentlig ikke blive accepteret!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Genereret, men ikke accepteret</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Modtaget med</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Modtaget fra</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betaling til dig selv</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Udvundne</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>Transaktionsstatus. Hold musen over dette felt for at vise antallet af bekræftelser.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Dato og klokkeslæt for modtagelse af transaktionen.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Transaktionstype.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Destinationsadresse for transaktion.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Beløb fjernet eller tilføjet balance.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alle</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>I dag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Denne uge</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Denne måned</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Sidste måned</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Dette år</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Interval...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Modtaget med</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Til dig selv</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Udvundne</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Andet</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Indtast adresse eller mærkat for at søge</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimumsbeløb</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopier adresse</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopier mærkat</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopier beløb</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopier transaktionens ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Rediger mærkat</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Vis transaktionsdetaljer</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Eksporter transaktionsdata</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommasepareret fil (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bekræftet</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Mærkat</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Beløb</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fejl under eksport</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til filen %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Interval:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>til</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Send swiscoins</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>Eksporter</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Eksportér den aktuelle visning til en fil</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Sikkerhedskopier tegnebog</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Tegnebogsdata (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Foretagelse af sikkerhedskopi fejlede</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Der opstod en fejl i forbindelse med at gemme tegnebogsdata til det nye sted</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Sikkerhedskopieret problemfri</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Tegnebogsdata blev problemfrit gemt til det nye sted.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Swiscoin version</source> <translation>Swiscoin-version</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Anvendelse:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or swiscoind</source> <translation>Send kommando til -server eller swiscoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Liste over kommandoer</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Få hjælp til en kommando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Indstillinger:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: swiscoin.conf)</source> <translation>Angiv konfigurationsfil (standard: swiscoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: swiscoind.pid)</source> <translation>Angiv pid-fil (default: swiscoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Angiv datakatalog</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Angiv databasecachestørrelse i megabytes (standard: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9229 or testnet: 19229)</source> <translation>Lyt til forbindelser på &lt;port&gt; (standard: 9229 eller testnetværk: 19229)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Oprethold højest &lt;n&gt; forbindelser til andre i netværket (standard: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Forbind til en knude for at modtage adresse, og afbryd</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Angiv din egen offentlige adresse</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Grænse for afbrydelse til dårlige forbindelser (standard: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Antal sekunder dårlige forbindelser skal vente før reetablering (standard: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Der opstod en fejl ved angivelse af RPC-porten %u til at lytte på IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9228 or testnet: 19228)</source> <translation>Lyt til JSON-RPC-forbindelser på &lt;port&gt; (standard: 9228 eller testnetværk: 19228)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accepter kommandolinje- og JSON-RPC-kommandoer</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Kør i baggrunden som en service, og accepter kommandoer</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Brug testnetværket</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepter forbindelser udefra (standard: 1 hvis hverken -proxy eller -connect)</translation> </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=swiscoinrpc 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;Swiscoin Alert&quot; admin@foo.com </source> <translation>%s, du skal angive en RPC-adgangskode i konfigurationsfilen: %s Det anbefales, at du bruger nedenstående, tilfældige adgangskode: rpcuser=swiscoinrpc rpcpassword=%s (du behøver ikke huske denne adgangskode) Brugernavnet og adgangskode MÅ IKKE være det samme. Hvis filen ikke eksisterer, opret den og giv ingen andre end ejeren læserettighed. Det anbefales også at angive alertnotify, så du påmindes om problemer; f.eks.: alertnotify=echo %%s | mail -s &quot;Swiscoin Alert&quot; admin@foo.com </translation> </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>Der opstod en fejl ved angivelse af RPC-porten %u til at lytte på IPv6, falder tilbage til IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Tildel til den givne adresse og lyt altid på den. Brug [vært]:port-notation for IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Swiscoin is probably already running.</source> <translation>Kan ikke opnå lås på datakatalog %s. Swiscoin er sandsynligvis allerede startet.</translation> </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>Fejl: Transaktionen blev afvist. Dette kan ske, hvis nogle af dine swiscoins i din tegnebog allerede er brugt, som hvis du brugte en kopi af wallet.dat og dine swiscoins er blevet brugt i kopien, men ikke er markeret som brugt her.</translation> </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>Fejl: Denne transaktion kræver et transaktionsgebyr på minimum %s pga. dens størrelse, kompleksitet eller anvendelse af nyligt modtagne swiscoins!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Udfør kommando, når en relevant advarsel modtages (%s i kommandoen erstattes med beskeden)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Udfør kommando, når en transaktion i tegnebogen ændres (%s i kommandoen erstattes med TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Angiv maksimumstørrelse for høj prioritet/lavt gebyr-transaktioner i bytes (standard: 27000)</translation> </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>Dette er en foreløbig testudgivelse - brug på eget ansvar - brug ikke til udvinding eller handelsprogrammer</translation> </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>Advarsel: -paytxfee er sat meget højt! Dette er det gebyr du vil betale, hvis du sender en transaktion.</translation> </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>Advarsel: Viste transaktioner kan være ukorrekte! Du eller andre knuder kan have behov for at opgradere.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Swiscoin will not work properly.</source> <translation>Advarsel: Undersøg venligst, at din computers dato og klokkeslæt er korrekt indstillet! Hvis der er fejl i disse, vil Swiscoin ikke fungere korrekt.</translation> </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>Advarsel: fejl under læsning af wallet.dat! Alle nøgler blev læst korrekt, men transaktionsdata eller adressebogsposter kan mangle eller være forkerte.</translation> </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>Advarsel: wallet.dat ødelagt, data reddet! Oprindelig wallet.net gemt som wallet.{timestamp}.bak i %s; hvis din saldo eller dine transaktioner er forkert, bør du genskabe fra en sikkerhedskopi.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Forsøg at genskabe private nøgler fra ødelagt wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Blokoprettelsestilvalg:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Tilslut kun til de(n) angivne knude(r)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Ødelagt blokdatabase opdaget</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Find egen IP-adresse (standard: 1 når lytter og ingen -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Ønsker du at genbygge blokdatabasen nu?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Klargøring af blokdatabase mislykkedes</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Klargøring af tegnebogsdatabasemiljøet %s mislykkedes!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Indlæsning af blokdatabase mislykkedes</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Åbning af blokdatabase mislykkedes</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Fejl: Mangel på ledig diskplads!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Fejl: Tegnebog låst, kan ikke oprette transaktion!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Fejl: systemfejl: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Lytning på enhver port mislykkedes. Brug -listen=0, hvis du ønsker dette.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Læsning af blokinformation mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Læsning af blok mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Synkronisering af blokindeks mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Skrivning af blokindeks mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Skrivning af blokinformation mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Skrivning af blok mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Skriving af filinformation mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Skrivning af swiscoin-database mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Skrivning af transaktionsindeks mislykkedes</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Skrivning af genskabelsesdata mislykkedes</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Find ligeværdige ved DNS-opslag (standard: 1 hvis ikke -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Generer swiscoins (standard: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Antal blokke som tjekkes ved opstart (0=alle, standard: 288)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Grundighed af efterprøvning af blokke (0-4, standard: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>For få tilgængelige fildeskriptorer.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Genbyg blokkædeindeks fra nuværende blk000??.dat filer</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Angiv antallet af tråde til at håndtere RPC-kald (standard: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Efterprøver blokke...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Efterprøver tegnebog...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importerer blokke fra ekstern blk000??.dat fil</translation> </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>Angiv nummeret af skriptefterprøvningstråde (op til 16, 0 = automatisk, &lt;0 = efterlad det antal kerner tilgængelige, standard: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Information</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Ugyldig -tor adresse: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ugyldigt beløb til -minrelaytxfee=&lt;beløb&gt;:&apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ugyldigt beløb til -mintxfee=&lt;beløb&gt;:&apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Vedligehold et komplet transaktionsindeks (standard: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maksimum for modtagelsesbuffer pr. forbindelse, &lt;n&gt;*1000 bytes (standard: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maksimum for afsendelsesbuffer pr. forbindelse, &lt;n&gt;*1000 bytes (standard: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Accepter kun blokkæde, som matcher indbyggede kontrolposter (standard: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Tilslut kun til knuder i netværk &lt;net&gt; (IPv4, IPv6 eller Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Skriv ekstra fejlsøgningsinformation. Indebærer alle andre -debug* tilvalg</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Skriv ekstra netværksfejlsøgningsinformation</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Tilføj fejlsøgningsoutput med tidsstempel</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Swiscoin Wiki for SSL setup instructions)</source> <translation>SSL-indstillinger: (se Swiscoin Wiki for SSL-opsætningsinstruktioner)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Angiv version af SOCKS-proxyen (4-5, standard: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Send sporings-/fejlsøgningsinformation til konsollen i stedet for debug.log filen</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Send sporings-/fejlsøgningsinformation til fejlsøgningprogrammet</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Angiv maksimumblokstørrelse i bytes (standard: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Angiv minimumsblokstørrelse i bytes (standard: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Formindsk debug.log filen ved klientopstart (standard: 1 hvis ikke -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Underskrift af transaktion mislykkedes</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Angiv tilslutningstimeout i millisekunder (standard: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Systemfejl: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Transaktionsbeløb er for lavt</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Transaktionsbeløb skal være positive</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transaktionen er for stor</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Forsøg at bruge UPnP til at konfigurere den lyttende port (standard: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Forsøg at bruge UPnP til at konfigurere den lyttende port (standard: 1 når lytter)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Brug proxy til at tilgå Tor Hidden Services (standard: som -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Brugernavn til JSON-RPC-forbindelser</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Advarsel</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Advarsel: Denne version er forældet, opgradering påkrævet!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Du skal genbygge databaserne med -reindex for at ændre -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat ødelagt, redning af data mislykkedes</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Adgangskode til JSON-RPC-forbindelser</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Tillad JSON-RPC-forbindelser fra bestemt IP-adresse</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Send kommandoer til knude, der kører på &lt;ip&gt; (standard: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Udfør kommando, når den bedste blok ændres (%s i kommandoen erstattes med blokhash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Opgrader tegnebog til seneste format</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Angiv nøglepoolstørrelse til &lt;n&gt; (standard: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Gennemsøg blokkæden for manglende tegnebogstransaktioner</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Brug OpenSSL (https) for JSON-RPC-forbindelser</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Servercertifikat-fil (standard: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Serverens private nøgle (standard: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Acceptable ciphers (standard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Denne hjælpebesked</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kunne ikke tildele %s på denne computer (bind returnerede fejl %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Tilslut via SOCKS-proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Tillad DNS-opslag for -addnode, -seednode og -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Indlæser adresser...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fejl ved indlæsning af wallet.dat: Tegnebog ødelagt</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Swiscoin</source> <translation>Fejl ved indlæsning af wallet.dat: Tegnebog kræver en nyere version af Swiscoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Swiscoin to complete</source> <translation>Det var nødvendigt at genskrive tegnebogen: genstart Swiscoin for at gennemføre</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Fejl ved indlæsning af wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ugyldig -proxy adresse: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Ukendt netværk anført i -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Ukendt -socks proxy-version: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kan ikke finde -bind adressen: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kan ikke finde -externalip adressen: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ugyldigt beløb for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Ugyldigt beløb</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Manglende dækning</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Indlæser blokindeks...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Tilføj en knude til at forbinde til og forsøg at holde forbindelsen åben</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Swiscoin is probably already running.</source> <translation>Kunne ikke tildele %s på denne computer. Swiscoin kører sikkert allerede.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Gebyr pr. kB, som skal tilføjes til transaktioner, du sender</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Indlæser tegnebog...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Kan ikke nedgradere tegnebog</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Kan ikke skrive standardadresse</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Genindlæser...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Indlæsning gennemført</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>For at bruge %s mulighed</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Fejl</translation> </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>Du skal angive rpcpassword=&lt;password&gt; i konfigurationsfilen: %s Hvis filen ikke eksisterer, opret den og giv ingen andre end ejeren læserettighed.</translation> </message> </context> </TS>
{ "content_hash": "447bdeecd617b19f91c3c26d3526a3a1", "timestamp": "", "source": "github", "line_count": 2938, "max_line_length": 413, "avg_line_length": 39.678352620830495, "alnum_prop": 0.6348788333690757, "repo_name": "SCNPay/swiscoin", "id": "e0050bbc0dd105bbdbea7b51294fc0ee003a8b8a", "size": "116952", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_da.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "32394" }, { "name": "C++", "bytes": "2610932" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "13384" }, { "name": "NSIS", "bytes": "5950" }, { "name": "Objective-C", "bytes": "1052" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "69714" }, { "name": "QMake", "bytes": "14770" }, { "name": "Roff", "bytes": "18284" }, { "name": "Shell", "bytes": "16339" } ], "symlink_target": "" }
layout: sermon series: "The Marks of a Healthy Church" title: "A Witnessing Church." date: "2014-02-23 11:00:00" audio: "http://media.coggesparish.com/2014-02-23 Simon Kirby.mp3" speaker: "Simon Kirby" speaker_info: "" duration: "33" youtube_videos: [""] vimeo_videos: [""] slides: ["http://media.coggesparish.com/2014-02-23 Simon Kirby.pdf"] files: [""] bible_passages: ["Matthew 28:16-20"] bible_links: ["Matthew 28:16-20&amp;version=NIVUK"] bible_videos: [""] bible_videos_links: [""] ---
{ "content_hash": "61d52f1d9a8e266a82461e47bf7a165a", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 68, "avg_line_length": 28.941176470588236, "alnum_prop": 0.693089430894309, "repo_name": "Cogges/cogges.github.io", "id": "d7f5db9ac670e90af6e8e538860b1fe0cee664f8", "size": "496", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2014-02-23-sermon.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19566" }, { "name": "HTML", "bytes": "7075172" }, { "name": "JavaScript", "bytes": "21326" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Parmelia cetrata var. subisidiosa Müll. Arg. ### Remarks null
{ "content_hash": "3940d1d4e67e71c98919b25b8824c79d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 44, "avg_line_length": 11.461538461538462, "alnum_prop": 0.7114093959731543, "repo_name": "mdoering/backbone", "id": "96ab94739040514b8ac4e44a6ea37e1af994494f", "size": "219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Parmeliaceae/Parmelia/Parmelia cetrata/Parmelia cetrata subisidiosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#include "tensorflow/compiler/xla/service/hlo_cse.h" #include <list> #include <map> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/container/inlined_vector.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_domain_map.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_instructions.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/platform/hash.h" namespace xla { namespace { // Find and combine identical constants. Constants are identical if they have // the same type and value. // // While we're here, also combine identical iota instructions, since they need // similar treatment. StatusOr<bool> CombineConstants(HloComputation* computation, bool is_layout_sensitive) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); // Map from ShortDebugString of the layoutless shape of the constant/iota to // the set of constant instructions with that shape. Layoutless shape is used // to bin possible common constants together to reduce number of constant // comparisons. If we end up having too many constant comparisons, a more // precise binning might have to be used. std::multimap<string, HloInstruction*> instrs; int64 combined = 0; auto inst_it = computation->instructions().begin(); while (inst_it != computation->instructions().end()) { HloInstruction* instruction = *inst_it; // Advance list iterator before loop body because iterator may be // invalidated due to deletion. ++inst_it; if (instruction->opcode() == HloOpcode::kConstant || instruction->opcode() == HloOpcode::kIota) { Shape shape = instruction->shape(); if (!is_layout_sensitive) { LayoutUtil::ClearLayout(&shape); } string shape_string = shape.ShortDebugString(); // Compare against all iotas/constants with the same shape. HloInstruction* match = nullptr; auto range = instrs.equal_range(shape_string); for (auto it = range.first; it != range.second; ++it) { if (instruction->opcode() == it->second->opcode() && domain_map->InSameDomain(it->second, instruction) && ((instruction->opcode() == HloOpcode::kConstant && instruction->literal() == it->second->literal()) || (instruction->opcode() == HloOpcode::kIota && Cast<HloIotaInstruction>(instruction)->iota_dimension() == Cast<HloIotaInstruction>(it->second)->iota_dimension()))) { match = it->second; break; } } if (match == nullptr) { instrs.emplace(shape_string, instruction); } else { // Match found, replace this instruction with the one in the multimap. TF_CHECK_OK(instruction->ReplaceAllUsesWith(match)); TF_CHECK_OK(computation->RemoveInstruction(instruction)); ++combined; } } } VLOG(4) << "Combined " << combined << " constants and iotas in " << computation->name() << " computation"; return combined > 0; } // An instruction is considered to be equivalent to another only if they // share the exact same set of operands. int64 CseHash(const HloInstruction* instruction) { int64 hash = std::hash<int64>()(static_cast<int64>(instruction->opcode())); auto c_hash = [](auto c) { return tensorflow::Hash64(reinterpret_cast<const char*>(c.data()), c.size() * sizeof(c[0])); }; auto proto_hash = [](auto proto) { return std::hash<int64>{}(proto.ByteSizeLong()); }; hash = tensorflow::Hash64Combine( hash, instruction->opcode() == HloOpcode::kGetTupleElement ? instruction->tuple_index() : c_hash(instruction->shape().dimensions())); for (auto operand : instruction->operands()) { hash = tensorflow::Hash64Combine(hash, operand->unique_id()); } for (auto c : instruction->called_computations()) { hash = tensorflow::Hash64Combine( hash, std::hash<int64>()( static_cast<int64>(c->root_instruction()->opcode()))); } switch (instruction->opcode()) { case HloOpcode::kSlice: return tensorflow::Hash64Combine( tensorflow::Hash64Combine(hash, c_hash(instruction->slice_starts())), c_hash(instruction->slice_strides())); case HloOpcode::kPad: return tensorflow::Hash64Combine( hash, proto_hash(instruction->padding_config())); case HloOpcode::kDot: return tensorflow::Hash64Combine( hash, proto_hash(instruction->dot_dimension_numbers())); case HloOpcode::kConvolution: return tensorflow::Hash64Combine( tensorflow::Hash64Combine( hash, proto_hash(instruction->convolution_dimension_numbers())), proto_hash(instruction->window())); case HloOpcode::kReduceWindow: return tensorflow::Hash64Combine(hash, proto_hash(instruction->window())); case HloOpcode::kConcatenate: case HloOpcode::kBroadcast: case HloOpcode::kTranspose: case HloOpcode::kReduce: return tensorflow::Hash64Combine(hash, c_hash(instruction->dimensions())); default: return hash; } } } // namespace StatusOr<bool> HloCSE::Run(HloModule* module) { bool changed = false; const std::function<bool(const HloInstruction*, const HloInstruction*)> eq_instructions = std::equal_to<const HloInstruction*>(); const std::function<bool(const HloComputation*, const HloComputation*)> eq_computations = [](const HloComputation* lhs, const HloComputation* rhs) { return *lhs == *rhs; }; auto cse_equal = [&](const HloInstruction* lhs, const HloInstruction* rhs) { return lhs->Identical(*rhs, eq_instructions, eq_computations, is_layout_sensitive_); }; for (auto* computation : module->computations()) { if (only_fusion_computations_ && !computation->IsFusionComputation()) { continue; } TF_ASSIGN_OR_RETURN(bool combined, CombineConstants(computation, is_layout_sensitive_)); changed |= combined; // HLO instructions are grouped into equivalency classes by using the // cse_equal predicate defined above. This set holds a representative // instruction for each class. absl::flat_hash_set<HloInstruction*, decltype(&CseHash), decltype(cse_equal)> representatives(/*N=*/computation->instruction_count() + 1, &CseHash, cse_equal); for (auto instruction : computation->MakeInstructionPostOrder()) { // If the instruction has zero operands (constants, parameters, etc.) skip // over it. if (instruction->operand_count() == 0 && instruction->opcode() != HloOpcode::kPartitionId && instruction->opcode() != HloOpcode::kReplicaId) { continue; } // Skip instructions which have side effects. if (instruction->HasSideEffect()) { continue; } auto pair = representatives.insert(instruction); if (!pair.second) { HloInstruction* equivalent_instruction = *pair.first; TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(equivalent_instruction)); TF_RETURN_IF_ERROR(computation->RemoveInstruction(instruction)); changed = true; continue; } } } return changed; } } // namespace xla
{ "content_hash": "2b8fa1d245d5040b0e8ffa9dca122e74", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 80, "avg_line_length": 39.044117647058826, "alnum_prop": 0.6557438794726931, "repo_name": "sarvex/tensorflow", "id": "17743352d2c6f5623bc43c2909f3c3bf2a6d7f06", "size": "8633", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tensorflow/compiler/xla/service/hlo_cse.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "148184" }, { "name": "C++", "bytes": "6224499" }, { "name": "CSS", "bytes": "107" }, { "name": "HTML", "bytes": "650478" }, { "name": "Java", "bytes": "53519" }, { "name": "JavaScript", "bytes": "6659" }, { "name": "Jupyter Notebook", "bytes": "777935" }, { "name": "Objective-C", "bytes": "1288" }, { "name": "Protocol Buffer", "bytes": "61743" }, { "name": "Python", "bytes": "3474762" }, { "name": "Shell", "bytes": "45640" }, { "name": "TypeScript", "bytes": "283668" } ], "symlink_target": "" }
'use strict' var mongoose = require('mongoose'), Schema = mongoose.Schema; //This defines each entry in the phonebook and the data //which is required and optional for it. var entrySchema = new Schema({ 'name': {type: String, required: true, trim: true}, 'surname': {type: String, required: true, trim:true}, 'phonenumber': {type: String, required: true, trim:true}, 'address': String }); mongoose.model('Entry', entrySchema);
{ "content_hash": "95332e2ebf42936d7519d2c0f4efb52a", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 55, "avg_line_length": 20.458333333333332, "alnum_prop": 0.6252545824847251, "repo_name": "apg84/RESTphonebook", "id": "b4957c1a6c746be8f8e33a0b675fbf7cacebf24d", "size": "491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/pbentry.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "20557" } ], "symlink_target": "" }
import Errors from 'ui/utils/errors'; import Component from '@ember/component' import { all as PromiseAll } from 'rsvp'; import { inject as service } from '@ember/service'; import { computed, get, set, setProperties } from '@ember/object'; import layout from './template'; import NewOrEdit from 'ui/mixins/new-or-edit'; import { next } from '@ember/runloop'; const CUSTOM = 'custom'; export default Component.extend(NewOrEdit,{ layout, globalStore: service(), intl: service(), user: null, primaryResource: null, editing: false, type: null, cTyped: null, stdUser: null, admin: null, principal: null, baseRoles: computed(function () { return [ `${get(this, 'type')}-admin`, `${get(this, 'type')}-owner`, `${get(this, 'type')}-member`, 'read-only' ]; }), userRoles: computed('model.roles.[]', function() { let roles = get(this, 'model.roles'); let current = get(this, 'defaultUser').get(`${get(this, 'type')}RoleBindings`); let userDef = roles.filter(role => { return !get(role, 'builtin') && !get(role, 'external') && !get(role, 'hidden'); }); return userDef.map((role) => { const binding = current.findBy('roleTemplateId', get(role, 'id')) || null; return { role, active: !!binding, existing: binding, } }); }), custom: computed('model.roles.[]', function() { // built in let current = get(this, 'defaultUser').get(`${get(this, 'type')}RoleBindings`); let roles = get(this, 'model.roles').filterBy('hidden', false); let excludes = get(this, 'baseRoles'); let context = `${get(this, 'type')}`; return roles.filter(role => { return !excludes.includes(role.id) && get(role, 'builtin') && get(role, 'context') === context; }).map((role) => { const binding = current.findBy('roleTemplateId', get(role, 'id')) || null; return { role, active: !!binding, existing: binding, } }); }), mode: computed('editing','defaultUser', { get() { let editing = get(this, 'editing'); let dfu = get(this, 'defaultUser'); let current = dfu.get(`${get(this, 'type')}RoleBindings`); let mode = null; if (editing && current.length === 1) { mode = get(current, 'firstObject.roleTemplateId'); } else if (editing && current.length > 1){ mode = CUSTOM; } else { mode = `${get(this, 'type')}-member`; } return mode; }, set(key, value) { if (typeof value === 'object') { set(value, 'active', true); // value = get(value, 'role.id'); // return get(value, 'role.id'); } else { let ur = get(this, 'userRoles').findBy('active', true); if (ur) { next(() => {set(ur, 'active', false)}) } } return value; }, }), init() { this._super(...arguments); let dfu = get(this, 'defaultUser'); let model = { type: `${get(this, 'type')}RoleTemplateBinding`, }; set(model, `${get(this, 'type')}Id`, get(this, `model.${get(this, 'type')}.id`)) setProperties(this, { primaryResource: this.make(model), defaultUser: dfu, stdUser: `${get(this, 'type')}-member`, admin: `${get(this, 'type')}-owner`, cTyped: get(this, 'type').capitalize() }); }, make(role) { return get(this, 'globalStore').createRecord(role); }, validate() { var errors = this.get('errors', errors) || []; if (get(this, 'mode') === 'custom') { if (get(this, 'customToAdd.length') < 1) { errors.push(this.get('intl').findTranslationByKey('rolesPage.new.errors.roleTemplate')); } } else { if (!get(this, 'primaryResource.roleTemplateId')) { errors.push(this.get('intl').findTranslationByKey('rolesPage.new.errors.roleTemplate')); } } let principal = get(this, 'principal'); if (!principal) { errors.push(this.get('intl').findTranslationByKey('rolesPage.new.errors.memberReq')); } this.set('errors', errors); return this.get('errors.length') === 0; }, customToAdd: computed('custom.@each.{active,existing}', function() { return get(this, 'custom').filter( role => { return get(role, 'active') && !get(role, 'existing'); }); }), customToRemove: computed('custom.@each.{active,existing}', function() { return get(this, 'custom').filter( role => { return get(role, 'active') === false && get(role, 'existing'); }) }), actions: { gotError: function(err) { set(this, 'errors', [Errors.stringify(err)]); }, addAuthorized: function(principal) { set(this, 'principal', principal); }, cancel() { this.sendAction('cancel'); }, save(cb) { this.set('errors', null); let mode = get(this, 'mode'); let add = []; let remove = []; let pr = get(this, 'primaryResource'); const userRoles = get(this, 'userRoles'); let principal = get(this, 'principal'); if (principal) { if (get(principal, 'principalType') === 'user') { set(pr, 'userPrincipalId', get(principal, 'id')) } else if (get(principal, 'principalType') === 'group') { set(pr, 'groupPrincipalId', get(principal, 'id')) } } switch ( mode ) { case `${get(this, 'type')}-owner`: case `${get(this, 'type')}-member`: case "read-only": set(pr, 'roleTemplateId', mode); add = [ pr ]; break; case CUSTOM: add = get(this, 'customToAdd').map((x) => { let neu = get(this, 'primaryResource').clone(); set(neu, 'roleTemplateId', get(x, 'role.id')); return neu; }); remove = get(this, 'customToRemove').map(y => y.existing); break; default: var addMatch =userRoles.find((ur) => { return get(ur, 'active') && !get(ur, 'existing'); }); var removeMatch = userRoles.find((ur) => { return !get(ur, 'active') && get(ur, 'existing'); }); if (addMatch) { set(pr, 'roleTemplateId', get(addMatch, 'role.id')); add = [ pr ]; } if (removeMatch) { remove = [ get(removeMatch, 'existing')]; } break; } if(!this.validate()) { if ( cb ) { cb(); } return; } return PromiseAll(add.map(x => x.save())).then(() => { return PromiseAll(remove.map(x => x.delete())).then(() => { return this.doneSaving(); }).catch((err) => { set(this, 'errors', [Errors.stringify(err)]); return cb(false); }); }).catch((err) => { set(this, 'errors', [Errors.stringify(err)]); return cb(false); }); }, }, didInsertElement() { next(() => { if ( this.isDestroyed || this.isDestroying ) { return; } const elem = this.$('INPUT')[0] if ( elem ) { setTimeout(()=>{ elem.focus(); }, 250); } }); }, });
{ "content_hash": "2a8aea9ae9aee2d94c345677356f76d7", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 96, "avg_line_length": 27.33969465648855, "alnum_prop": 0.531202010330867, "repo_name": "pengjiang80/ui", "id": "eab624b91a93954b6f73c180874a83d7365bb064", "size": "7163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/shared/addon/components/form-scoped-roles/component.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "157884" }, { "name": "HTML", "bytes": "739881" }, { "name": "JavaScript", "bytes": "1407771" }, { "name": "Shell", "bytes": "11290" }, { "name": "Standard ML", "bytes": "1205" } ], "symlink_target": "" }
package org.devilry.clientapi; import java.util.Iterator; import java.util.List; import javax.naming.NamingException; import org.devilry.core.NoSuchObjectException; import org.devilry.core.UnauthorizedException; public class ExaminerAssignment extends AbstractAssignment<ExaminerDelivery> { ExaminerAssignment(long assignmentId, DevilryConnection connection) { super(assignmentId, connection); } class ExaminerDeliveryIterator extends DeliveryIterator { ExaminerDeliveryIterator(List<Long> delivryIds) { super(delivryIds); } public ExaminerDelivery next() { return new ExaminerDelivery(deliveryIterator.next(), connection); } } Iterator<ExaminerDelivery> deliveries() throws NoSuchObjectException, UnauthorizedException, NamingException { List<Long> ids = getDeliveryBean().getDeliveriesWhereIsExaminer(); return new ExaminerDeliveryIterator(ids).iterator(); } }
{ "content_hash": "63fa22ac038220a74e0f8acf97e55fec", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 111, "avg_line_length": 27.545454545454547, "alnum_prop": 0.7953795379537953, "repo_name": "devilry/devilry-prototype1", "id": "3f82f60996e08bfe6440e76dc72f2fd3223d2150", "size": "909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/clientapi/src/main/java/org/devilry/clientapi/ExaminerAssignment.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "457676" }, { "name": "Python", "bytes": "469" } ], "symlink_target": "" }
import Tkinter as tk import xmlrpclib def new(): server.new() guess.set("-"*8) def submit(): propalValue = propal.get() result=server.guess(propalValue) if len(propalValue)==1: letters=list(guess.get()) for index in result: letters[index]=propalValue guess.set("".join(letters)) else: if result: message = "Congrats" else: message = "No luck" guess.set(message) if 1: server = xmlrpclib.Server('http://localhost:8081') gui=tk.Tk() propal = tk.StringVar() guess = tk.StringVar() guess.set("-"*8) tk.Label( gui,text="1 Letter or 8-letter word:").pack() tk.Entry( gui,textvariable=propal ).pack() tk.Label( gui,textvariable=guess ).pack() tk.Button(gui,text="Submit",command=submit ).pack() tk.Button(gui,text="New",command=new ).pack() gui.mainloop()
{ "content_hash": "a2122944af4733de78cf7e86c9c5a3d6", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 59, "avg_line_length": 29.838709677419356, "alnum_prop": 0.5816216216216217, "repo_name": "derivationBud/prez", "id": "d2c24fc2247033e15aa0ee6f6bce5823ad7d9d5a", "size": "925", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oldies/labs/python_more/gameClient.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "639424" }, { "name": "HTML", "bytes": "3039048" }, { "name": "JavaScript", "bytes": "388569" }, { "name": "Python", "bytes": "4231" }, { "name": "Shell", "bytes": "164" } ], "symlink_target": "" }
package shadow.tac; import shadow.interpreter.ConstantFieldInterpreter.FieldKey; import shadow.interpreter.ShadowValue; import shadow.parse.ShadowParser.VariableDeclaratorContext; import shadow.typecheck.type.Type; import java.io.StringWriter; /** * A simple node representing a compile-time constant field and containing its {@link * shadow.interpreter.ShadowValue} (as computed by {@link shadow.interpreter.ASTInterpreter}). */ public class TACConstant { private final FieldKey fieldKey; private final VariableDeclaratorContext context; public TACConstant(FieldKey fieldKey, VariableDeclaratorContext context) { this.fieldKey = fieldKey; this.context = context; } public FieldKey getFieldKey() { return fieldKey; } public ShadowValue getInterpretedValue() { return context.getInterpretedValue(); } @Override public String toString() { StringWriter writer = new StringWriter(); writer.write(context.getModifiers().toString()); writer.write(context.getType().toString(Type.TYPE_PARAMETERS)); writer.write(' '); writer.write(fieldKey.fieldName); writer.write(" = "); writer.write(getInterpretedValue().toLiteral()); return writer.toString(); } }
{ "content_hash": "45e4a275a18c9619d7c42e3e20709295", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 94, "avg_line_length": 29.166666666666668, "alnum_prop": 0.7493877551020408, "repo_name": "bwittman/shadow", "id": "ee2b36d2476ba3f9085b11745f061d76d315fb56", "size": "1225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/shadow/tac/TACConstant.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "19650" }, { "name": "C", "bytes": "35013" }, { "name": "CSS", "bytes": "3452" }, { "name": "Java", "bytes": "1394895" }, { "name": "LLVM", "bytes": "231618" } ], "symlink_target": "" }
import rg class Robot(object): def act(self, game): all_bots = [bot for bot in game['robots'].values() if bot['player_id'] != self.player_id] min_dist = rg.dist(self.location, all_bots[0]['location']) close_bots = [all_bots[0]] for bot in all_bots[1:]: distance = rg.dist(self.location, bot['location']) if distance == min_dist: # this bot is the same distance as the (known) closest bot close_bots.append(bot) elif distance < min_dist: # this bot is closer than the (known) closest bots, make it # the closest bot min_dist = distance close_bots = [bot] # by this point, we should have a list of the closest robot(s) target = min(close_bots, key=lambda x: x['hp']) if min_dist <= 1: return ['attack', target['location']] return['move', rg.toward(self.location, target['location'])]
{ "content_hash": "ac83409306f5c0a5eae9997b1360fc8a", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 97, "avg_line_length": 39.111111111111114, "alnum_prop": 0.5179924242424242, "repo_name": "Team-Brobot/robot-hackathon", "id": "1aff30e75774cbe81ac59c7211bf2a82f69355e8", "size": "1056", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bully_bot.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "1662" } ], "symlink_target": "" }
layout: page title: Tumblr Cover Letter --- ## Dear Tumblr Talent Acquistion, To be brief, I would absolutely adore a position at Tumblr. What I can offer Tumblr is 3 years of data science experience (both full and part-time), a large portfolio of work in applied statistics and statistical learning, and best practices analytical software development. But above any of my technical qualifications is a compelling love and excitement of solutions to problems. I come from a low-SES background, having no exterior support financially. I recieved scholarships in Undergrad, as well as practicum and assistantships through State Farm and the University of Illinois throughout my Masters Degree. Frankly, landing a job at Tumblr would be a great milestone in my personal story, and would prove (at least to myself) that hard work and determination does truly pay off in the end. Thank you for reviewing my application. My resume has also been submitted for your review. Best, Kyle N. Payne
{ "content_hash": "743ebd27d30d93668130d033e4f0b89d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 796, "avg_line_length": 70.85714285714286, "alnum_prop": 0.8014112903225806, "repo_name": "kylenpayne/kylenpayne.github.io", "id": "6e37b58839feeedd05f485eed84f6252ba80e62c", "size": "996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tumblr/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2449" }, { "name": "CSS", "bytes": "11239" }, { "name": "HTML", "bytes": "8151588" }, { "name": "JavaScript", "bytes": "980002" }, { "name": "Jupyter Notebook", "bytes": "186571" }, { "name": "R", "bytes": "39" }, { "name": "SAS", "bytes": "2096" }, { "name": "Shell", "bytes": "5095" } ], "symlink_target": "" }
namespace process { // Forward declaration. class SequenceProcess; // Provides an abstraction that serializes the execution of a sequence // of callbacks. class Sequence { public: Sequence(); ~Sequence(); // Registers a callback that will be invoked when all the futures // returned by the previously registered callbacks are in // non-pending status (i.e., ready, discarded or failed). Due to // these semantics, we should avoid registering a callback which // returns a future that could be in non-pending status for a long // time because it will prevent all the subsequent callbacks from // being invoked. This is analogous to the requirement that we want // to avoid invoking blocking function in a libprocess handler. A // user is allowed to cancel a registered callback by discarding the // returned future. Other callbacks in this sequence will NOT be // affected. The subsequent callbacks will not be invoked until the // future is actually DISCARDED. template <typename T> Future<T> add(const lambda::function<Future<T>(void)>& callback); private: // Not copyable, not assignable. Sequence(const Sequence&); Sequence& operator = (const Sequence&); SequenceProcess* process; }; class SequenceProcess : public Process<SequenceProcess> { public: SequenceProcess() : last(Nothing()) {} template <typename T> Future<T> add(const lambda::function<Future<T>(void)>& callback) { // This is the future that is used to notify the next callback // (denoted by 'N' in the following graph). Owned<Promise<Nothing> > notifier(new Promise<Nothing>()); // This is the future that will be returned to the user (denoted // by 'F' in the following graph). Owned<Promise<T> > promise(new Promise<T>()); // We use a graph to show how we hook these futures. Each box in // the graph represents a future. As mentioned above, 'F' denotes // a future that will be returned to the user, and 'N' denotes a // future that is used for notifying the next callback. Each arrow // represents a "notification" relation. We will explain in detail // what "notification" means in the following. // // 'last' 'last' 'last' // | | | // v v v // +---+ +---+ +---+ +---+ +---+ +---+ // | N | | N |--+ | N | | N |--+ | N |--+ | N | // +---+ +---+ | +---+ +---+ | +---+ | +---+ // ==> | ^ ==> | ^ | ^ // | | | | | | // | +---+ | +---+ | +---+ // +-->| F | +-->| F | +-->| F | // +---+ +---+ +---+ // // Initial => Added one callback => Added two callbacks // Setup the "notification" from 'F' to 'N' so that when a // callback is done, signal the notifier ('N'). promise->future().onAny(lambda::bind(&completed, notifier)); // Setup the "notification" from previous 'N' to 'F' so that when // a notifier ('N') is set (indicating the previous callback has // completed), invoke the next callback ('F') in the sequence. last.onAny(lambda::bind(&notified<T>, promise, callback)); // In the following, we setup the hooks so that if this sequence // process is being terminated, all pending callbacks will be // discarded. We use weak futures here to avoid cyclic dependencies. // Discard the future associated with this notifier. notifier->future().onDiscard( lambda::bind( &internal::discard<T>, WeakFuture<T>(promise->future()))); // Discard the notifier associated with the previous future. notifier->future().onDiscard( lambda::bind( &internal::discard<Nothing>, WeakFuture<Nothing>(last))); // Update the 'last'. last = notifier->future(); return promise->future(); } protected: virtual void finalize() { last.discard(); // TODO(jieyu): Do we need to wait for the future of the last // callback to be in DISCARDED state? } private: // Invoked when a callback is done. static void completed(Owned<Promise<Nothing> > notifier) { notifier->set(Nothing()); } // Invoked when a notifier is set. template <typename T> static void notified( Owned<Promise<T> > promise, const lambda::function<Future<T>(void)>& callback) { if (promise->future().hasDiscard()) { // The user has shown the intention to discard this callback // (i.e., by calling future.discard()). As a result, we will // just skip this callback. promise->discard(); } else { promise->associate(callback()); } } Future<Nothing> last; }; inline Sequence::Sequence() { process = new SequenceProcess(); process::spawn(process); } inline Sequence::~Sequence() { process::terminate(process); process::wait(process); delete process; } template <typename T> Future<T> Sequence::add(const lambda::function<Future<T>(void)>& callback) { return dispatch(process, &SequenceProcess::add<T>, callback); } } // namespace process { #endif // __PROCESS_SEQUENCE_HPP__
{ "content_hash": "6de2c82b5c1defa5cd42c2e68a986458", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 74, "avg_line_length": 32.92727272727273, "alnum_prop": 0.586416344561016, "repo_name": "jmanero/mesos-service", "id": "241afd243c3a91a824186b2dc511e9384901799f", "size": "5676", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mesos-0.20.0/3rdparty/libprocess/include/process/sequence.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "AGS Script", "bytes": "5016" }, { "name": "C", "bytes": "702382" }, { "name": "C++", "bytes": "4231114" }, { "name": "CSS", "bytes": "40879" }, { "name": "Java", "bytes": "3691420" }, { "name": "JavaScript", "bytes": "1245478" }, { "name": "Perl", "bytes": "298868" }, { "name": "Python", "bytes": "271683" }, { "name": "Ruby", "bytes": "22808" }, { "name": "Shell", "bytes": "762921" }, { "name": "XSLT", "bytes": "6024" } ], "symlink_target": "" }
package org.sharedhealth.datasense.repository; import org.sharedhealth.datasense.model.tr.TrReferenceTerm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Component; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @Component public class ReferenceTermDao { @Autowired private NamedParameterJdbcTemplate jdbcTemplate; public void saveOrUpdate(final TrReferenceTerm trReferenceTerm) { HashMap<String, Object> map = getParameterMap(trReferenceTerm); String sql; if (findByReferenceTermUuid(trReferenceTerm.getReferenceTermUuid()) == null) { sql = "insert into reference_term (reference_term_uuid, name, code, source) values " + "(:reference_term_uuid, :name, :code, :source)"; } else { sql = "update reference_term set name = :name, code = :code, source = :source, updated_at =:updated_at where " + "reference_term_uuid = :reference_term_uuid"; } jdbcTemplate.update(sql, map); } public void saveReferenceTermMap(String referenceTermUuid, String conceptUuid, String relationshipType) { HashMap<String, Object> map = new HashMap<>(); map.put("concept_uuid", conceptUuid); map.put("reference_term_uuid", referenceTermUuid); map.put("relationship_type", relationshipType); String sql; sql = "insert into reference_term_map (concept_uuid, reference_term_uuid, relationship_type) " + "values(:concept_uuid, :reference_term_uuid, :relationship_type)"; jdbcTemplate.update(sql, map); } public void deleteConceptReferenceTermMap(String conceptUuid) { jdbcTemplate.update("delete from reference_term_map where concept_uuid = :concept_uuid", Collections.singletonMap("concept_uuid", conceptUuid)); } public TrReferenceTerm findByReferenceTermUuid(String referenceTermUuid) { List<TrReferenceTerm> trReferenceTerms = jdbcTemplate.query( "select reference_term_uuid, name, code, source from reference_term where reference_term_uuid = :reference_term_uuid", Collections.singletonMap("reference_term_uuid", referenceTermUuid), new RowMapper<TrReferenceTerm>() { @Override public TrReferenceTerm mapRow(ResultSet rs, int rowNum) throws SQLException { TrReferenceTerm trReferenceTerm = new TrReferenceTerm(); trReferenceTerm.setReferenceTermUuid(rs.getString("reference_term_uuid")); trReferenceTerm.setName(rs.getString("name")); trReferenceTerm.setCode(rs.getString("code")); trReferenceTerm.setSource(rs.getString("source")); return trReferenceTerm; } }); return trReferenceTerms.isEmpty() ? null : trReferenceTerms.get(0); } private HashMap<String, Object> getParameterMap(TrReferenceTerm trReferenceTerm) { HashMap<String, Object> map = new HashMap<>(); map.put("reference_term_uuid", trReferenceTerm.getReferenceTermUuid()); map.put("name", trReferenceTerm.getName()); map.put("code", trReferenceTerm.getCode()); map.put("source", trReferenceTerm.getSource()); map.put("updated_at", new Date()); return map; } }
{ "content_hash": "d8b8e666186b63bdc3e70c75a7b710ad", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 152, "avg_line_length": 48.35526315789474, "alnum_prop": 0.6672108843537415, "repo_name": "SharedHealth/SHR-Datasense", "id": "6c6cbe954dc04b81d140da1755e06ed1bbaff283", "size": "3675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/sharedhealth/datasense/repository/ReferenceTermDao.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7563" }, { "name": "FreeMarker", "bytes": "594" }, { "name": "HTML", "bytes": "70978" }, { "name": "Java", "bytes": "592505" }, { "name": "JavaScript", "bytes": "43781" }, { "name": "Shell", "bytes": "2805" } ], "symlink_target": "" }
Originally published: 2004-07-07 18:34:01 Last updated: 2004-07-07 18:34:01 Author: Duncan Smith The following KeyedSet class mirrors the builtin set class as closely as possible, whilst maintaining the general flexibility of a dictionary. The only requirement is that each set item has a distinct 'id' attribute. The usual set operations are implemented, but items can also be referenced via their id.
{ "content_hash": "ad038d6b73e87a41430a20da0ab88a78", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 307, "avg_line_length": 82.6, "alnum_prop": 0.7869249394673123, "repo_name": "ActiveState/code", "id": "080b3afc751343b5b423a0e197b359bad837d48e", "size": "491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "recipes/Python/286209_set_class_mutable_objects_unique_hashable_id/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "35894" }, { "name": "C", "bytes": "56048" }, { "name": "C++", "bytes": "90880" }, { "name": "HTML", "bytes": "11656" }, { "name": "Java", "bytes": "57468" }, { "name": "JavaScript", "bytes": "181218" }, { "name": "PHP", "bytes": "250144" }, { "name": "Perl", "bytes": "37296" }, { "name": "Perl 6", "bytes": "9914" }, { "name": "Python", "bytes": "17387779" }, { "name": "Ruby", "bytes": "40233" }, { "name": "Shell", "bytes": "190732" }, { "name": "Tcl", "bytes": "674650" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>compcert: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0~camlp4 / compcert - 3.3.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> compcert <small> 3.3.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-09-23 22:02:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-23 22:02:02 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp4 4.02+7 Camlp4 is a system for writing extensible parsers for programming languages conf-findutils 1 Virtual package relying on findutils conf-which 1 Virtual package relying on which coq 8.5.0~camlp4 Formal proof management system. num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlbuild 0 Build system distributed with the OCaml compiler since OCaml 3.10.0 # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Jacques-Henri Jourdan &lt;jacques-Henri.jourdan@normalesup.org&gt;&quot; homepage: &quot;http://compcert.inria.fr/&quot; dev-repo: &quot;git+https://github.com/AbsInt/CompCert.git&quot; bug-reports: &quot;https://github.com/AbsInt/CompCert/issues&quot; license: &quot;INRIA Non-Commercial License Agreement&quot; build: [ [ &quot;./configure&quot; &quot;ia32-linux&quot; {os = &quot;linux&quot;} &quot;ia32-macosx&quot; {os = &quot;macos&quot;} &quot;ia32-cygwin&quot; {os = &quot;cygwin&quot;} &quot;-bindir&quot; &quot;%{bin}%&quot; &quot;-libdir&quot; &quot;%{lib}%/compcert&quot; &quot;-install-coqdev&quot; &quot;-clightgen&quot; &quot;-coqdevdir&quot; &quot;%{lib}%/coq/user-contrib/compcert&quot; &quot;-ignore-coq-version&quot; ] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] [&quot;install&quot; &quot;-m&quot; &quot;0644&quot; &quot;VERSION&quot; &quot;%{lib}%/coq/user-contrib/compcert/&quot;] ] remove: [ [&quot;rm&quot; &quot;%{bin}%/ccomp&quot;] [&quot;rm&quot; &quot;%{bin}%/clightgen&quot;] [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/compcert&quot;] [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/compcert&quot;] [&quot;rm&quot; &quot;%{share}%/compcert.ini&quot;] [&quot;rm&quot; &quot;%{share}%/man/man1/ccomp.1&quot;] [&quot;sh&quot; &quot;-c&quot; &quot;rmdir -p %{share}%/man/man1 || true&quot;] ] depends: [ &quot;ocaml&quot; {&lt; &quot;4.07.0&quot;} &quot;coq&quot; {&gt; &quot;8.6.0&quot; &amp; &lt; &quot;8.8.1&quot;} &quot;menhir&quot; {&gt;= &quot;20161201&quot; &amp; &lt; &quot;20180530&quot;} ] synopsis: &quot;The CompCert C compiler&quot; authors: &quot;Xavier Leroy &lt;xavier.leroy@inria.fr&gt;&quot; url { src: &quot;https://github.com/AbsInt/CompCert/archive/v3.3.tar.gz&quot; checksum: &quot;md5=89c62f13cea4c2be7917aa04590e8c7d&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-compcert.3.3.0 coq.8.5.0~camlp4</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0~camlp4). The following dependencies couldn&#39;t be met: - coq-compcert -&gt; coq &gt;= 8.6.1 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-compcert.3.3.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "d6f546f5c18d521adec8830cc71d7a06", "timestamp": "", "source": "github", "line_count": 192, "max_line_length": 157, "avg_line_length": 41.651041666666664, "alnum_prop": 0.5507065149431036, "repo_name": "coq-bench/coq-bench.github.io", "id": "a7b6b8a8a272fd67d35ba556275c1433e110408e", "size": "7999", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.1/released/8.5.0~camlp4/compcert/3.3.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.apache.accumulo.test.functional; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Collections; import java.util.Map.Entry; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableExistsException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl; import org.apache.accumulo.test.mapreduce.RowHash; import org.apache.hadoop.io.Text; import org.junit.Test; public class MapReduceIT extends ConfigurableMacBase { @Override protected int defaultTimeoutSeconds() { return 60; } public static final String hadoopTmpDirArg = "-Dhadoop.tmp.dir=" + System.getProperty("user.dir") + "/target/hadoop-tmp"; static final String tablename = "mapredf"; static final String input_cf = "cf-HASHTYPE"; static final String input_cq = "cq-NOTHASHED"; static final String input_cfcq = input_cf + ":" + input_cq; static final String output_cq = "cq-MD4BASE64"; static final String output_cfcq = input_cf + ":" + output_cq; @Test public void test() throws Exception { runTest(getConnector(), getCluster()); } static void runTest(Connector c, MiniAccumuloClusterImpl cluster) throws AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException, MutationsRejectedException, IOException, InterruptedException, NoSuchAlgorithmException { c.tableOperations().create(tablename); BatchWriter bw = c.createBatchWriter(tablename, new BatchWriterConfig()); for (int i = 0; i < 10; i++) { Mutation m = new Mutation("" + i); m.put(input_cf, input_cq, "row" + i); bw.addMutation(m); } bw.close(); Process hash = cluster.exec(RowHash.class, Collections.singletonList(hadoopTmpDirArg), "-i", c.getInstance().getInstanceName(), "-z", c.getInstance() .getZooKeepers(), "-u", "root", "-p", ROOT_PASSWORD, "-t", tablename, "--column", input_cfcq); assertEquals(0, hash.waitFor()); try (Scanner s = c.createScanner(tablename, Authorizations.EMPTY)) { s.fetchColumn(new Text(input_cf), new Text(output_cq)); int i = 0; for (Entry<Key,Value> entry : s) { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] check = Base64.getEncoder().encode(md.digest(("row" + i).getBytes())); assertEquals(entry.getValue().toString(), new String(check)); i++; } } } }
{ "content_hash": "35e03292f93abc18ea4d042aac623d75", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 153, "avg_line_length": 40.753246753246756, "alnum_prop": 0.7383683875079669, "repo_name": "mikewalch/accumulo", "id": "26fe5b7eb0d88f4cc3bb620bd4be1f69ce372ff3", "size": "3939", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/src/main/java/org/apache/accumulo/test/functional/MapReduceIT.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2423" }, { "name": "C++", "bytes": "2276148" }, { "name": "CSS", "bytes": "7395" }, { "name": "FreeMarker", "bytes": "54658" }, { "name": "Groovy", "bytes": "1385" }, { "name": "HTML", "bytes": "5970" }, { "name": "Java", "bytes": "23452563" }, { "name": "JavaScript", "bytes": "86450" }, { "name": "Makefile", "bytes": "2865" }, { "name": "Python", "bytes": "1001767" }, { "name": "Ruby", "bytes": "270630" }, { "name": "Shell", "bytes": "64165" }, { "name": "Thrift", "bytes": "66191" } ], "symlink_target": "" }
package querqy.solr.rewriter.commonrules; import static querqy.solr.QuerqyQParserPlugin.PARAM_REWRITERS; import static querqy.solr.StandaloneSolrTestSupport.withCommonRulesRewriter; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.params.DisMaxParams; import org.apache.solr.request.SolrQueryRequest; import org.junit.BeforeClass; import org.junit.Test; import querqy.solr.StandaloneSolrTestSupport; @SolrTestCaseJ4.SuppressSSL public class CommonRulesBooleanInputTest extends SolrTestCaseJ4 { private static final String REWRITER_NAME = "common_rules"; @BeforeClass public static void beforeTests() throws Exception { initCore("solrconfig.xml", "schema.xml"); withCommonRulesRewriter( h.getCore(), REWRITER_NAME, new CommonRulesConfigRequestBuilder() .rules(StandaloneSolrTestSupport.class.getClassLoader() .getResourceAsStream("configs/commonrules/rules-booleaninput.txt")) .allowBooleanInput(true)); addDocs(); } private static void addDocs() { assertU(adoc("id", "1", "f1", "a b c", "f2", "d")); assertU(adoc("id", "2", "f1", "a b c", "f2", "e")); assertU(adoc("id", "3", "f1", "a b c", "f2", "f")); assertU(adoc("id", "4", "f1", "gh i", "f2", "j")); assertU(adoc("id", "5", "f1", "gh i", "f2", "k")); assertU(adoc("id", "6", "f1", "l m", "f2", "n")); assertU(adoc("id", "7", "f1", "l m", "f2", "o")); assertU(adoc("id", "8", "f1", "abc no ise", "f2", "xyz")); assertU(adoc("id", "9", "f1", "abc", "f2", "not boosted")); assertU(adoc("id", "10", "f1", "uvw", "f2", "not boosted")); assertU(commit()); } private String[] createParams(String q) { return new String[]{ "q", q, DisMaxParams.QF, "f1", "fl", "id,score", DisMaxParams.MM, "100%", PARAM_REWRITERS, REWRITER_NAME, "debugQuery", "on", "defType", "querqy" }; } @Test public void testFilteringForSimpleBooleanInput() { SolrQueryRequest req; req = req(createParams("a b")); assertQ("", req, "//result[@name='response' and @numFound='1']"); req.close(); req = req(createParams("c")); assertQ("", req, "//result[@name='response' and @numFound='1']"); req.close(); req = req(createParams("a")); assertQ("", req, "//result[@name='response' and @numFound='3']"); req.close(); req = req(createParams("b")); assertQ("", req, "//result[@name='response' and @numFound='3']"); req.close(); } @Test public void testFilteringForPrefixInput() { SolrQueryRequest req; req = req(createParams("gh i")); assertQ("", req, "//result[@name='response' and @numFound='1']"); req.close(); } @Test public void testFilteringBoundaryInput() { SolrQueryRequest req; req = req(createParams("l l m")); assertQ("", req, "//result[@name='response' and @numFound='1']"); req.close(); req = req(createParams("m l l")); assertQ("", req, "//result[@name='response' and @numFound='2']"); req.close(); req = req(createParams("l m m")); assertQ("", req, "//result[@name='response' and @numFound='1']"); req.close(); req = req(createParams("m m l")); assertQ("", req, "//result[@name='response' and @numFound='2']"); req.close(); req = req(createParams("m m m")); assertQ("", req, "//result[@name='response' and @numFound='1']"); req.close(); req = req(createParams("l l l")); assertQ("", req, "//result[@name='response' and @numFound='1']"); req.close(); req = req(createParams("m m m m")); assertQ("", req, "//result[@name='response' and @numFound='2']"); req.close(); req = req(createParams("l l l l")); assertQ("", req, "//result[@name='response' and @numFound='2']"); req.close(); } @Test public void testMixedBooleanNonBooleanInput() { try (final SolrQueryRequest req = req( "q", "abc def", DisMaxParams.QF, "f1 f2", "fl", "id,score", DisMaxParams.MM, "1", PARAM_REWRITERS, REWRITER_NAME, "debugQuery", "on", "defType", "querqy" )) { assertQ("Mixed input not working", req, "//result[@name='response' and @numFound='3']", "//result/doc[1]/str[@name='id'][text()='8']" ); } } }
{ "content_hash": "220e06ca8e634abc18cb0bb084f57b80", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 99, "avg_line_length": 32.06369426751592, "alnum_prop": 0.5061581247516885, "repo_name": "renekrie/querqy", "id": "8d1609a1d596787e3cebb9d405427535ca1e1acb", "size": "5034", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "querqy-for-lucene/querqy-solr/src/test/java/querqy/solr/rewriter/commonrules/CommonRulesBooleanInputTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1036697" } ], "symlink_target": "" }
""" Copyright 2018 Dispel, LLC Apache 2.0 License, see https://github.com/dispel/jak/blob/master/LICENSE for details. """ import base64 import binascii from io import open from . import helpers from .compat import b from .aes_cipher import AES256Cipher from .exceptions import JakException, WrongKeyException ENCRYPTED_BY_HEADER = u'- - - Encrypted by jak - - -\n\n' def _read_file(filepath): """Helper for reading a file and making sure it has content.""" try: with open(filepath, 'rb') as f: contents = f.read() except IOError: raise JakException("Sorry I can't find the file: {}".format(filepath)) if len(contents) == 0: raise JakException('The file "{}" is empty, aborting...'.format(filepath)) return contents def _restore_from_backup(jwd, filepath, plaintext, aes256_cipher): """Return backup value (if such exists and content in file has not changed) We may want to replace this with a simpler "check last modified time" lookup that could happen in constant time instead. """ if not helpers.is_there_a_backup(jwd=jwd, filepath=filepath): return None backup_ciphertext_original = helpers.get_backup_content_for_file(jwd=jwd, filepath=filepath) previous_enc = base64.urlsafe_b64decode(b(backup_ciphertext_original)) iv = aes256_cipher.extract_iv(ciphertext=previous_enc) new_secret_w_same_iv = aes256_cipher.encrypt(plaintext=plaintext, iv=iv) if new_secret_w_same_iv == previous_enc: return backup_ciphertext_original return None def write_ciphertext_to_file(filepath, ciphertext): ciphertext = b(ciphertext) ciphertext = ciphertext.replace(b'\n', b'') encrypted_chunks = helpers.grouper(ciphertext.decode('utf-8'), 60) with open(filepath, 'w', encoding='utf-8') as f: f.write(ENCRYPTED_BY_HEADER) for encrypted_chunk in encrypted_chunks: f.write(encrypted_chunk + '\n') def encrypt_file(jwd, filepath, key, **kwargs): """Encrypts a file""" plaintext = _read_file(filepath=filepath) if b(ENCRYPTED_BY_HEADER) in plaintext: raise JakException('I already encrypted the file: "{}".'.format(filepath)) aes256_cipher = AES256Cipher(key=key) ciphertext = _restore_from_backup(jwd=jwd, filepath=filepath, plaintext=plaintext, aes256_cipher=aes256_cipher) if not ciphertext: ciphertext_ugly = aes256_cipher.encrypt(plaintext=plaintext) # Base64 is prettier ciphertext = base64.urlsafe_b64encode(ciphertext_ugly) write_ciphertext_to_file(filepath=filepath, ciphertext=ciphertext) return '{} - is now encrypted.'.format(filepath) def decrypt_file(filepath, key, jwd, **kwargs): """Decrypts a file""" contents = _read_file(filepath=filepath) if b(ENCRYPTED_BY_HEADER) not in contents: return 'The file "{}" is already decrypted, or it is missing it\'s jak header.'.format( filepath) ciphertext_no_header = contents.replace(b(ENCRYPTED_BY_HEADER), b'') # We could actually check that the first few letters are SkFL (JAK in base64) # it seems unreasonably unlikely that a plaintext would start with those 4 characters. # But the header check above should be enough. # Remove the base64 encoding which is applied to make output prettier after encryption. try: ciphertext = base64.urlsafe_b64decode(ciphertext_no_header) except (TypeError, binascii.Error): return 'The file "{}" is already decrypted, or is not in a format I recognize.'.format( filepath) # Remember the encrypted file in the .jak folder # The reason to remember is because we don't want re-encryption of files to # be different from previous ones if the content has not changed (which it would # with a new random IV). This way it works way better with VCS systems like git. helpers.backup_file_content(jwd=jwd, filepath=filepath, content=ciphertext_no_header) # Perform decryption aes256_cipher = AES256Cipher(key=key) try: decrypted_secret = aes256_cipher.decrypt(ciphertext=ciphertext) except WrongKeyException as wke: raise JakException('{} - {}'.format(filepath, wke.__str__())) with open(filepath, 'wb') as f: f.write(decrypted_secret) return '{} - is now decrypted.'.format(filepath)
{ "content_hash": "3b26448a1f2489abe1d1ab199b2583a5", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 96, "avg_line_length": 36.390243902439025, "alnum_prop": 0.6744861483467381, "repo_name": "dispel/jak", "id": "5977d026ffd8ef934aa15bfba024fb5c5a6090ce", "size": "4501", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jak/crypto_services.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "67541" }, { "name": "Shell", "bytes": "470" } ], "symlink_target": "" }
package weibo4j; import java.util.List; import weibo4j.model.Paging; import weibo4j.model.PostParameter; import weibo4j.model.Tag; import weibo4j.model.TagWapper; import weibo4j.model.WeiboException; import weibo4j.org.json.JSONArray; import weibo4j.org.json.JSONException; import weibo4j.org.json.JSONObject; import weibo4j.util.WeiboConfig; public class Tags extends Weibo { private static final long serialVersionUID = 7047254100483792467L; public Tags(String access_token) { this.access_token = access_token; } /*----------------------------标签接口----------------------------------------*/ /** * 返回指定用户的标签列表 * * @param uid * 要获取的标签列表所属的用户ID * @return list of the tags * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.1 * @see http://open.weibo.com/wiki/2/tags * @since JDK 1.5 */ public List<Tag> getTags(String uid) throws WeiboException { return Tag.constructTags(client.get(WeiboConfig.getValue("baseURL") + "tags.json", new PostParameter[] { new PostParameter("uid", uid) }, access_token)); } /** * 返回指定用户的标签列表 * * @param uid * 要获取的标签列表所属的用户ID * @param page * 返回结果的页码,默认为1 * @return list of the tags * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.1 * @see http://open.weibo.com/wiki/2/tags * @since JDK 1.5 */ public List<Tag> getTags(String uid, int count, Paging page) throws WeiboException { return Tag.constructTags(client.get(WeiboConfig.getValue("baseURL") + "tags.json", new PostParameter[] { new PostParameter("uid", uid), new PostParameter("count", count) }, page, access_token)); } /** * 批量获取用户的标签列表 * * @param uids * 要获取标签的用户ID。最大20,逗号分隔 * @return list of the tags * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.1 * @see http://open.weibo.com/wiki/2/tags/tags_batch * @since JDK 1.5 */ public TagWapper getTagsBatch(String uids) throws WeiboException { return Tag.constructTagWapper(client.get( WeiboConfig.getValue("baseURL") + "tags/tags_batch.json", new PostParameter[] { new PostParameter("uids", uids) }, access_token)); } /** * 获取系统推荐的标签列表 * * @return list of the tags * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.1 * @see http://open.weibo.com/wiki/2/tags/suggestions * @since JDK 1.5 */ public List<Tag> getTagsSuggestions() throws WeiboException { return Tag.constructTags(client.get(WeiboConfig.getValue("baseURL") + "tags/suggestions.json", access_token)); } /** * 获取系统推荐的标签列表 * * @param count * 返回记录数,默认10,最大10 * @return * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.2 * @see http://open.weibo.com/wiki/2/tags/suggestions * @since JDK 1.5 */ public List<Tag> getTagsSuggestions(int count) throws WeiboException { return Tag.constructTags(client.get(WeiboConfig.getValue("baseURL") + "tags/suggestions.json", new PostParameter[] { new PostParameter("count", count) }, access_token)); } /** * 为当前登录用户添加新的用户标签 * * @param tags * 要创建的一组标签,用半角逗号隔开,每个标签的长度不可超过7个汉字,14个半角字符 * @return tag_id * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.1 * @see http://open.weibo.com/wiki/2/tags/create * @since JDK 1.5 */ public JSONArray createTags(String tags) throws WeiboException { return client.post( WeiboConfig.getValue("baseURL") + "tags/create.json", new PostParameter[] { new PostParameter("tags", tags) }, access_token).asJSONArray(); } /** * 删除一个用户标签 * * @param tag_id * 要删除的标签ID * @return * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.1 * @throws JSONException * @see http://open.weibo.com/wiki/2/tags/destroy * @since JDK 1.5 */ public JSONObject destoryTag(Integer tag_id) throws WeiboException { return client.post( WeiboConfig.getValue("baseURL") + "tags/destroy.json", new PostParameter[] { new PostParameter("tag_id", tag_id .toString()) }, access_token).asJSONObject(); } /** * 批量删除一组标签 * * @param ids * 要删除的一组标签ID,以半角逗号隔开,一次最多提交10个ID * @return tag_id * @throws WeiboException * when Weibo service or network is unavailable * @version weibo4j-V2 1.0.1 * @see http://open.weibo.com/wiki/2/tags/destroy_batch * @since JDK 1.5 */ public List<Tag> destroyTagsBatch(String ids) throws WeiboException { return Tag.constructTags(client.post(WeiboConfig.getValue("baseURL") + "tags/destroy_batch.json", new PostParameter[] { new PostParameter("ids", ids) }, access_token)); } }
{ "content_hash": "1acce92a2f7fcf3e1d77f2d3d889a4db", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 77, "avg_line_length": 28.434285714285714, "alnum_prop": 0.6569533762057878, "repo_name": "yuzhiping/jeeplus", "id": "08edc7d16ccc0362cf5a285cd37cab4328518ee5", "size": "5418", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "jeeplus-blog/src/main/java/weibo4j/Tags.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2722981" }, { "name": "HTML", "bytes": "4185867" }, { "name": "Java", "bytes": "2192038" }, { "name": "JavaScript", "bytes": "16235016" }, { "name": "PHP", "bytes": "7682" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>30. Recursion &mdash; Learn Python with Reeborg</title> <link rel="stylesheet" href="_static/reeborg.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="shortcut icon" href="_static/favicon.ico"/> <link rel="top" title="Learn Python with Reeborg" href="index.html" /> <link rel="next" title="31. Tricky recursion" href="recursion2.html" /> <link rel="prev" title="29. Revisiting some challenges" href="challenges2.html" /> <script> // intelligent scrolling of the sidebar content // copied from the sphinx website $(window).scroll(function() { var sb = $('.sphinxsidebarwrapper'); var win = $(window); var sbh = sb.height(); var offset = $('.sphinxsidebar').position()['top']; var wintop = win.scrollTop(); var winbot = wintop + win.innerHeight(); var curtop = sb.position()['top']; var curbot = curtop + sbh; // does sidebar fit in window? if (sbh < win.innerHeight()) { // yes: easy case -- always keep at the top sb.css('top', $u.min([$u.max([0, wintop - offset - 10]), $(document).height() - sbh - 200])); } else { // no: only scroll if top/bottom edge of sidebar is at // top/bottom edge of window if (curtop > wintop && curbot > winbot) { sb.css('top', $u.max([wintop - offset - 10, 0])); } else if (curtop < wintop && curbot < winbot) { sb.css('top', $u.min([winbot - sbh - offset - 20, $(document).height() - sbh - 200])); } } }); </script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="recursion2.html" title="31. Tricky recursion" accesskey="N">next</a></li> <li class="right" > <a href="challenges2.html" title="29. Revisiting some challenges" accesskey="P">previous</a> |</li> <li><a class="logo" href="../../index_en.html" class="fake_button"> <img class="logo" src="_static/robot_e.png" alt="Logo"/>Reeborg's World </a></li> <li><a href="index.html">Learn Python with Reeborg</a></li> </ul> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="challenges2.html" title="previous chapter">29. Revisiting some challenges</a></p> <h4>Next topic</h4> <p class="topless"><a href="recursion2.html" title="next chapter">31. Tricky recursion</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/recursion.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="recursion"> <h1>30. Recursion<a class="headerlink" href="#recursion" title="Permalink to this headline">¶</a></h1> <p>If you look up on the Internet for a definition of recursion, you will often see something like the following:</p> <dl class="docutils"> <dt><strong>Recursion</strong></dt> <dd>See recursion.</dd> </dl> <p>This is wrong, wrong, <em>wrong</em>, <strong>wrong</strong> .... WRONG!</p> <p>If you were a computer program, trying to parse the above definition, you would get stuck in an infinite loop. Since you are reading this, it means that either you did not behave like a computer and got stuck in an infinite loop OR that you did not read everything here and, in particular, skipped over the above definition.</p> <p>Recursion is sometimes described as being difficult to grasp. Do not believe this. If you understand loops, you can understand recursion.</p> <p>So, what is recursion you ask?...</p> <p>Recursion is the process of repeating items in a self-similar way. For computer programs, it means repeating instructions - like in a loop. And, like in a loop, we do not want to get stuck forever.</p> <p>The simplest example is that of a single recursive function, that is a function that calls itself.:</p> <div class="highlight-py3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">recursive</span><span class="p">():</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">completed_task</span><span class="p">():</span> <span class="o">...</span> <span class="n">recursive</span><span class="p">()</span> <span class="c"># the same function is called ...</span> </pre></div> </div> <p>Let&#8217;s consider a real program for Reeborg to execute.</p> <div class="topic"> <p class="topic-title first">Try this!</p> <p>Select <strong>Home&nbsp;1</strong> and have Reeborg do the following:</p> <div class="highlight-py3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">go_home</span><span class="p">():</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">at_goal</span><span class="p">():</span> <span class="n">move</span><span class="p">()</span> <span class="n">go_home</span><span class="p">()</span> <span class="c"># now do it!</span> <span class="n">go_home</span><span class="p">()</span> </pre></div> </div> </div> <p>Once you have tried the above and tried to understood it, go to the next lesson where we will review it and consider a slightly trickier example.</p> </div> </div> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="recursion2.html" title="31. Tricky recursion" >next</a></li> <li class="right" > <a href="challenges2.html" title="29. Revisiting some challenges" >previous</a> |</li> <li><a class="logo" href="../../index_en.html" class="fake_button"> <img class="logo" src="_static/robot_e.png" alt="Logo"/>Reeborg's World </a></li> <li><a href="index.html">Learn Python with Reeborg</a></li> </ul> </div> <div class="footer"> &copy; Copyright <a href="mailto:andre.roberge@gmail.com">André Roberge </a> - Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.2. </div> </body> </html>
{ "content_hash": "14cbc3c9dcf7f1076e3abda40b0121af", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 141, "avg_line_length": 40.858695652173914, "alnum_prop": 0.5940409683426443, "repo_name": "coursemdetw/reeborg_tw", "id": "df2484937450065db3811d4651f6bd49578bec89", "size": "7520", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "docs/begin_py_en/_build/html/recursion.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "195060" }, { "name": "JavaScript", "bytes": "1308242" }, { "name": "Python", "bytes": "2842856" }, { "name": "Shell", "bytes": "26128" } ], "symlink_target": "" }
/////////////////////////////////////////////////////////////////////////////// // FILE: Marzhauser.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Marzhauser Tango Controller Driver // XY Stage // Z Stage // TTL Shutter // DAC-0 (e.g. LED100 #1) // DAC-1 (e.g. LED100 #2) // ADC (e.g. 0..5 V) // // AUTHOR: Falk Dettmar, falk.dettmar@marzhauser-st.de, 09/04/2009 // COPYRIGHT: Marzhauser SensoTech GmbH, Wetzlar, 2010 // LICENSE: This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation. // // You should have received a copy of the GNU Lesser General Public // License along with the source distribution; if not, write to // the Free Software Foundation, Inc., 59 Temple Place, Suite 330, // Boston, MA 02111-1307 USA // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // #ifdef WIN32 // #include <windows.h> #define snprintf _snprintf #pragma warning(disable: 4355) #endif #include "Marzhauser.h" #include <string> //#include <math.h> #include "../../MMDevice/ModuleInterface.h" #include <sstream> const char* g_XYStageDeviceName = "XYStage"; const char* g_ZStageDeviceName = "ZAxis"; const char* g_AStageDeviceName = "AAxis"; const char* g_ShutterName = "TTLShutter"; const char* g_LED1Name = "LED100-1"; const char* g_LED2Name = "LED100-2"; const char* g_DACName = "DAC"; const char* g_ADCName = "ADC"; using namespace std; /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { RegisterDevice(g_XYStageDeviceName, MM::XYStageDevice, "Tango XY Stage"); RegisterDevice(g_ZStageDeviceName, MM::StageDevice, "Tango Z Axis"); RegisterDevice(g_AStageDeviceName, MM::StageDevice, "Tango A Axis"); RegisterDevice(g_ShutterName, MM::ShutterDevice, "Tango TTL Shutter"); RegisterDevice(g_LED1Name, MM::ShutterDevice, "Tango LED100-1 [0..100%]"); RegisterDevice(g_LED2Name, MM::ShutterDevice, "Tango LED100-2 [0..100%]"); RegisterDevice(g_DACName, MM::SignalIODevice, "Tango DAC [0..10V]"); RegisterDevice(g_ADCName, MM::SignalIODevice, "Tango ADC [0..5V]"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; if (strcmp(deviceName, g_XYStageDeviceName) == 0) return new XYStage(); if (strcmp(deviceName, g_ZStageDeviceName) == 0) return new ZStage(); if (strcmp(deviceName, g_AStageDeviceName) == 0) return new AStage(); if (strcmp(deviceName, g_ShutterName) == 0) return new Shutter(); if (strcmp(deviceName, g_LED1Name) == 0) return new LED100(g_LED1Name, 0); //legal range of id = [0..1] if (strcmp(deviceName, g_LED2Name) == 0) return new LED100(g_LED2Name, 1); if (strcmp(deviceName, g_DACName) == 0) return new DAC(); if (strcmp(deviceName, g_ADCName) == 0) return new ADC(); return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } /////////////////////////////////////////////////////////////////////////////// // TangoBase (convenience parent class) // TangoBase::TangoBase(MM::Device *device) : initialized_(false), Configuration_(0), port_("Undefined"), device_(device), core_(0) { } TangoBase::~TangoBase() { } // Communication "clear buffer" utility function: int TangoBase::ClearPort(void) { // Clear contents of serial port const int bufSize = 255; unsigned char clear[bufSize]; unsigned long read = bufSize; int ret; // clear Tango Rx Buffer from any incomplete command or rubbish sent from PC OS // send \r to clear Tango Rx Buffer ret = SendCommand(""); CDeviceUtils::SleepMs(10); // clear PC Rx buffer while ((int) read == bufSize) { ret = core_->ReadFromSerial(device_, port_.c_str(), clear, bufSize, read); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } // Communication "send" utility function: int TangoBase::SendCommand(const char *command) const { const char* g_TxTerm = "\r"; //unique termination from MM to Tango communication int ret; std::string base_command = ""; base_command += command; // send command ret = core_->SetSerialCommand(device_, port_.c_str(), base_command.c_str(), g_TxTerm); return ret; } // Communication "send & receive" utility function: int TangoBase::QueryCommand(const char *command, std::string &answer) const { const char* g_RxTerm = "\r"; //unique termination from Tango to MM communication std::string base_command = ""; int ret; // send command ret = SendCommand(command); if (ret != DEVICE_OK) return ret; // block/wait for acknowledge (or until we time out) const size_t BUFSIZE = 2048; char buf[BUFSIZE] = {'\0'}; ret = core_->GetSerialAnswer(device_, port_.c_str(), BUFSIZE, buf, g_RxTerm); answer = buf; return ret; } int TangoBase::CheckDeviceStatus(void) { int ret = ClearPort(); if (ret != DEVICE_OK) return ret; // Tango Version string resp; ret = QueryCommand("?version",resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_NOT_CONNECTED; if (resp.find("TANGO") == string::npos) return DEVICE_NOT_CONNECTED; ret = SendCommand("!autostatus 0"); //diasable autostatus if (ret != DEVICE_OK) return ret; ret = QueryCommand("?det", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; Configuration_ = atoi(resp.c_str()); initialized_ = true; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // XYStage // /* * XYStage - two axis stage device. * Note that this adapter uses two coordinate systems. There is the adapters own coordinate * system with the X and Y axis going the 'Micro-Manager standard' direction * Then, there is the Tango native system. All functions using 'steps' use the Tango system * All functions using Um use the Micro-Manager coordinate system */ XYStage::XYStage() : TangoBase(this), range_measured_(false), stepSizeXUm_(0.0012), //=1000*pitch[mm]/gear/(motorsteps*4096) (assume gear=1 motorsteps=200 => stepsize=pitch/819.2) stepSizeYUm_(0.0012), speedX_(20.0), //[mm/s] speedY_(20.0), //[mm/s] accelX_(0.2), //[m/s²] accelY_(0.2), originX_(0), originY_(0) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // NOTE: pre-initialization properties contain parameters which must be defined fo // proper startup // Name, read-only (RO) CreateProperty(MM::g_Keyword_Name, g_XYStageDeviceName, MM::String, true); // Description, RO CreateProperty(MM::g_Keyword_Description, "Tango XY stage driver adapter", MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &XYStage::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); } XYStage::~XYStage() { Shutdown(); } /////////////////////////////////////////////////////////////////////////////// // XYStage methods required by the API /////////////////////////////////////////////////////////////////////////////// void XYStage::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_XYStageDeviceName); } /* MM::DeviceDetectionStatus XYStage::DetectDevice(void) { return TangoCheckSerialPort(*this,*GetCoreCallback(), port_, answerTimeoutMs_); } */ /** * Performs device initialization. * Additional properties can be defined here too. */ int XYStage::Initialize() { core_ = GetCoreCallback(); int ret = CheckDeviceStatus(); if (ret != DEVICE_OK) return ret; int NumberOfAxes = (Configuration_ >> 4) &0x0f; if (NumberOfAxes < 2) return DEVICE_NOT_CONNECTED; if ((Configuration_ & 7) > 0) { ret = SendCommand("!encpos 1 1"); if (ret != DEVICE_OK) return ret; } // Step size // --------- CPropertyAction* pAct = new CPropertyAction (this, &XYStage::OnStepSizeX); // get current step size from the controller string resp; ret = QueryCommand("?pitch x", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; float pitch; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &pitch); stepSizeXUm_ = pitch/819.2; ret = CreateProperty("StepSizeX [um]", CDeviceUtils::ConvertToString(stepSizeXUm_), MM::Float, false, pAct); // mm/s if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction (this, &XYStage::OnStepSizeY); // get current step size from the controller ret = QueryCommand("?pitch y", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &pitch); stepSizeYUm_ = pitch/819.2; ret = CreateProperty("StepSizeY [um]", CDeviceUtils::ConvertToString(stepSizeYUm_), MM::Float, false, pAct); // mm/s if (ret != DEVICE_OK) return ret; // Speed (in mm/s) // ----- pAct = new CPropertyAction (this, &XYStage::OnSpeedX); // switch to mm/s ret = SendCommand("!dim x 9"); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?vel x", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; ret = CreateProperty("SpeedX [mm/s]", resp.c_str(), MM::Float, false, pAct); // mm/s if (ret != DEVICE_OK) return ret; SetPropertyLimits("SpeedX [mm/s]", 0.001, 100.0); // mm/s pAct = new CPropertyAction (this, &XYStage::OnSpeedY); // switch to mm/s ret = SendCommand("!dim y 9"); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?vel y", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; ret = CreateProperty("SpeedY [mm/s]", resp.c_str(), MM::Float, false, pAct); // mm/s if (ret != DEVICE_OK) return ret; SetPropertyLimits("SpeedY [mm/s]", 0.001, 100.0); // mm/s // Accel (Acceleration (in m/s²) // ----- pAct = new CPropertyAction (this, &XYStage::OnAccelX); ret = QueryCommand("?accel x", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; ret = CreateProperty("Acceleration X [m/s^2]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; SetPropertyLimits("Acceleration X [m/s^2]", 0.01, 2.0); pAct = new CPropertyAction (this, &XYStage::OnAccelY); ret = QueryCommand("?accel y", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; ret = CreateProperty("Acceleration Y [m/s^2]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; SetPropertyLimits("Acceleration Y [m/s^2]", 0.01, 2.0); // Backlash (in µm) ret = QueryCommand("?backlash x", resp); if (ret == DEVICE_OK) { pAct = new CPropertyAction (this, &XYStage::OnBacklashX); ret = CreateProperty("Backlash X [um]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; } ret = QueryCommand("?backlash y", resp); if (ret == DEVICE_OK) { pAct = new CPropertyAction (this, &XYStage::OnBacklashY); ret = CreateProperty("Backlash Y [um]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; } ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int XYStage::Shutdown() { initialized_ = false; range_measured_ = false; return DEVICE_OK; } /** * Returns true if any axis (X or Y) is still moving. */ bool XYStage::Busy() { string resp; int ret; // send command ret = QueryCommand("?statusaxis", resp); if (ret != DEVICE_OK) { ostringstream os; os << "SendSerialCommand failed in XYStage::Busy, error code:" << ret; this->LogMessage(os.str().c_str(), false); // return false; // can't write, continue just so that we can read an answer in case write succeeded even though we received an error } if ((resp[0] == 'M') || (resp[1] == 'M')) return true; else return false; } /** * Returns current position in µm. */ int XYStage::GetPositionUm(double& x, double& y) { int ret; // switch to µm ret = SendCommand("!dim 1 1"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?pos", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float xx, yy; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f %f\r", &xx, &yy); x = xx; y = yy; return DEVICE_OK; } /** * Sets position in µm */ int XYStage::SetPositionUm(double x, double y) { ostringstream os; os << "XYStage::SetPositionUm() " << x << " " << y; this->LogMessage(os.str().c_str()); // switch to µm int ret = SendCommand("!dim 1 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!moa "<< x << " " << y; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /** * Sets relative position in µm */ int XYStage::SetRelativePositionUm(double dx, double dy) { ostringstream os; os << "XYStage::SetPositionUm() " << dx << " " << dy; this->LogMessage(os.str().c_str()); // switch to µm int ret = SendCommand("!dim 1 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!mor "<< dx << " " << dy; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /** * Sets position in steps. */ int XYStage::SetPositionSteps(long x, long y) { // switch to steps int ret = SendCommand("!dim 0 0"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!moa "<< x << " " << y; ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /** * Sets relative position in steps. */ int XYStage::SetRelativePositionSteps(long x, long y) { // switch to steps int ret = SendCommand("!dim 0 0"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!mor "<< x << " " << y; ret = SendCommand(cmd.str().c_str()); return ret; } /** * Returns current position in steps. */ int XYStage::GetPositionSteps(long& x, long& y) { // switch to steps int ret = SendCommand("!dim 0 0"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?pos", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is(resp); is >> x; is >> y; return DEVICE_OK; } /** * Defines current position as origin (0,0) coordinate of the controller. */ int XYStage::SetOrigin() { int ret = SendCommand("!pos 0 0"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return SetAdapterOrigin(); } /** * Defines current position as origin (0,0) coordinate of our coordinate system * Get the current (stage-native) XY position * This is going to be the origin in our coordinate system * The Tango stage X axis is the same orientation as out coordinate system, the Y axis is reversed */ int XYStage::SetAdapterOrigin() { double xx, yy; int ret = GetPositionUm(xx, yy); if (ret != DEVICE_OK) return ret; originX_ = xx; originY_ = yy; return DEVICE_OK; } /** * Defines current position as (x,y) coordinate of the controller. */ int XYStage::SetAdapterOriginUm(double x, double y) { // switch to steps int ret = SendCommand("!dim 1 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!pos "<< x << " " << y; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } int XYStage::Home() { const char* cmd; range_measured_ = false; // format the command cmd = "!cal x"; int ret = SendCommand(cmd); if (ret != DEVICE_OK) return ret; cmd = "!cal y"; ret = SendCommand(cmd); if (ret != DEVICE_OK) return ret; bool status; int numTries=0, maxTries=400; long pollIntervalMs = 100; this->LogMessage("Starting read in XY-Stage HOME\n", true); do { status = Busy(); numTries++; CDeviceUtils::SleepMs(pollIntervalMs); } while(status && (numTries < maxTries)); // keep trying up to maxTries * pollIntervalMs ( = 20 sec) ostringstream os; os << "Tried reading "<< numTries << " times, and finally read " << status; this->LogMessage(os.str().c_str()); // additional range measure to provide GetLimitsUm() cmd = "!rm x"; ret = SendCommand(cmd); if (ret != DEVICE_OK) return ret; cmd = "!rm y"; ret = SendCommand(cmd); if (ret != DEVICE_OK) return ret; this->LogMessage("Starting read in XY-Stage HOME\n", true); do { status = Busy(); numTries++; CDeviceUtils::SleepMs(pollIntervalMs); } while(status && (numTries < maxTries)); // keep trying up to maxTries * pollIntervalMs ( = 20 sec) os << "Tried reading "<< numTries << " times, and finally read " << status; this->LogMessage(os.str().c_str()); if (status) return DEVICE_ERR; range_measured_ = true; return DEVICE_OK; } int XYStage::Stop() { int ret = SendCommand("a x"); ret = SendCommand("a y"); return ret; } /** * Returns the stage position limits in um. */ int XYStage::GetLimitsUm(double& xMin, double& xMax, double& yMin, double& yMax) { if (!range_measured_) return DEVICE_UNKNOWN_POSITION; // switch to µm int ret = SendCommand("!dim 1 1"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?lim x", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float lower, upper; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f %f\r", &lower, &upper); xMin = lower; xMax = upper; ret = QueryCommand("?lim y", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f %f\r", &lower, &upper); yMin = lower; yMax = upper; return DEVICE_OK; } int XYStage::Move(double vx, double vy) { // switch to mm/s int ret = SendCommand("!dim 9 9"); if (ret != DEVICE_OK) return ret; // if vx and vy are not in mm/s then please convert here to mm/s double vx_ = vx; double vy_ = vy; // format the command ostringstream cmd; cmd << "!speed "<< vx_ << " " << vy_; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } int XYStage::GetStepLimits(long& xMin, long& xMax, long& yMin, long& yMax) { // switch to steps int ret = SendCommand("!dim 0 0"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?lim x", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; long lower, upper; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%ld %ld\r", &lower, &upper); xMin = lower; xMax = upper; ret = QueryCommand("?lim y", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%ld %ld\r", &lower, &upper); yMin = lower; yMax = upper; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers // Handle changes and updates to property values. /////////////////////////////////////////////////////////////////////////////// int XYStage::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int XYStage::OnStepSizeX(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // get current step size from the controller string resp; int ret = QueryCommand("?pitch x", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; float pitch; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &pitch); double stepSizeXUm = pitch/819.2; pProp->Set(stepSizeXUm); } else if (eAct == MM::AfterSet) { double stepSize; pProp->Get(stepSize); if (stepSize <= 0.0) { pProp->Set(stepSizeXUm_); return DEVICE_INVALID_INPUT_PARAM; } stepSizeXUm_ = stepSize; } return DEVICE_OK; } int XYStage::OnStepSizeY(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // get current step size from the controller string resp; int ret = QueryCommand("?pitch y", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; float pitch; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &pitch); double stepSizeYUm = pitch/819.2; pProp->Set(stepSizeYUm); } else if (eAct == MM::AfterSet) { double stepSize; pProp->Get(stepSize); if (stepSize <= 0.0) { pProp->Set(stepSizeYUm_); return DEVICE_INVALID_INPUT_PARAM; } stepSizeYUm_ = stepSize; } return DEVICE_OK; } /* * Speed as returned by device is in mm/s * We convert that to um per second using the factor 1000 */ int XYStage::OnSpeedX(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // switch to mm/s int ret = SendCommand("!dim x 9"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?vel x", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double speedX = atof(tokens.at(0).c_str()); speedX_ = speedX; pProp->Set(speedX_); } else if (eAct == MM::AfterSet) { // switch to mm/s int ret = SendCommand("!dim x 9"); if (ret != DEVICE_OK) return ret; double uiSpeed; // Speed in mm/sec pProp->Get(uiSpeed); double speed = uiSpeed; ostringstream cmd; cmd << "!vel x " << speed; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; speedX_ = speed; } return DEVICE_OK; } int XYStage::OnSpeedY(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // switch to mm/s int ret = SendCommand("!dim y 9"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?vel y", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double speedY = atof(tokens.at(0).c_str()); speedY_ = speedY; pProp->Set(speedY_); } else if (eAct == MM::AfterSet) { // switch to mm/s int ret = SendCommand("!dim y 9"); if (ret != DEVICE_OK) return ret; double uiSpeed; // Speed in mm/sec pProp->Get(uiSpeed); double speed = uiSpeed; ostringstream cmd; cmd << "!vel y " << speed; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; speedY_ = speed; } return DEVICE_OK; } int XYStage::OnAccelX(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?accel x", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double accelX = atof(tokens.at(0).c_str()); accelX_ = accelX; pProp->Set(accelX_); } else if (eAct == MM::AfterSet) { double accel; pProp->Get(accel); if (accel < 0.001) accel = 0.001; //clipping to useful values if (accel > 10.0 ) accel = 10.0; ostringstream cmd; cmd << "!accel x " << accel; int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; accelX_ = accel; } return DEVICE_OK; } int XYStage::OnAccelY(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?accel y", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double accelY = atof(tokens.at(0).c_str()); accelY_ = accelY; pProp->Set(accelY_); } else if (eAct == MM::AfterSet) { double accel; pProp->Get(accel); if (accel < 0.001) accel = 0.001; //clipping to useful values if (accel > 10.0 ) accel = 10.0; ostringstream cmd; cmd << "!accel y " << accel; int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; accelY_ = accel; } return DEVICE_OK; } int XYStage::OnBacklashX(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?backlash x", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double backlash_ = atof(tokens.at(0).c_str()); pProp->Set(backlash_); } else if (eAct == MM::AfterSet) { double backlash; pProp->Get(backlash); ostringstream cmd; cmd << "!backlash x " << backlash; int ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; } return DEVICE_OK; } int XYStage::OnBacklashY(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?backlash y", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double backlash_ = atof(tokens.at(0).c_str()); pProp->Set(backlash_); } else if (eAct == MM::AfterSet) { double backlash; pProp->Get(backlash); if (backlash < 0.0) backlash = 0.0; //clipping to useful values if (backlash > 10.0) backlash = 10.0; ostringstream cmd; cmd << "!backlash y " << backlash; int ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Z - Stage /////////////////////////////////////////////////////////////////////////////// /** * Single axis stage. */ ZStage::ZStage() : TangoBase(this), range_measured_(false), stepSizeUm_(0.1), speedZ_(20.0), //[mm/s] accelZ_(0.2), //[m/s²] originZ_(0), sequenceable_(false), nrEvents_(1024) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_ZStageDeviceName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Tango Z axis driver", MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &ZStage::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); } ZStage::~ZStage() { Shutdown(); } /////////////////////////////////////////////////////////////////////////////// // Stage methods required by the API /////////////////////////////////////////////////////////////////////////////// void ZStage::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_ZStageDeviceName); } /* MM::DeviceDetectionStatus ZStage::DetectDevice(void) { return TangoCheckSerialPort(*this,*GetCoreCallback(), port_, answerTimeoutMs_); } */ int ZStage::Initialize() { core_ = GetCoreCallback(); int ret = CheckDeviceStatus(); if (ret != DEVICE_OK) return ret; int NumberOfAxes = (Configuration_ >> 4) &0x0f; if (NumberOfAxes < 3) return DEVICE_NOT_CONNECTED; if ((Configuration_ & 7) > 0) { ret = SendCommand("!encpos z 1"); if (ret != DEVICE_OK) return ret; } // set property list // ----------------- // Step size // --------- CPropertyAction* pAct = new CPropertyAction (this, &ZStage::OnStepSize); // get current step size from the controller string resp; ret = QueryCommand("?pitch z", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; float pitch; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &pitch); stepSizeUm_ = pitch/819.2; ret = CreateProperty("StepSize [um]", CDeviceUtils::ConvertToString(stepSizeUm_), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; // switch to mm/s ret = SendCommand("!dim z 9"); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?vel z", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; pAct = new CPropertyAction (this, &ZStage::OnSpeed); ret = CreateProperty("SpeedZ [mm/s]", resp.c_str(), MM::Float, false, pAct); // mm/s if (ret != DEVICE_OK) return ret; SetPropertyLimits("SpeedZ [mm/s]", 0.001, 100.0); // mm/s // Accel (Acceleration (in m/s²) // ----- ret = QueryCommand("?accel z", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; pAct = new CPropertyAction (this, &ZStage::OnAccel); ret = CreateProperty("Acceleration Z [m/s^2]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; SetPropertyLimits("Acceleration Z [m/s^2]", 0.01, 2.0); // Backlash (in µm) // get current Backlash from the controller ret = QueryCommand("?backlash z", resp); if (ret == DEVICE_OK) { pAct = new CPropertyAction (this, &ZStage::OnBacklash); ret = CreateProperty("Backlash Z [um]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; } // verify if sequenceable e.g. if snapshot buffer is configured if ((Configuration_ & 0x0800) == 0x0800) { sequenceable_ = true; CPropertyAction* pAct = new CPropertyAction (this, &ZStage::OnSequence); const char* spn = "Use Sequence"; CreateProperty(spn, "No", MM::String, false, pAct); AddAllowedValue(spn, "No"); AddAllowedValue(spn, "Yes"); } ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int ZStage::Shutdown() { initialized_ = false; range_measured_ = false; return DEVICE_OK; } bool ZStage::Busy() { string resp; int ret; // send command ret = QueryCommand("?statusaxis", resp); if (ret != DEVICE_OK) { ostringstream os; os << "SendSerialCommand failed in ZStage::Busy, error code:" << ret; this->LogMessage(os.str().c_str(), false); // return false; // can't write, continue just so that we can read an answer in case write succeeded even though we received an error } if (resp[2] == 'M') return true; else return false; } int ZStage::Stop() { int ret; ret = SendCommand("a z"); return ret; } int ZStage::SetPositionUm(double pos) { ostringstream os; os << "ZStage::SetPositionUm() " << pos; this->LogMessage(os.str().c_str()); // switch to µm int ret = SendCommand("!dim z 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!moa z " << pos; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int ZStage::SetRelativePositionUm(double d) { // switch to µm int ret = SendCommand("!dim z 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!mor z " << d; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int ZStage::GetPositionUm(double& pos) { int ret; // switch to µm ret = SendCommand("!dim z 1"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?pos z", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float zz; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &zz); pos = zz; ostringstream os; os << "ZStage::GetPositionUm() " << pos; this->LogMessage(os.str().c_str()); return DEVICE_OK; } int ZStage::SetPositionSteps(long pos) { int ret; // switch to steps ret = SendCommand("!dim z 0"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "MOA Z " << pos; string resp; ret = QueryCommand(cmd.str().c_str(), resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int ZStage::GetPositionSteps(long& steps) { int ret; // switch to steps ret = SendCommand("!dim z 0"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?pos z", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is(resp); is >> steps; return DEVICE_OK; } int ZStage::SetAdapterOrigin() { double zz; int ret = GetPositionUm(zz); if (ret != DEVICE_OK) return ret; originZ_ = zz; return DEVICE_OK; } int ZStage::SetOrigin() { int ret = SendCommand("!pos z 0"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?status", resp); if (ret != DEVICE_OK) return ret; if (resp.compare("OK...") != 0) { return DEVICE_SERIAL_INVALID_RESPONSE; } return SetAdapterOrigin(); } /** * Defines current position as (d) coordinate of the controller. */ int ZStage::SetAdapterOriginUm(double d) { // switch to steps int ret = SendCommand("!dim z 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!pos z "<< d; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } int ZStage::Move(double v) { // switch to mm/s int ret = SendCommand("!dim z 9"); if (ret != DEVICE_OK) return ret; // if v is not in mm/s then please convert here to mm/s double v_ = v; // format the command ostringstream cmd; cmd << "!speed z "<< v_; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /** * Returns the stage position limits in um. */ int ZStage::GetLimits(double& min, double& max) { if (!range_measured_) return DEVICE_UNKNOWN_POSITION; // switch to µm int ret = SendCommand("!dim z 1"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?lim z", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float lower, upper; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f %f\r", &lower, &upper); min = lower; max = upper; return DEVICE_OK; } int ZStage::StartStageSequence() { ostringstream cmd; string resp; int err; cmd << "!snsi 0"; // ensure that ringbuffer pointer points to first entry and that we only trigger the Z axis int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; cmd << "!axis 0 0"; //prevent XY from moving. So far no XY sequence is stored and this fast mode is for Z-stack application only ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is2(resp); is2 >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; cmd << "!snsm 4"; // use Tango snapshot mode 4 to TTL step through list ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is3(resp); is3 >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int ZStage::StopStageSequence() { ostringstream cmd; cmd << "!sns 0"; //disable snapshot mode int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; cmd << "!axis 1 1"; //enable XY again ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is2(resp); is2 >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int ZStage::SendStageSequence() { // first stop any pending actions ostringstream cmd; cmd << "!snsm 0"; int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; // clear the buffer in the device // format the command cmd << "!snsa 0"; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is2(resp); is2 >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; // switch to µm ret = SendCommand("!dim z 1"); if (ret != DEVICE_OK) return ret; ostringstream os; os.precision(1); for (unsigned i=0; i< sequence_.size(); i++) { os << "!snsa z " << sequence_[i]; ret = SendCommand(os.str().c_str()); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is3(resp); is3 >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; } return DEVICE_OK; } int ZStage::ClearStageSequence() { sequence_.clear(); // clear the buffer in the device // format the command ostringstream cmd; cmd << "!snsa 0"; int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } int ZStage::AddToStageSequence(double position) { sequence_.push_back(position); return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers // Handle changes and updates to property values. /////////////////////////////////////////////////////////////////////////////// int ZStage::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int ZStage::OnSpeed(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // switch to mm/s int ret = SendCommand("!dim z 9"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?vel z", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double speed = atof(tokens.at(0).c_str()); speedZ_ = speed; pProp->Set(speedZ_); } else if (eAct == MM::AfterSet) { // switch to mm/s int ret = SendCommand("!dim z 9"); if (ret != DEVICE_OK) return ret; double uiSpeed; // Speed in mm/sec pProp->Get(uiSpeed); double speed = uiSpeed; ostringstream cmd; cmd << "!vel z " << speed; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; speedZ_ = speed; } return DEVICE_OK; } int ZStage::OnAccel(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?accel z", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double accel = atof(tokens.at(0).c_str()); accelZ_ = accel; pProp->Set(accelZ_); } else if (eAct == MM::AfterSet) { double accel; pProp->Get(accel); if (accel < 0.001) accel = 0.001; //clipping to useful values if (accel > 10.0 ) accel = 10.0; ostringstream cmd; cmd << "!accel z " << accel; int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; accelZ_ = accel; } return DEVICE_OK; } int ZStage::OnBacklash(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?backlash z", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double backlash_ = atof(tokens.at(0).c_str()); pProp->Set(backlash_); } else if (eAct == MM::AfterSet) { double backlash; pProp->Get(backlash); if (backlash < 0.0) backlash = 0.0; //clipping to useful values if (backlash > 10.0) backlash = 10.0; ostringstream cmd; cmd << "!backlash z " << backlash; int ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; } return DEVICE_OK; } int ZStage::OnSequence(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { if (sequenceable_) pProp->Set("Yes"); else pProp->Set("No"); } else if (eAct == MM::AfterSet) { std::string prop; pProp->Get(prop); sequenceable_ = false; if (prop == "Yes") sequenceable_ = true; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int ZStage::OnStepSize(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(stepSizeUm_); } else if (eAct == MM::AfterSet) { double stepSize; pProp->Get(stepSize); if (stepSize <= 0.0) { pProp->Set(stepSizeUm_); return DEVICE_INVALID_INPUT_PARAM; } stepSizeUm_ = stepSize; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // A - Stage /////////////////////////////////////////////////////////////////////////////// /** * Single axis stage. */ AStage::AStage() : TangoBase(this), range_measured_(false), speed_(20.0), //[mm/s] accel_(0.2), //[m/s²] origin_(0), stepSizeUm_(0.1) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_AStageDeviceName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Tango A axis driver", MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &AStage::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); } AStage::~AStage() { Shutdown(); } /////////////////////////////////////////////////////////////////////////////// // Stage methods required by the API /////////////////////////////////////////////////////////////////////////////// void AStage::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_AStageDeviceName); } /* MM::DeviceDetectionStatus AStage::DetectDevice(void) { return TangoCheckSerialPort(*this,*GetCoreCallback(), port_, answerTimeoutMs_); } */ int AStage::Initialize() { core_ = GetCoreCallback(); int ret = CheckDeviceStatus(); if (ret != DEVICE_OK) return ret; int NumberOfAxes = (Configuration_ >> 4) &0x0f; if (NumberOfAxes < 4) return DEVICE_NOT_CONNECTED; // set property list // ----------------- // Step size // --------- CPropertyAction* pAct = new CPropertyAction (this, &AStage::OnStepSize); // get current step size from the controller string resp; ret = QueryCommand("?pitch a", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; float pitch; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &pitch); stepSizeUm_ = pitch/819.2; ret = CreateProperty("StepSize [um]", CDeviceUtils::ConvertToString(stepSizeUm_), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; // switch to mm/s ret = SendCommand("!dim a 9"); if (ret != DEVICE_OK) return ret; ret = QueryCommand("?vel a", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; pAct = new CPropertyAction (this, &AStage::OnSpeed); ret = CreateProperty("SpeedA [mm/s]", resp.c_str(), MM::Float, false, pAct); // mm/s if (ret != DEVICE_OK) return ret; SetPropertyLimits("SpeedA [mm/s]", 0.001, 100.0); // mm/s // Accel (Acceleration (in m/s²) // ----- ret = QueryCommand("?accel a", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; pAct = new CPropertyAction (this, &AStage::OnAccel); ret = CreateProperty("Acceleration A [m/s^2]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; SetPropertyLimits("Acceleration A [m/s^2]", 0.01, 2.0); // Backlash (in µm) // get current Backlash from the controller ret = QueryCommand("?backlash a", resp); if (ret == DEVICE_OK) { pAct = new CPropertyAction (this, &AStage::OnBacklash); ret = CreateProperty("Backlash Z [um]", resp.c_str(), MM::Float, false, pAct); if (ret != DEVICE_OK) return ret; } ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int AStage::Shutdown() { initialized_ = false; range_measured_ = false; return DEVICE_OK; } bool AStage::Busy() { string resp; int ret; // send command ret = QueryCommand("?statusaxis", resp); if (ret != DEVICE_OK) { ostringstream os; os << "SendSerialCommand failed in AStage::Busy, error code:" << ret; this->LogMessage(os.str().c_str(), false); // return false; // can't write, continue just so that we can read an answer in case write succeeded even though we received an error } if (resp[3] == 'M') return true; else return false; } int AStage::Stop() { int ret; ret = SendCommand("a a"); return ret; } int AStage::SetPositionUm(double pos) { ostringstream os; os << "AStage::SetPositionUm() " << pos; this->LogMessage(os.str().c_str()); // switch to µm int ret = SendCommand("!dim a 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!moa a " << pos; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int AStage::SetRelativePositionUm(double d) { // switch to µm int ret = SendCommand("!dim a 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!mor a " << d; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int AStage::GetPositionUm(double& pos) { int ret; // switch to µm ret = SendCommand("!dim a 1"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?pos a", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float aa; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &aa); pos = aa; ostringstream os; os << "AStage::GetPositionUm() " << pos; this->LogMessage(os.str().c_str()); return DEVICE_OK; } int AStage::SetPositionSteps(long pos) { int ret; // switch to steps ret = SendCommand("!dim a 0"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "MOA A " << pos; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int AStage::GetPositionSteps(long& steps) { int ret; // switch to steps ret = SendCommand("!dim a 0"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?pos a", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; istringstream is(resp); is >> steps; return DEVICE_OK; } int AStage::SetAdapterOrigin() { double aa; int ret = GetPositionUm(aa); if (ret != DEVICE_OK) return ret; origin_ = aa; return DEVICE_OK; } int AStage::SetOrigin() { int ret = SendCommand("!pos a 0"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?status", resp); if (ret != DEVICE_OK) return ret; if (resp.compare("OK...") != 0) { return DEVICE_SERIAL_INVALID_RESPONSE; } return SetAdapterOrigin(); } /** * Defines current position as (d) coordinate of the controller. */ int AStage::SetAdapterOriginUm(double d) { // switch to steps int ret = SendCommand("!dim a 1"); if (ret != DEVICE_OK) return ret; // format the command ostringstream cmd; cmd << "!pos a "<< d; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } int AStage::Move(double v) { // switch to mm/s int ret = SendCommand("!dim a 9"); if (ret != DEVICE_OK) return ret; // if v is not in mm/s then please convert here to mm/s double v_ = v; // format the command ostringstream cmd; cmd << "!speed a "<< v_; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /** * Returns the stage position limits in um. */ int AStage::GetLimits(double& min, double& max) { if (!range_measured_) return DEVICE_UNKNOWN_POSITION; // switch to µm int ret = SendCommand("!dim a 1"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?lim a", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float lower, upper; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f %f\r", &lower, &upper); min = lower; max = upper; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers // Handle changes and updates to property values. /////////////////////////////////////////////////////////////////////////////// int AStage::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int AStage::OnSpeed(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // switch to mm/s int ret = SendCommand("!dim a 9"); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?vel a", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double speed = atof(tokens.at(0).c_str()); speed_ = speed; pProp->Set(speed_); } else if (eAct == MM::AfterSet) { // switch to mm/s int ret = SendCommand("!dim a 9"); if (ret != DEVICE_OK) return ret; double uiSpeed; // Speed in mm/sec pProp->Get(uiSpeed); double speed = uiSpeed; ostringstream cmd; cmd << "!vel a " << speed; ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; speed_ = speed; } return DEVICE_OK; } int AStage::OnAccel(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?accel a", resp); if (ret != DEVICE_OK) return ret; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double accel = atof(tokens.at(0).c_str()); accel_ = accel; pProp->Set(accel_); } else if (eAct == MM::AfterSet) { double accel; pProp->Get(accel); if (accel < 0.001) accel = 0.001; //clipping to useful values if (accel > 10.0 ) accel = 10.0; ostringstream cmd; cmd << "!accel a " << accel; int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; accel_ = accel; } return DEVICE_OK; } int AStage::OnBacklash(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { string resp; int ret = QueryCommand("?backlash a", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; // tokenize on space: stringstream ss(resp); string buf; vector<string> tokens; while (ss >> buf) tokens.push_back(buf); double backlash_ = atof(tokens.at(0).c_str()); pProp->Set(backlash_); } else if (eAct == MM::AfterSet) { double backlash; pProp->Get(backlash); if (backlash < 0.0) backlash = 0.0; //clipping to useful values if (backlash > 10.0) backlash = 10.0; ostringstream cmd; cmd << "!backlash a " << backlash; int ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int AStage::OnStepSize(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(stepSizeUm_); } else if (eAct == MM::AfterSet) { double stepSize; pProp->Get(stepSize); if (stepSize <= 0.0) { pProp->Set(stepSizeUm_); return DEVICE_INVALID_INPUT_PARAM; } stepSizeUm_ = stepSize; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Shutter // ~~~~~~~ Shutter::Shutter() : TangoBase(this), name_(g_ShutterName) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &Shutter::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); UpdateStatus(); } Shutter::~Shutter() { Shutdown(); } void Shutter::GetName(char* name) const { CDeviceUtils::CopyLimitedString(name, name_.c_str()); } /* MM::DeviceDetectionStatus Shutter::DetectDevice(void) { return TangoCheckSerialPort(*this,*GetCoreCallback(), port_, answerTimeoutMs_); } */ int Shutter::Initialize() { core_ = GetCoreCallback(); int ret = CheckDeviceStatus(); if (ret != DEVICE_OK) return ret; // set property list // ----------------- // State // ----- CPropertyAction* pAct = new CPropertyAction (this, &Shutter::OnState); // get current Shutter state from the controller string resp; ret = QueryCommand("?shutter", resp); if (ret != DEVICE_OK) return DEVICE_UNSUPPORTED_COMMAND; ret = CreateProperty(MM::g_Keyword_State, resp.c_str(), MM::Integer, false, pAct); if (ret != DEVICE_OK) return ret; AddAllowedValue(MM::g_Keyword_State, "0"); // low = closed AddAllowedValue(MM::g_Keyword_State, "1"); // high = open ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int Shutter::Shutdown() { if (initialized_) { initialized_ = false; } return DEVICE_OK; } bool Shutter::Busy() { return false; } int Shutter::SetOpen(bool open) { long pos; if (open) pos = 1; else pos = 0; return SetProperty(MM::g_Keyword_State, CDeviceUtils::ConvertToString(pos)); } int Shutter::GetOpen(bool& open) { char buf[MM::MaxStrLength]; int ret = GetProperty(MM::g_Keyword_State, buf); if (ret != DEVICE_OK) return ret; long pos = atol(buf); pos == 1 ? open = true : open = false; return DEVICE_OK; } int Shutter::Fire(double /*deltaT*/) { return DEVICE_UNSUPPORTED_COMMAND; } /** * Sends an open/close command through the serial port. */ int Shutter::SetShutterPosition(bool state) { ostringstream cmd; if (state) cmd << "!shutter 1"; else cmd << "!shutter 0"; int ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /** * Check the state of the shutter. */ int Shutter::GetShutterPosition(bool& state) { // request shutter status string resp; int ret = QueryCommand("?shutter", resp); if (ret !=DEVICE_OK) return ret; if (resp.size() != 1) return DEVICE_SERIAL_INVALID_RESPONSE; int x = atoi(resp.substr(1,2).c_str()); if (x == 0) state = false; else if (x == 1) state = true; else return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers // Handle changes and updates to property values. /////////////////////////////////////////////////////////////////////////////// int Shutter::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int Shutter::OnState(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { bool open; int ret = GetShutterPosition(open); if (ret != DEVICE_OK) return ret; if (open) pProp->Set((long)1); else pProp->Set((long)0); } else if (eAct == MM::AfterSet) { long state; pProp->Get(state); if (state == 1) return SetShutterPosition(true); else if (state == 0) return SetShutterPosition(false); } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Tango LED100 /////////////////////////////////////////////////////////////////////////////// LED100::LED100 (const char* name, int id) : TangoBase(this), name_ (name), id_(id), intensity_(0), fireT_(0) { InitializeDefaultErrorMessages(); // Port CPropertyAction* pAct = new CPropertyAction (this, &LED100::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); } LED100::~LED100() { Shutdown(); } void LED100::GetName(char* name) const { assert(name_.length() < CDeviceUtils::GetMaxStringLength()); CDeviceUtils::CopyLimitedString(name, name_.c_str()); } int LED100::GetIntensity(double& intensity) { // request lamp intensity ostringstream cmd; cmd << "?anaout c " << id_; string resp; int ret = QueryCommand(cmd.str().c_str(), resp); if (ret !=DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float percent; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &percent); intensity = percent; return DEVICE_OK; } int LED100::SetIntensity(double intensity) { // format the command ostringstream cmd; cmd << "!anaout c " << id_ << " " << intensity; int ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /* MM::DeviceDetectionStatus LED100::DetectDevice(void) { return TangoCheckSerialPort(*this,*GetCoreCallback(), port_, answerTimeoutMs_); } */ int LED100::Initialize() { core_ = GetCoreCallback(); int ret = CheckDeviceStatus(); if (ret != DEVICE_OK) return ret; CPropertyAction* pAct; // Name ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); if (DEVICE_OK != ret) return ret; // Description ret = CreateProperty(MM::g_Keyword_Description, "Tango LED100", MM::String, true); if (DEVICE_OK != ret) return ret; // get current intensity from the controller double intensity; ret = GetIntensity(intensity); if (ret == DEVICE_OK) { pAct = new CPropertyAction(this, &LED100::OnIntensity); CreateProperty("Intensity", CDeviceUtils::ConvertToString(intensity_), MM::Float, false, pAct); SetPropertyLimits("Intensity", 0.0, 100.0); // [0..100] percent (= [0..10V]) // State pAct = new CPropertyAction (this, &LED100::OnState); if (intensity_ > 0) ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct); else ret = CreateProperty(MM::g_Keyword_State, "0", MM::Integer, false, pAct); if (ret != DEVICE_OK) return ret; AddAllowedValue(MM::g_Keyword_State, "0"); // Closed AddAllowedValue(MM::g_Keyword_State, "1"); // Open } // Fire // create property Fire if Tango command flash is possible with this version ostringstream cmd; cmd << "!flash -0.01"; //example 10µs pulse ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err == 0) { pAct = new CPropertyAction(this, &LED100::OnFire); CreateProperty("Fire", "0.0", MM::Float, false, pAct); } ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } bool LED100::Busy() { return false; } int LED100::Shutdown() { initialized_ = false; return DEVICE_OK; } int LED100::SetOpen(bool open) { ostringstream cmd; if (open) cmd << "!adigout 0 0"; else cmd << "!adigout 0 1"; int ret = SendCommand(cmd.str().c_str()); if (ret !=DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; if (resp != "0") return DEVICE_SERIAL_INVALID_RESPONSE; return DEVICE_OK; } int LED100::GetOpen(bool &open) { string resp; int ret = QueryCommand("?adigout 0", resp); if (ret != DEVICE_OK) return ret; if (resp == "0") { open = true; return DEVICE_OK; } else if (resp == "1") { open = false; return DEVICE_OK; } else return DEVICE_SERIAL_INVALID_RESPONSE; } // this supports Tango precision timer output (as used in conjunction with LED100 device) int LED100::Fire(double deltaT) //assume unit is [ms] { ostringstream cmd; int ret; string resp; double dT = - fabs(deltaT); //LED100 hardware uses negative polarity to open shutter (see Tango reference manual). cmd << "!flash " << dT; ret = SendCommand(cmd.str().c_str()); return ret; } /////////////////////////////////////////////////////////////////////////////// // Action handlers // Handle changes and updates to property values. /////////////////////////////////////////////////////////////////////////////// int LED100::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int LED100::OnState(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // get LED100 shutter state from Tango bool open; GetOpen(open); if (open) pProp->Set(1L); else pProp->Set(0L); } else if (eAct == MM::AfterSet) { int ret; long pos; pProp->Get(pos); if (pos==1) { ret = this->SetOpen(true); } else { ret = this->SetOpen(false); } if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int LED100::OnIntensity(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { int ret = GetIntensity(intensity_); if (ret != DEVICE_OK) return ret; pProp->Set(intensity_); //(long) } else if (eAct == MM::AfterSet) { double intensity; pProp->Get(intensity); int ret = SetIntensity(intensity); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int LED100::OnFire(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(fireT_); } else if (eAct == MM::AfterSet) { double fireT; pProp->Get(fireT); fireT_ = fireT; int ret = Fire(fireT_); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Tango DAC /////////////////////////////////////////////////////////////////////////////// DAC::DAC () : TangoBase(this), DACPort_(0), name_ (g_DACName), open_(false) { InitializeDefaultErrorMessages(); // Port CPropertyAction* pAct = new CPropertyAction (this, &DAC::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); // DAC Port pAct = new CPropertyAction (this, &DAC::OnDACPort); CreateProperty("DACPort", "0", MM::Integer, false, pAct,true); std::vector<std::string> vals; vals.push_back("0"); vals.push_back("1"); vals.push_back("2"); SetAllowedValues("DACPort", vals); } DAC::~DAC() { Shutdown(); } void DAC::GetName(char* name) const { assert(name_.length() < CDeviceUtils::GetMaxStringLength()); CDeviceUtils::CopyLimitedString(name, name_.c_str()); } int DAC::GetSignal(double& volts) { // request DAC intensity ostringstream cmd; cmd << "?anaout c " << DACPort_; string resp; int ret = QueryCommand(cmd.str().c_str(), resp); if (ret !=DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; float percent; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%f\r", &percent); volts = percent / 10; return DEVICE_OK; } int DAC::SetSignal(double volts) { // format the command ostringstream cmd; cmd << "!anaout c " << DACPort_ << " " << (volts * 10); int ret = SendCommand(cmd.str().c_str()); if (ret != DEVICE_OK) return ret; string resp; ret = QueryCommand("?err", resp); if (ret != DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int err; istringstream is(resp); is >> err; if (err != 0) return DEVICE_SERIAL_INVALID_RESPONSE; else return DEVICE_OK; } /* MM::DeviceDetectionStatus DAC::DetectDevice(void) { return TangoCheckSerialPort(*this,*GetCoreCallback(), port_, answerTimeoutMs_); } */ int DAC::Initialize() { core_ = GetCoreCallback(); int ret = CheckDeviceStatus(); if (ret != DEVICE_OK) return ret; // Name ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); if (DEVICE_OK != ret) return ret; // Description ret = CreateProperty(MM::g_Keyword_Description, "Tango DAC", MM::String, true); if (DEVICE_OK != ret) return ret; // Check current intensity of DAC ret = GetSignal(volts_); if (DEVICE_OK != ret) return ret; // State CPropertyAction* pAct = new CPropertyAction (this, &DAC::OnState); if (volts_ > 0) ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct); else ret = CreateProperty(MM::g_Keyword_State, "0", MM::Integer, false, pAct); if (ret != DEVICE_OK) return ret; AddAllowedValue(MM::g_Keyword_State, "0"); // Closed AddAllowedValue(MM::g_Keyword_State, "1"); // Open // Voltage pAct = new CPropertyAction(this, &DAC::OnVoltage); CreateProperty("Volts", "0.0", MM::Float, false, pAct); SetPropertyLimits("Volts", 0.0, 10.0); // [0..10V] // EnableDelay(); ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } bool DAC::Busy() { return false; } int DAC::Shutdown() { initialized_ = false; return DEVICE_OK; } int DAC::SetGateOpen(bool open) { if (open) { int ret = SetSignal(volts_); if (ret != DEVICE_OK) return ret; open_ = true; } else { int ret = SetSignal(0); if (ret != DEVICE_OK) return ret; open_ = false; } return DEVICE_OK; } int DAC::GetGateOpen(bool &open) { open = open_; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers // Handle changes and updates to property values. /////////////////////////////////////////////////////////////////////////////// int DAC::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int DAC::OnState(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // return pos as we know it bool open; GetGateOpen(open); if (open) { pProp->Set(1L); } else { pProp->Set(0L); } } else if (eAct == MM::AfterSet) { int ret; long pos; pProp->Get(pos); if (pos==1) { ret = this->SetGateOpen(true); } else { ret = this->SetGateOpen(false); } if (ret != DEVICE_OK) return ret; pProp->Set(pos); } return DEVICE_OK; } int DAC::OnVoltage(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { if (open_) { int ret = GetSignal(volts_); if (ret != DEVICE_OK) return ret; } else { // gate is closed. Return the cached value // TODO: check if user changed voltage } pProp->Set(volts_); } else if (eAct == MM::AfterSet) { double intensity; pProp->Get(intensity); volts_ = intensity; if (open_) { int ret = SetSignal(volts_); if (ret != DEVICE_OK) return ret; } } return DEVICE_OK; } int DAC::OnDACPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set((long int)DACPort_); } else if (eAct == MM::AfterSet) { long channel; pProp->Get(channel); if ((channel >= 0) && (channel < MAX_DACHANNELS) ) DACPort_ = channel; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Tango ADC /////////////////////////////////////////////////////////////////////////////// ADC::ADC () : TangoBase(this), name_ (g_ADCName), volts_(0.0), ADCPort_(0) { InitializeDefaultErrorMessages(); // Port CPropertyAction* pAct = new CPropertyAction (this, &ADC::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); // ADC Port pAct = new CPropertyAction (this, &ADC::OnADCPort); CreateProperty("ADCPort", "0", MM::Integer, false, pAct,true); std::vector<std::string> vals; vals.push_back("0"); vals.push_back("1"); vals.push_back("2"); vals.push_back("3"); vals.push_back("4"); vals.push_back("5"); vals.push_back("6"); vals.push_back("7"); vals.push_back("8"); vals.push_back("9"); vals.push_back("10"); vals.push_back("11"); vals.push_back("12"); vals.push_back("13"); vals.push_back("14"); vals.push_back("15"); SetAllowedValues("ADCPort", vals); } ADC::~ADC() { Shutdown(); } void ADC::GetName(char* name) const { assert(name_.length() < CDeviceUtils::GetMaxStringLength()); CDeviceUtils::CopyLimitedString(name, name_.c_str()); } int ADC::GetSignal(double& volts) { // request ADC value ostringstream cmd; cmd << "?anain c " << ADCPort_; string resp; int ret = QueryCommand(cmd.str().c_str(), resp); if (ret !=DEVICE_OK) return ret; if (resp.length() < 1) return DEVICE_SERIAL_INVALID_RESPONSE; int raw; char iBuf[256]; strcpy(iBuf,resp.c_str()); sscanf(iBuf, "%d\r", &raw); volts = (5.0 * raw) / 1023; return DEVICE_OK; } /* MM::DeviceDetectionStatus ADC::DetectDevice(void) { return TangoCheckSerialPort(*this,*GetCoreCallback(), port_, answerTimeoutMs_); } */ int ADC::Initialize() { core_ = GetCoreCallback(); int ret = CheckDeviceStatus(); if (ret != DEVICE_OK) return ret; // Name ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true); if (DEVICE_OK != ret) return ret; // Description ret = CreateProperty(MM::g_Keyword_Description, "Tango ADC", MM::String, true); if (DEVICE_OK != ret) return ret; // Check current intensity of ADC ret = GetSignal(volts_); if (DEVICE_OK != ret) return ret; // Voltage CPropertyAction* pAct = new CPropertyAction(this, &ADC::OnVolts); CreateProperty("Volts", "0.0", MM::Float, false, pAct); SetPropertyLimits("Volts", 0.0, 5.0); // [0..5V] // EnableDelay(); ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int ADC::Shutdown() { initialized_ = false; return DEVICE_OK; } int ADC::SetGateOpen(bool /*open*/) { return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers // Handle changes and updates to property values. /////////////////////////////////////////////////////////////////////////////// int ADC::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int ADC::OnVolts(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { int ret = GetSignal(volts_); if (ret != DEVICE_OK) return ret; pProp->Set(volts_); } return DEVICE_OK; } int ADC::OnADCPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set((long int)ADCPort_); } else if (eAct == MM::AfterSet) { long channel; pProp->Get(channel); if ((channel >= 0) && (channel < MAX_ADCHANNELS) ) ADCPort_ = channel; } return DEVICE_OK; }
{ "content_hash": "b5c24ce307b301d2772775d8c90bf33e", "timestamp": "", "source": "github", "line_count": 3658, "max_line_length": 139, "avg_line_length": 24.744669218151994, "alnum_prop": 0.5538247381678377, "repo_name": "kmdouglass/Micro-Manager", "id": "d5661151f8efc650ae865516c829a0af2aa160a7", "size": "90516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DeviceAdapters/Marzhauser/Marzhauser.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "11345" }, { "name": "Matlab", "bytes": "78981" } ], "symlink_target": "" }
#ifndef AGENT_H_ #define AGENT_H_ #include <algorithm> #include <fstream> #include <sstream> #include <string> #include <iostream> #include <list> #include <vector> #include <math.h> #include <float.h> #include <Eigen/Eigen> #include "Learning/NeuroEvo.h" #include "Utilities/Utilities.h" #include "Domains/Target.h" #include "Domains/State.h" #ifndef PI #define PI 3.14159265358979323846264338328 #endif using std::string; using std::vector; using std::list; using std::max; using easymath::pi_2_pi; enum class Fitness {G, D}; class Agent { public: Agent(size_t n, size_t nPop, size_t nInput, size_t nHidden, size_t nOutput, Fitness f); virtual ~Agent(); // Computes the input to the neural network using a list of actor joint states // // The returned VectorXd will be the same size as nInput // // This function is a pure virtual function. virtual VectorXd ComputeNNInput(vector<Vector2d> jointState) const = 0; vector< double > getVectorState(vector<State>); // Calculates the new State from the ith neural network in the CCEA pool // using the result of ComputeNNInput with the jointstate as input. // // Updates both currentXY and currentPsi // // Is implemented. Should only be overriden when the NN does not directly return // a new position (ie, when it chooses between two other networks). virtual State executeNNControlPolicy(size_t, vector<State>); virtual State getNextState(size_t, vector<State>) const; void move(State); // Sets initial simulation parameters, including rover positions. Clears // evaluation storage vector. virtual void initialiseNewLearningEpoch(State s); // Sets initial simulation parameters, including rover positions. Clears // evaluation storage vector. Intended for use with POIs // // Base functionality is to ignore the first argument. virtual void initialiseNewLearningEpoch(State s, vector<Target>); virtual void DifferenceEvaluationFunction(vector<Vector2d>, double) = 0; // The Reward an agent receives at a given time step. virtual double getReward() { return 0.0; } // Returns a jointstate that has the agent's state replaced with a // counterfactual state. The default is the intial state (ie, if the // agent had not moved at all). vector<Vector2d> substituteCounterfactual(vector<Vector2d> jointState); vector<Vector2d> substituteCounterfactual(vector<Vector2d>, double, double); // Evolves the NeuroEvo, using the epochEvals score. When init is true, // only mutates the population. void EvolvePolicies(bool init = false); // Writes the neural networks to file void OutputNNs(std::string); // Sets the epoch values to 0 (for new scenario) void ResetEpochEvals(); // Sets the performance for the epoch and position i to either G or stepwise D void SetEpochPerformance(double G, size_t i); vector<double> GetEpochEvals() const{ return epochEvals; } double getCurrentPsi() const { return currentState.psi(); } double getInitialPsi() const { return initialState.psi(); } Vector2d getCurrentXY() const { return currentState.pos(); } Vector2d getInitialXY() const { return initialState.pos(); } State getCurrentState() const { return currentState; } State getInitialState() const { return initialState; } NeuroEvo * GetNEPopulation() const { return AgentNE; } void setOutputBool(bool toggle) { printOutput = toggle; } void openOutputFile(std::string filename); virtual Agent* copyAgent() const = 0; friend std::ostream& operator<<(std::ostream&, const Agent&); private: size_t nSteps; size_t popSize; size_t numHidden; size_t numOut; NeuroEvo* AgentNE; std::vector<double> epochEvals; void ResetStepwiseEval(); unsigned id; protected: Matrix2d RotationMatrix(double psi) const; Fitness fitness; State initialState; State currentState; size_t numIn; double stepwiseD; // Determines the index of this agent's position in a jointState vector size_t selfIndex(vector<Vector2d> jointState) const; bool printOutput; std::ofstream outputFile; void setNets(NeuroEvo* nets) { AgentNE = nets; } size_t getSteps() const { return nSteps; } size_t getPop() const { return popSize; } Fitness getFitness() const { return fitness; } }; #endif // AGENT_H_
{ "content_hash": "15efac3a096a93ef663fe69d529610d6", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 82, "avg_line_length": 28.543046357615893, "alnum_prop": 0.7262180974477959, "repo_name": "eklinkhammer/aadil", "id": "5a2c36ed2021d5be027717a5cd00ba35cdeb932f", "size": "5659", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/Agents/Agent.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "255824" }, { "name": "CMake", "bytes": "2339" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Reinforcement")] [assembly: AssemblyDescription("")] [assembly: AssemblyProduct("Reinforcement")] [assembly: AssemblyCopyright("Copyright © 2016")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Tests")]
{ "content_hash": "5b59236889911e6dd9e88d0042af975b", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 76, "avg_line_length": 38.76470588235294, "alnum_prop": 0.7511380880121397, "repo_name": "Ed-ward/Reinforcement", "id": "a2abfe57de16041fd35a1e68c380b24ed151d092", "size": "662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Reinforcement/Properties/AssemblyInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "209937" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\Qualcomm; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class DefectPixCorEnable extends AbstractTag { protected $Id = 'defect_pix_cor_enable'; protected $Name = 'DefectPixCorEnable'; protected $FullName = 'Qualcomm::Main'; protected $GroupName = 'Qualcomm'; protected $g0 = 'MakerNotes'; protected $g1 = 'Qualcomm'; protected $g2 = 'Camera'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Defect Pix Cor Enable'; protected $flag_Permanent = true; }
{ "content_hash": "70d1b2876ef47313736f8ac40e480367", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 53, "avg_line_length": 17.62162162162162, "alnum_prop": 0.6779141104294478, "repo_name": "romainneutron/PHPExiftool", "id": "99a1a19d5aeebe95a82892ef541aaf2132f1539f", "size": "874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/Qualcomm/DefectPixCorEnable.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22042446" } ], "symlink_target": "" }
package net.wendal.nutzbook.module; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.sql.SQLException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.shiro.authz.annotation.RequiresUser; import org.nutz.dao.Chain; import org.nutz.dao.Cnd; import org.nutz.dao.DaoException; import org.nutz.dao.FieldFilter; import org.nutz.dao.util.Daos; import org.nutz.img.Images; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.lang.Strings; import org.nutz.lang.random.R; import org.nutz.lang.util.NutMap; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mvc.Mvcs; import org.nutz.mvc.adaptor.JsonAdaptor; import org.nutz.mvc.annotation.AdaptBy; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.GET; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.POST; import org.nutz.mvc.annotation.Param; import org.nutz.mvc.impl.AdaptorErrorContext; import org.nutz.mvc.upload.TempFile; import org.nutz.mvc.upload.UploadAdaptor; import org.nutz.plugins.apidoc.annotation.Api; import net.wendal.nutzbook.bean.UserProfile; import net.wendal.nutzbook.util.Toolkit; @Api(name="用户配置文件", description="UserProfile的增删改查") @IocBean @At("/user/profile") public class UserProfileModule extends BaseModule { private static final Log log = Logs.get(); protected byte[] emailKEY = R.sg(24).next().getBytes(); @RequiresUser @At public UserProfile get() { int userId = Toolkit.uid(); UserProfile profile = Daos.ext(dao, FieldFilter.locked(UserProfile.class, "avatar")).fetch(UserProfile.class, userId); if (profile == null) { profile = new UserProfile(); profile.setUserId(userId); profile.setCreateTime(new Date()); profile.setUpdateTime(new Date()); dao.insert(profile); } return profile; } @RequiresUser @At @AdaptBy(type=JsonAdaptor.class) @Ok("void") public void update(@Param("..")UserProfile profile) { int userId = Toolkit.uid(); if (profile == null) return; profile.setUserId(userId);//修正userId,防止恶意修改其他用户的信息 profile.setUpdateTime(new Date()); profile.setAvatar(null); // 不准通过这个方法更新 UserProfile old = get(); // 检查email相关的更新 if (old.getEmail() == null) { // 老的邮箱为null,所以新的肯定是未check的状态 profile.setEmailChecked(false); } else { if (profile.getEmail() == null) { profile.setEmail(old.getEmail()); profile.setEmailChecked(old.isEmailChecked()); } else if (!profile.getEmail().equals(old.getEmail())) { // 设置新邮箱,果断设置为未检查状态 profile.setEmailChecked(false); } else { profile.setEmailChecked(old.isEmailChecked()); } } Daos.ext(dao, FieldFilter.create(UserProfile.class, null, "avatar", true)).update(profile); } @RequiresUser @At("/") @GET @Ok("jsp:jsp.user.profile") public UserProfile index() { return get(); } @RequiresUser @AdaptBy(type=UploadAdaptor.class, args={"${app.root}/WEB-INF/tmp/user_avatar", "8192", "utf-8", "20000", "102400"}) @POST @Ok(">>:/user/profile") @At("/avatar") public void uploadAvatar(@Param("file")TempFile tf, AdaptorErrorContext err) { String msg = null; if (err != null && err.getAdaptorErr() != null) { msg = "文件大小不符合规定"; } else if (tf == null) { msg = "空文件"; } else { UserProfile profile = get(); try (InputStream ins = tf.getInputStream()) { BufferedImage image = Images.read(ins); image = Images.zoomScale(image, 128, 128, Color.WHITE); ByteArrayOutputStream out = new ByteArrayOutputStream(); Images.writeJpeg(image, out, 0.8f); profile.setAvatar(out.toByteArray()); dao.update(profile, "^avatar$"); } catch(DaoException e) { log.info("System Error", e); msg = "系统错误"; } catch (Throwable e) { msg = "图片格式错误"; } } if (msg != null) Mvcs.getHttpSession().setAttribute("upload-error-msg", msg); } @RequiresUser @Ok("raw:jpg") @At("/avatar") @GET public Object readAvatar(HttpServletRequest req) throws SQLException { int userId = Toolkit.uid(); UserProfile profile = Daos.ext(dao, FieldFilter.create(UserProfile.class, "^avatar$")).fetch(UserProfile.class, userId); if (profile == null || profile.getAvatar() == null) { return new File(Mvcs.getServletContext().getRealPath("/rs/user_avatar/none.jpg")); } return profile.getAvatar(); } @RequiresUser @At("/active/mail") @POST public Object activeMail(HttpServletRequest req) { int userId = Toolkit.uid(); NutMap re = new NutMap(); UserProfile profile = get(); if (Strings.isBlank(profile.getEmail())) { return re.setv("ok", false).setv("msg", "你还没有填邮箱啊!"); } String token = String.format("%s,%s,%s", userId, profile.getEmail(), System.currentTimeMillis()); token = Toolkit._3DES_encode(emailKEY, token.getBytes()); String url = req.getRequestURL() + "?token=" + token; String html = "<div>如果无法点击,请拷贝一下链接到浏览器中打开<p/>验证链接 %s</div>"; html = String.format(html, url, url); try { boolean ok = emailService.send(profile.getEmail(), "XXX 验证邮件 by Nutzbook", html); if (!ok) { return re.setv("ok", false).setv("msg", "发送失败"); } } catch (Throwable e) { log.debug("发送邮件失败", e); return re.setv("ok", false).setv("msg", "发送失败"); } return re.setv("ok", true); } // @RequiresGuest @At("/active/mail") @GET @Ok("raw") // 为了简单起见,这里直接显示验证结果就好了 public String activeMailCallback(@Param("token")String token, HttpSession session) { if (Strings.isBlank(token)) { return "请不要直接访问这个链接!!!"; } if (token.length() < 10) { return "非法token"; } try { token = Toolkit._3DES_decode(emailKEY, Toolkit.hexstr2bytearray(token)); if (token == null) return "非法token"; String[] tmp = token.split(",", 3); if (tmp.length != 3 || tmp[0].length() == 0 || tmp[1].length() == 0 || tmp[2].length() == 0) return "非法token"; long time = Long.parseLong(tmp[2]); if (System.currentTimeMillis() - time > 10*60*1000) { return "该验证链接已经超时"; } int userId = Integer.parseInt(tmp[0]); Cnd cnd = Cnd.where("userId", "=", userId).and("email", "=", tmp[1]); int re = dao.update(UserProfile.class, Chain.make("emailChecked", true), cnd); if (re == 1) { return "验证成功"; } return "验证失败!!请重新验证!!"; } catch (Throwable e) { log.debug("检查token时出错", e); return "非法token"; } } }
{ "content_hash": "4ce00b03da1dfc9e5c8ba72f270728ec", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 122, "avg_line_length": 29.80373831775701, "alnum_prop": 0.682815929758545, "repo_name": "sunhai1988/nutz-book-project", "id": "43b4bdc374e991df7842f0f51f37dac3b5d09ca9", "size": "6800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/wendal/nutzbook/module/UserProfileModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "528780" }, { "name": "FreeMarker", "bytes": "137012" }, { "name": "HTML", "bytes": "63369" }, { "name": "Java", "bytes": "490754" }, { "name": "JavaScript", "bytes": "2136956" }, { "name": "Python", "bytes": "1492" } ], "symlink_target": "" }
namespace pxt.py { import B = pxt.blocks; import SK = pxtc.SymbolKind interface Ctx { currModule: py.Module; currClass?: py.ClassDef; currFun?: py.FunctionDef; blockDepth: number; } interface OverrideTextPart { kind: "text"; text: string; } interface OverrideArgPart { kind: "arg"; index: number; isOptional: boolean; prefix?: string; default?: string; } type OverridePart = OverrideArgPart | OverrideTextPart; interface TypeScriptOverride { parts: OverridePart[]; } // global state let externalApis: pxt.Map<SymbolInfo> // slurped from libraries let internalApis: pxt.Map<SymbolInfo> // defined in Python let ctx: Ctx let currIteration = 0 let typeId = 0 // this measures if we gained additional information about type state // we run conversion several times, until we have all information possible let numUnifies = 0 let autoImport = true let currErrorCtx: string | undefined = "???" let verboseTypes = false let lastAST: AST | undefined = undefined let lastFile: string let diagnostics: pxtc.KsDiagnostic[] let compileOptions: pxtc.CompileOptions let syntaxInfo: pxtc.SyntaxInfo | undefined let infoNode: AST | undefined = undefined let infoScope: ScopeDef // TODO: move to utils function isFalsy<T>(t: T | null | undefined): t is null | undefined { return t === null || t === undefined } function isTruthy<T>(t: T | null | undefined): t is T { return t !== null && t !== undefined } function stmtTODO(v: py.Stmt) { pxt.tickEvent("python.todo.statement", { kind: v.kind }) return B.mkStmt(B.mkText("TODO: " + v.kind)) } function exprTODO(v: py.Expr) { pxt.tickEvent("python.todo.expression", { kind: v.kind }) return B.mkText(" {TODO: " + v.kind + "} ") } function docComment(cmt: string) { if (cmt.trim().split(/\n/).length <= 1) cmt = cmt.trim() else cmt = cmt + "\n" return B.mkStmt(B.mkText("/** " + cmt + " */")) } function defName(n: string, tp: Type): Name { return { kind: "Name", id: n, isdef: true, ctx: "Store", tsType: tp } as any } const tpString = mkType({ primType: "string" }) const tpNumber = mkType({ primType: "number" }) const tpBoolean = mkType({ primType: "boolean" }) const tpVoid = mkType({ primType: "void" }) const tpAny = mkType({ primType: "any" }) let tpBuffer: Type | undefined = undefined const builtInTypes: Map<Type> = { "str": tpString, "string": tpString, "number": tpNumber, "bool": tpBoolean, "void": tpVoid, "any": tpAny, } function ts2PyType(syntaxKind: ts.SyntaxKind): Type { switch (syntaxKind) { case ts.SyntaxKind.StringKeyword: return tpString case ts.SyntaxKind.NumberKeyword: return tpNumber case ts.SyntaxKind.BooleanKeyword: return tpBoolean case ts.SyntaxKind.VoidKeyword: return tpVoid case ts.SyntaxKind.AnyKeyword: return tpAny default: { // TODO: this could be null return tpBuffer! } } } function cleanSymbol(s: SymbolInfo): pxtc.SymbolInfo { let r = U.flatClone(s) delete r.pyAST delete r.pyInstanceType delete r.pyRetType delete r.pySymbolType delete r.moduleTypeMarker delete r.declared if (r.parameters) r.parameters = r.parameters.map(p => { p = U.flatClone(p) delete p.pyType return p }) return r } function mapTsType(tp: string): Type { // TODO handle specifc generic types like: SparseArray<number[]> // wrapped in (...) if (tp[0] == "(" && U.endsWith(tp, ")")) { return mapTsType(tp.slice(1, -1)) } // lambda (...) => ... const arrowIdx = tp.indexOf(" => ") if (arrowIdx > 0) { const retTypeStr = tp.slice(arrowIdx + 4) if (retTypeStr.indexOf(")[]") == -1) { const retType = mapTsType(retTypeStr) const argsStr = tp.slice(1, arrowIdx - 1) const argsWords = argsStr ? argsStr.split(/, /) : [] const argTypes = argsWords.map(a => mapTsType(a.replace(/\w+\??: /, ""))) return mkFunType(retType, argTypes) } } // array ...[] if (U.endsWith(tp, "[]")) { return mkArrayType(mapTsType(tp.slice(0, -2))) } if (tp === "_py.Array") { return mkArrayType(tpAny); } // builtin const t = U.lookup(builtInTypes, tp) if (t) return t // handle number litterals like "-20" (b/c TS loves to give specific types to const's) let isNum = !!tp && !isNaN(tp as any as number) // https://stackoverflow.com/questions/175739 if (isNum) return tpNumber // generic if (tp == "T" || tp == "U") // TODO hack! return mkType({ primType: "'" + tp }) // union if (tp.indexOf("|") >= 0) { const parts = tp.split("|") .map(p => p.trim()) return mkType({ primType: "@union", typeArgs: parts.map(mapTsType) }) } // defined by a symbol, // either in external (non-py) APIs (like default/common packages) // or in internal (py) APIs (probably main.py) let sym = lookupApi(tp + "@type") || lookupApi(tp) if (!sym) { error(null, 9501, U.lf("unknown type '{0}' near '{1}'", tp, currErrorCtx || "???")) return mkType({ primType: tp }) } if (sym.kind == SK.EnumMember) return tpNumber // sym.pyInstanceType might not be initialized yet and we don't want to call symbolType() here to avoid infinite recursion if (sym.kind == SK.Class || sym.kind == SK.Interface) return sym.pyInstanceType || mkType({ classType: sym }) if (sym.kind == SK.Enum) return tpNumber error(null, 9502, U.lf("'{0}' is not a type near '{1}'", tp, currErrorCtx || "???")) return mkType({ primType: tp }) } function getOrSetSymbolType(sym: SymbolInfo): Type { if (!sym.pySymbolType) { currErrorCtx = sym.pyQName if (sym.parameters) { if (pxtc.service.isTaggedTemplate(sym)) { sym.parameters = [{ "name": "literal", "description": "", "type": "string", "options": {} }] } for (let p of sym.parameters) { if (!p.pyType) p.pyType = mapTsType(p.type) } } const prevRetType = sym.pyRetType if (isModule(sym)) { sym.pyRetType = mkType({ moduleType: sym }) } else { if (sym.retType) sym.pyRetType = mapTsType(sym.retType) else if (sym.pyRetType) { // nothing to do } else { U.oops("no type for: " + sym.pyQName) sym.pyRetType = mkType({}) } } if (prevRetType) { unify(sym.pyAST, prevRetType, sym.pyRetType) } if (sym.kind == SK.Function || sym.kind == SK.Method) { let paramTypes = sym.parameters.map(p => p.pyType) if (paramTypes.some(isFalsy)) { error(null, 9526, U.lf("function symbol is missing parameter types near '{1}'", currErrorCtx || "???")) return mkType({}) } sym.pySymbolType = mkFunType(sym.pyRetType, paramTypes.filter(isTruthy)) } else sym.pySymbolType = sym.pyRetType if (sym.kind == SK.Class || sym.kind == SK.Interface) { sym.pyInstanceType = mkType({ classType: sym }) } currErrorCtx = undefined } return sym.pySymbolType } function lookupApi(name: string) { return U.lookup(internalApis, name) || U.lookup(externalApis, name) } function lookupGlobalSymbol(name: string): SymbolInfo | undefined { if (!name) return undefined let sym = lookupApi(name) if (sym) getOrSetSymbolType(sym) else if (name.indexOf(".") && !name.endsWith(".__constructor")) { const base = name.substring(0, name.lastIndexOf(".")); const baseSymbol = lookupGlobalSymbol(base); if (baseSymbol?.kind === SK.Class && baseSymbol.extendsTypes?.length) { return lookupGlobalSymbol(baseSymbol.extendsTypes[0] + name.substring(base.length)); } } return sym } function initApis(apisInfo: pxtc.ApisInfo, tsShadowFiles: string[]) { internalApis = {} externalApis = {} let tsShadowFilesSet = U.toDictionary(tsShadowFiles, t => t) for (let sym of U.values(apisInfo.byQName)) { if (tsShadowFilesSet.hasOwnProperty(sym.fileName)) { continue } let sym2 = sym as SymbolInfo if (sym2.extendsTypes) sym2.extendsTypes = sym2.extendsTypes.filter(e => e != sym2.qName) if (!sym2.pyQName || !sym2.qName) { error(null, 9526, U.lf("Symbol '{0}' is missing qName for '{1}'", sym2.name, !sym2.pyQName ? "py" : "ts")) } externalApis[sym2.pyQName!] = sym2 externalApis[sym2.qName!] = sym2 } // TODO this is for testing mostly; we can do this lazily // for (let sym of U.values(externalApis)) { // if (sym) // getOrSetSymbolType(sym) // } tpBuffer = mapTsType("Buffer") } function mkType(o: py.TypeOptions = {}) { let r: Type = U.flatClone(o) as any r.tid = ++typeId return r } function mkArrayType(eltTp: Type) { return mkType({ primType: "@array", typeArgs: [eltTp] }) } function mkFunType(retTp: Type, argTypes: Type[]) { return mkType({ primType: "@fn" + argTypes.length, typeArgs: [retTp].concat(argTypes) }) } function isFunType(t: Type): boolean { return !!U.startsWith(t.primType || "", "@fn") } function isPrimativeType(t: Type): boolean { return !!t.primType && !U.startsWith(t.primType, "@") } function isUnionType(t: Type): boolean { return !!U.startsWith(t.primType || "", "@union") } function instanceType(sym: SymbolInfo): Type { getOrSetSymbolType(sym) if (!sym.pyInstanceType) error(null, 9527, U.lf("Instance type symbol '{0}' is missing pyInstanceType", sym)) return sym.pyInstanceType! } function currentScope(): py.ScopeDef { return ctx.currFun || ctx.currClass || ctx.currModule } function topScope(): py.ScopeDef { let current = currentScope(); while (current && current.parent) { current = current.parent; } return current; } function isTopLevel() { return ctx.currModule.name == "main" && !ctx.currFun && !ctx.currClass } function addImport(a: AST, name: string, scope?: ScopeDef): SymbolInfo { const sym = lookupGlobalSymbol(name) if (!sym) error(a, 9503, U.lf("No module named '{0}'", name)) return sym! } function defvar(name: string, opts: py.VarDescOptions, modifier?: VarModifier, scope?: ScopeDef): ScopeSymbolInfo { if (!scope) scope = currentScope() let varScopeSym = scope.vars[name] let varSym = varScopeSym?.symbol; if (!varSym) { let pref = getFullName(scope) if (pref) { pref += "." } let qualifiedName = pref + name if (scope.kind === "ClassDef") { varSym = addSymbol(SK.Property, qualifiedName) } else if (isLocalScope(scope) && (modifier === VarModifier.Global || modifier === VarModifier.NonLocal)) { varSym = addSymbol(SK.Variable, name) } else if (isLocalScope(scope)) varSym = mkSymbol(SK.Variable, name) else varSym = addSymbol(SK.Variable, qualifiedName) varScopeSym = { symbol: varSym, modifier, }; scope.vars[name] = varScopeSym; } for (let k of Object.keys(opts)) { (varSym as any)[k] = (opts as any)[k] } return varScopeSym } function canonicalize(t: Type): Type { if (t.unifyWith) { t.unifyWith = canonicalize(t.unifyWith) return t.unifyWith } return t } // TODO cache it? function getFullName(n: py.AST): string { let s = n as py.ScopeDef let pref = "" if (s.parent && s.parent.kind !== "FunctionDef" && s.parent.kind !== "AsyncFunctionDef") { pref = getFullName(s.parent) if (!pref) pref = "" else pref += "." } let nn = n as py.FunctionDef if (n.kind == "Module" && nn.name == "main") return "" if (nn.name) return pref + nn.name else return pref + "?" + n.kind } function applyTypeMap(s: string): string { let over = U.lookup(typeMap, s) if (over) return over for (let scopeVar of U.values(ctx.currModule.vars)) { let v = scopeVar.symbol if (!v.isImport) continue if (v.expandsTo == s) { if (!v.pyName) error(null, 9553, lf("missing pyName")); return v.pyName! } if (v.isImport && U.startsWith(s, (v.expandsTo || "") + ".")) { return v.pyName + s.slice(v.expandsTo!.length) } } return s } function t2s(t: Type): string { t = canonicalize(t) const suff = (s: string) => verboseTypes ? s : "" if (t.primType) { if (t.typeArgs && t.primType == "@array") { return t2s(t.typeArgs[0]) + "[]" } if (isFunType(t) && t.typeArgs) return "(" + t.typeArgs.slice(1).map(t => "_: " + t2s(t)).join(", ") + ") => " + t2s(t.typeArgs[0]) if (isUnionType(t) && t.typeArgs) { return t.typeArgs.map(t2s).join(" | ") } return t.primType + suff("/P") } if (t.classType && t.classType.pyQName) return applyTypeMap(t.classType.pyQName) + suff("/C") else if (t.moduleType && t.moduleType.pyQName) return applyTypeMap(t.moduleType.pyQName) + suff("/M") else return "any" } function mkDiag(astNode: py.AST | undefined | null, category: pxtc.DiagnosticCategory, code: number, messageText: string): pxtc.KsDiagnostic { if (!astNode) astNode = lastAST if (!astNode || !ctx || !ctx.currModule) { return { fileName: lastFile, start: 0, length: 0, line: undefined, column: undefined, code, category, messageText, } } else { return { fileName: lastFile, start: astNode.startPos, length: astNode.endPos - astNode.startPos, line: undefined, column: undefined, code, category, messageText, } } } // next free error 9576 function error(astNode: py.AST | null | undefined, code: number, msg: string) { diagnostics.push(mkDiag(astNode, pxtc.DiagnosticCategory.Error, code, msg)) //const pos = position(astNode ? astNode.startPos || 0 : 0, mod.source) //currErrs += U.lf("{0} near {1}{2}", msg, mod.tsFilename.replace(/\.ts/, ".py"), pos) + "\n" } function typeError(a: py.AST | undefined, t0: Type, t1: Type) { error(a, 9500, U.lf("types not compatible: {0} and {1}", t2s(t0), t2s(t1))) } function typeCtor(t: Type): string | SymbolInfo | {} | null { if (t.primType) return t.primType else if (t.classType) return t.classType else if (t.moduleType) { // a class SymbolInfo can be used as both classType and moduleType // but these are different constructors (one is instance, one is class itself) if (!t.moduleType.moduleTypeMarker) t.moduleType.moduleTypeMarker = {} return t.moduleType.moduleTypeMarker } return null } function isFree(t: Type) { return !typeCtor(canonicalize(t)) } function canUnify(t0: Type, t1: Type): boolean { t0 = canonicalize(t0) t1 = canonicalize(t1) if (t0 === t1) return true let c0 = typeCtor(t0) let c1 = typeCtor(t1) if (!c0 || !c1) return true if (c0 !== c1) return false if (t0.typeArgs && t1.typeArgs) { for (let i = 0; i < Math.min(t0.typeArgs.length, t1.typeArgs.length); ++i) if (!canUnify(t0.typeArgs[i], t1.typeArgs[i])) return false } return true } function unifyClass(a: AST, t: Type, cd: SymbolInfo) { t = canonicalize(t) if (t.classType == cd) return if (isFree(t)) { t.classType = cd return } unify(a, t, instanceType(cd)) } function unifyTypeOf(e: Expr, t1: Type): void { unify(e, typeOf(e), t1) } function unify(a: AST | undefined, t0: Type, t1: Type): void { if (t0 === t1) return t0 = canonicalize(t0) t1 = canonicalize(t1) // We don't handle generic types yet, so bail out. Worst case // scenario is that we infer some extra types as "any" if (t0 === t1 || isGenericType(t0) || isGenericType(t1)) return if (t0.primType === "any") { t0.unifyWith = t1 return } const c0 = typeCtor(t0) const c1 = typeCtor(t1) if (c0 && c1) { if (c0 === c1) { t0.unifyWith = t1 // no type-state change here - actual change would be in arguments only if (t0.typeArgs && t1.typeArgs) { for (let i = 0; i < Math.min(t0.typeArgs.length, t1.typeArgs.length); ++i) unify(a, t0.typeArgs[i], t1.typeArgs[i]) } t0.unifyWith = t1 } else { typeError(a, t0, t1) } } else if (c0 && !c1) { unify(a, t1, t0) } else { // the type state actually changes here numUnifies++ t0.unifyWith = t1 // detect late unifications // if (currIteration > 2) error(a, `unify ${t2s(t0)} ${t2s(t1)}`) } } function isAssignable(fromT: Type, toT: Type): boolean { // TODO: handle assignablity beyond interfaces and classes, e.g. "any", generics, arrays, ... const t0 = canonicalize(fromT) const t1 = canonicalize(toT) if (t0 === t1) return true; const c0 = typeCtor(t0) const c1 = typeCtor(t1) if (c0 === c1) return true; if (c0 && c1) { if (isSymbol(c0) && isSymbol(c1)) { // check extends relationship (e.g. for interfaces & classes) if (c0.extendsTypes && c0.extendsTypes.length) { if (c0.extendsTypes.some(e => e === c1.qName)) { return true } } } // check unions if (isUnionType(t1)) { for (let uT of t1.typeArgs || []) { if (isAssignable(t0, uT)) return true } return false } } return false } function narrow(e: Expr, constrainingType: Type): void { const t0 = canonicalize(typeOf(e)) const t1 = canonicalize(constrainingType) if (isAssignable(t0, t1)) { return; } // if we don't know if two types are assignable, we can try to unify them in common cases // TODO: unification is too strict but should always be sound if (isFunType(t0) || isFunType(t1) || isPrimativeType(t0) || isPrimativeType(t1)) { unify(e, t0, t1) } else { // if we're not sure about assinability or unification, we do nothing as future // iterations may unify or make assinability clear. // TODO: Ideally what we should do is track a "constraining type" similiar to how we track .union // per type, and ensure the constraints are met as we unify or narrow types. The difficulty is that // this depends on a more accurate assignability check which will take some work to get right. } } function isSymbol(c: string | SymbolInfo | {} | null): c is SymbolInfo { return !!(c as SymbolInfo)?.name } function isGenericType(t: Type) { return !!(t?.primType?.startsWith("'")); } function mkSymbol(kind: SK, qname: string): SymbolInfo { let m = /(.*)\.(.*)/.exec(qname) let name = m ? m[2] : qname let ns = m ? m[1] : "" return { kind: kind, name: name, pyName: name, qName: qname, pyQName: qname, namespace: ns, attributes: {} as any, pyRetType: mkType() } as any } function addSymbol(kind: SK, qname: string) { let sym = internalApis[qname] if (sym) { sym.kind = kind return sym } sym = mkSymbol(kind, qname) if (!sym.pyQName) error(null, 9527, U.lf("Symbol '{0}' is missing pyQName", qname)) internalApis[sym.pyQName!] = sym return sym } function isLocalScope(scope: ScopeDef) { let s: ScopeDef | undefined = scope while (s) { if (s.kind == "FunctionDef") return true s = s.parent } return false } function addSymbolFor(k: SK, n: py.Symbol, scope?: ScopeDef) { if (!n.symInfo) { let qn = getFullName(n) if (U.endsWith(qn, ".__init__")) qn = qn.slice(0, -9) + ".__constructor" scope = scope || currentScope() if (isLocalScope(scope)) n.symInfo = mkSymbol(k, qn) else n.symInfo = addSymbol(k, qn) const sym = n.symInfo sym.pyAST = n if (!sym.pyName) error(null, 9528, U.lf("Symbol '{0}' is missing pyName", sym.qName || sym.name)) scope.vars[sym.pyName!] = { symbol: sym } } return n.symInfo } // TODO optimize ? function listClassFields(cd: ClassDef) { let qn = cd.symInfo.qName return U.values(internalApis).filter(e => e.namespace == qn && e.kind == SK.Property) } function getClassField(ct: SymbolInfo, n: string, isStatic: boolean, checkOnly = false, skipBases = false): SymbolInfo | null { let qid: string; if (n === "__init__") { qid = ct.pyQName + ".__constructor" } else { if (n.startsWith(ct.pyQName + ".")) { qid = n; } else { qid = ct.pyQName + "." + n; } } let f = lookupGlobalSymbol(qid) if (f) return f if (!skipBases) { for (let b of ct.extendsTypes || []) { let sym = lookupGlobalSymbol(b) if (sym) { if (sym == ct) U.userError("field lookup loop on: " + sym.qName + " / " + n) let classF = getClassField(sym, n, isStatic, true) if (classF) return classF } } } if (!checkOnly && ct.pyAST && ct.pyAST.kind == "ClassDef") { let sym = addSymbol(SK.Property, qid) sym.isInstance = !isStatic; return sym } return null } function getTypesForFieldLookup(recvType: Type): SymbolInfo[] { let t = canonicalize(recvType) return [ t.classType, ...resolvePrimTypes(t.primType), t.moduleType ].filter(isTruthy) } function getTypeField(recv: Expr, n: string, checkOnly = false) { const recvType = typeOf(recv) const constructorTypes = getTypesForFieldLookup(recvType) for (let ct of constructorTypes) { let isModule = !!recvType.moduleType let f = getClassField(ct, n, isModule, checkOnly) if (f) { if (isModule) { if (f.isInstance) error(null, 9505, U.lf("the field '{0}' of '{1}' is not static", n, ct.pyQName)) } else { if (isSuper(recv)) f.isProtected = true else if (isThis(recv)) { if (!ctx.currClass) error(null, 9529, U.lf("no class context found for {0}", f.pyQName)) if (f.namespace != ctx.currClass!.symInfo.qName) { f.isProtected = true } } } return f } } return null } function resolvePrimTypes(primType: string | undefined): SymbolInfo[] { let res: SymbolInfo[] = [] if (primType == "@array") { res = [lookupApi("_py.Array"), lookupApi("Array")] } else if (primType == "string") { // we need to check both the special "_py" namespace and the typescript "String" // class because for example ".length" is only defined in the latter res = [lookupApi("_py.String"), lookupApi("String")] } return res.filter(a => !!a) } function lookupVar(n: string): ScopeSymbolInfo | null { let s: ScopeDef | undefined = currentScope() let v = U.lookup(s.vars, n) if (v) return v while (s) { let v = U.lookup(s.vars, n) if (v) return v // go to parent, excluding class scopes do { s = s.parent } while (s && s.kind == "ClassDef") } //if (autoImport && lookupGlobalSymbol(n)) { // return addImport(currentScope(), n, ctx.currModule) //} return null } function lookupScopeSymbol(n: string | undefined): ScopeSymbolInfo | undefined | null { if (!n) return null const firstDot = n.indexOf(".") if (firstDot > 0) { const scopeVar = lookupVar(n.slice(0, firstDot)) const v = scopeVar?.symbol; // expand name if needed if (v && v.pyQName != v.pyName) n = v.pyQName + n.slice(firstDot) } else { const v = lookupVar(n) if (v) return v } let globalSym = lookupGlobalSymbol(n) if (!globalSym) return undefined return { symbol: globalSym } } function lookupSymbol(n: string | undefined): SymbolInfo | undefined | null { return lookupScopeSymbol(n)?.symbol } function getClassDef(e: py.Expr) { let n = getName(e) let s = lookupSymbol(n) if (s && s.pyAST && s.pyAST.kind == "ClassDef") return s.pyAST as py.ClassDef return null } function typeOf(e: py.Expr): Type { if (e.tsType) { return canonicalize(e.tsType) } else { e.tsType = mkType() return e.tsType } } function isOfType(e: py.Expr, name: string) { let t = typeOf(e) if (t.classType && t.classType.pyQName == name) return true if (t2s(t) == name) return true return false } function resetCtx(m: py.Module) { ctx = { currClass: undefined, currFun: undefined, currModule: m, blockDepth: 0 } lastFile = m.tsFilename.replace(/\.ts$/, ".py") } function isModule(s: SymbolInfo | undefined) { if (!s) return false switch (s.kind) { case SK.Module: case SK.Interface: case SK.Class: case SK.Enum: return true default: return false } } function scope(f: () => B.JsNode) { const prevCtx = U.flatClone(ctx) let r: B.JsNode; try { r = f() } finally { ctx = prevCtx } return r; } function todoExpr(name: string, e: B.JsNode) { if (!e) return B.mkText("") return B.mkGroup([B.mkText("/* TODO: " + name + " "), e, B.mkText(" */")]) } function todoComment(name: string, n: B.JsNode[]) { if (n.length == 0) return B.mkText("") return B.mkGroup([B.mkText("/* TODO: " + name + " "), B.mkGroup(n), B.mkText(" */"), B.mkNewLine()]) } function doKeyword(k: py.Keyword) { let t = expr(k.value) if (k.arg) return B.mkInfix(B.mkText(k.arg), "=", t) else return B.mkGroup([B.mkText("**"), t]) } function compileType(e: Expr): Type { if (!e) return mkType() let tpName = tryGetName(e) if (tpName) { let sym = lookupApi(tpName + "@type") || lookupApi(tpName) if (sym) { getOrSetSymbolType(sym) if (sym.kind == SK.Enum) return tpNumber if (sym.pyInstanceType) return sym.pyInstanceType } else if (builtInTypes[tpName]) return builtInTypes[tpName] error(e, 9506, U.lf("cannot find type '{0}'", tpName)) } else { // translate Python to TS type annotation for arrays // example: List[str] => string[] if (isSubscript(e)/*i.e. [] syntax*/) { let isList = tryGetName(e.value) === "List" if (isList) { if (isIndex(e.slice)) { let listTypeArg = compileType(e.slice.value) let listType = mkArrayType(listTypeArg) return listType } } } } error(e, 9507, U.lf("invalid type syntax")) return mkType({}) } function doArgs(n: FunctionDef, isMethod: boolean) { const args = n.args if (args.kwonlyargs.length) error(n, 9517, U.lf("keyword-only arguments not supported yet")) let nargs = args.args.slice() if (isMethod) { if (nargs[0]?.arg !== "self") n.symInfo.isStatic = true; else { nargs.shift(); } } else { if (nargs.some(a => a.arg == "self")) error(n, 9519, U.lf("non-methods cannot have an argument called 'self'")) } if (!n.symInfo.parameters) { let didx = args.defaults.length - nargs.length n.symInfo.parameters = nargs.map(a => { if (!a.annotation) error(n, 9519, U.lf("Arg '{0}' missing annotation", a.arg)) let tp = compileType(a.annotation!) let defl = "" if (didx >= 0) { defl = B.flattenNode([expr(args.defaults[didx])]).output unify(a, tp, typeOf(args.defaults[didx])) } didx++ return { name: a.arg, description: "", type: "", initializer: defl, default: defl, pyType: tp } }) } let lst = n.symInfo.parameters.map(p => { let scopeV = defvar(p.name, { isParam: true }) let v = scopeV?.symbol if (!p.pyType) error(n, 9530, U.lf("parameter '{0}' missing pyType", p.name)) unify(n, getOrSetSymbolType(v), p.pyType!) let res = [quote(p.name), typeAnnot(p.pyType!, true)] if (p.default) { res.push(B.mkText(" = " + p.default)) } return B.mkGroup(res) }) if (args.vararg) lst.push(B.mkText("TODO *" + args.vararg.arg)) if (args.kwarg) lst.push(B.mkText("TODO **" + args.kwarg.arg)) return B.H.mkParenthesizedExpression(B.mkCommaSep(lst)) } function accessAnnot(f: SymbolInfo) { if (!f.pyName || f.pyName[0] != "_") return B.mkText("") return f.isProtected ? B.mkText("protected ") : B.mkText("private ") } const numOps: Map<number> = { Sub: 1, Div: 1, Pow: 1, LShift: 1, RShift: 1, BitOr: 1, BitXor: 1, BitAnd: 1, FloorDiv: 1, Mult: 1, // this can be also used on strings and arrays, but let's ignore that for now } const arithmeticCompareOps: Map<number> = { Eq: 1, NotEq: 1, Lt: 1, LtE: 1, Gt: 1, GtE: 1 } const opMapping: Map<string> = { Add: "+", Sub: "-", Mult: "*", MatMult: "Math.matrixMult", Div: "/", Mod: "%", Pow: "**", LShift: "<<", RShift: ">>", BitOr: "|", BitXor: "^", BitAnd: "&", FloorDiv: "Math.idiv", And: "&&", Or: "||", Eq: "==", NotEq: "!=", Lt: "<", LtE: "<=", Gt: ">", GtE: ">=", Is: "===", IsNot: "!==", In: "py.In", NotIn: "py.NotIn", } const prefixOps: Map<string> = { Invert: "~", Not: "!", UAdd: "P+", USub: "P-", } const typeMap: pxt.Map<string> = { "adafruit_bus_device.i2c_device.I2CDevice": "pins.I2CDevice" } function stmts(ss: py.Stmt[]) { ctx.blockDepth++; const res = B.mkBlock(ss.map(stmt)); ctx.blockDepth--; return res; } function exprs0(ee: py.Expr[]) { ee = ee.filter(e => !!e) return ee.map(expr) } function setupScope(n: py.ScopeDef) { if (!n.vars) { n.vars = {} n.parent = currentScope() n.blockDepth = ctx.blockDepth; } } function typeAnnot(t: Type, defaultToAny = false) { let s = t2s(t) if (s === "any") { // TODO: // example from minecraft doc snippet: // player.onChat("while",function(num1){while(num1<10){}}) // -> py -> ts -> // player.onChat("while",function(num1:any;/**TODO:type**/){while(num1<10){;}}) // work around using any: // return B.mkText(": any /** TODO: type **/") // but for now we can just omit the type and most of the type it'll be inferable return defaultToAny ? B.mkText(": any") : B.mkText("") } return B.mkText(": " + t2s(t)) } function guardedScope(v: py.AST, f: () => B.JsNode) { try { return scope(f); } catch (e) { console.log(e) return B.mkStmt(todoComment(`conversion failed for ${(v as any).name || v.kind}`, [])); } } function shouldInlineFunction(si: SymbolInfo | undefined) { if (!si || !si.pyAST) return false if (si.pyAST.kind != "FunctionDef") return false const fn = si.pyAST as FunctionDef if (!fn.callers || fn.callers.length != 1) return false if (fn.callers[0].inCalledPosition) return false return true } function emitFunctionDef(n: FunctionDef, inline = false) { return guardedScope(n, () => { const isMethod = !!ctx.currClass && !ctx.currFun const topLev = isTopLevel() const nested = !!ctx.currFun; setupScope(n) const existing = lookupSymbol(getFullName(n)); const sym = addSymbolFor(isMethod ? SK.Method : SK.Function, n) if (!inline) { if (existing && existing.declared === currIteration) { error(n, 9520, lf("Duplicate function declaration")); } sym.declared = currIteration; if (shouldInlineFunction(sym)) { return B.mkText("") } } if (isMethod) sym.isInstance = true ctx.currFun = n let prefix = "" let funname = n.name const remainingDecorators = n.decorator_list.filter(d => { if (tryGetName(d) == "property") { prefix = "get" return false } if (d.kind == "Attribute" && (d as py.Attribute).attr == "setter" && (d as py.Attribute).value.kind == "Name") { funname = ((d as py.Attribute).value as py.Name).id prefix = "set" return false } return true }) let nodes = [ todoComment("decorators", remainingDecorators.map(expr)) ] if (n.body.length >= 1 && n.body[0].kind == "Raise") n.alwaysThrows = true if (isMethod) { if (!ctx.currClass) error(n, 9531, lf("method '{0}' is missing current class context", sym.pyQName)); if (!sym.pyRetType) error(n, 9532, lf("method '{0}' is missing a return type", sym.pyQName)); if (n.name == "__init__") { nodes.push(B.mkText("constructor")) unifyClass(n, sym.pyRetType!, ctx.currClass!.symInfo) } else { if (funname == "__get__" || funname == "__set__") { let scopeValueVar = n.vars["value"] let valueVar = scopeValueVar?.symbol if (funname == "__set__" && valueVar) { let cf = getClassField(ctx.currClass!.symInfo, "__get__", false) if (cf && cf.pyAST && cf.pyAST.kind == "FunctionDef") unify(n, valueVar.pyRetType!, cf.pyRetType!) } funname = funname.replace(/_/g, "") } if (!prefix) { prefix = funname[0] == "_" ? (sym.isProtected ? "protected" : "private") : "public" if (n.symInfo.isStatic) { prefix += " static"; } } nodes.push(B.mkText(prefix + " "), quote(funname)) } } else { U.assert(!prefix) if (n.name[0] == "_" || topLev || inline || nested) nodes.push(B.mkText("function "), quote(funname)) else nodes.push(B.mkText("export function "), quote(funname)) } let retType = n.name == "__init__" ? undefined : (n.returns ? compileType(n.returns) : sym.pyRetType); nodes.push( doArgs(n, isMethod), retType && canonicalize(retType) != tpVoid ? typeAnnot(retType) : B.mkText("")) // make sure type is initialized getOrSetSymbolType(sym) let body = n.body.map(stmt) if (n.name == "__init__") { if (!ctx.currClass) error(n, 9533, lf("__init__ method '{0}' is missing current class context", sym.pyQName)); if (ctx.currClass?.baseClass) { const firstStatement = n.body[0] const superConstructor = ctx.currClass.baseClass.pyQName + ".__constructor" if (((firstStatement as ExprStmt).value as Call)?.func?.symbolInfo?.pyQName !== superConstructor) { error(n, 9575, lf("Sub classes must call 'super().__init__' as the first statement inside an __init__ method")); } } for (let f of listClassFields(ctx.currClass!)) { let p = f.pyAST as Assign if (p && p.value) { body.push( B.mkStmt(B.mkText(`this.${quoteStr(f.pyName!)} = `), expr(p.value)) ) } } } const hoisted: B.JsNode[] = collectHoistedDeclarations(n); nodes.push(B.mkBlock(hoisted.concat(body))) let ret = B.mkGroup(nodes) if (inline) nodes[nodes.length - 1].noFinalNewline = true else ret = B.mkStmt(ret) return ret }) } const stmtMap: Map<(v: py.Stmt) => B.JsNode> = { FunctionDef: (n: py.FunctionDef) => emitFunctionDef(n), ClassDef: (n: py.ClassDef) => guardedScope(n, () => { setupScope(n) const sym = addSymbolFor(SK.Class, n) U.assert(!ctx.currClass) let topLev = isTopLevel() ctx.currClass = n n.isNamespace = n.decorator_list.some(d => d.kind == "Name" && (<Name>d).id == "namespace"); let nodes = n.isNamespace ? [B.mkText("namespace "), quote(n.name)] : [ todoComment("keywords", n.keywords.map(doKeyword)), todoComment("decorators", n.decorator_list.map(expr)), B.mkText(topLev ? "class " : "export class "), quote(n.name) ] if (!n.isNamespace && n.bases.length > 0) { if (tryGetName(n.bases[0]) == "Enum") { n.isEnum = true } else { nodes.push(B.mkText(" extends ")) nodes.push(B.mkCommaSep(n.bases.map(expr))) let b = getClassDef(n.bases[0]) if (b) { n.baseClass = b.symInfo sym.extendsTypes = [b.symInfo.pyQName!] } else { const nm = tryGetName(n.bases[0]); if (nm) { const localSym = lookupSymbol(nm); const globalSym = lookupGlobalSymbol(nm); n.baseClass = localSym || globalSym; if (n.baseClass) sym.extendsTypes = [n.baseClass.pyQName!] } } } } const classDefs = n.body.filter(s => n.isNamespace || s.kind === "FunctionDef"); const staticStmts = n.isNamespace ? [] : n.body.filter(s => classDefs.indexOf(s) === -1 && s.kind !== "Pass"); let body = stmts(classDefs) nodes.push(body) // Python classes allow arbitrary statements in their bodies, sort of like namespaces. // Take all of these statements and put them in a static method that we can call when // the class is defined. let generatedInitFunction = false; if (staticStmts.length) { generatedInitFunction = true; const staticBody = stmts(staticStmts); const initFun = B.mkStmt(B.mkGroup([ B.mkText(`public static __init${n.name}() `), staticBody ])) body.children.unshift(initFun); } if (!n.isNamespace) { const fieldDefs = listClassFields(n) .map(f => { if (!f.pyName || !f.pyRetType) error(n, 9535, lf("field definition missing py name or return type", f.qName)); return f }); const staticFieldSymbols = fieldDefs.filter(f => !f.isInstance); const instanceFields = fieldDefs.filter(f => f.isInstance) .map((f) => B.mkStmt(accessAnnot(f), quote(f.pyName!), typeAnnot(f.pyRetType!))); const staticFields = staticFieldSymbols .map((f) => B.mkGroup([ B.mkStmt(accessAnnot(f), B.mkText("static "), quote(f.pyName!), typeAnnot(f.pyRetType!)), declareLocalStatic(quoteStr(n.name), quoteStr(f.pyName!), t2s(f.pyRetType!)) ])); body.children = staticFields.concat(instanceFields).concat(body.children) } if (generatedInitFunction) { nodes = [ B.mkStmt(B.mkGroup(nodes)), B.mkStmt(B.mkText(`${n.name}.__init${n.name}()`)) ] } return B.mkStmt(B.mkGroup(nodes)) }), Return: (n: py.Return) => { if (n.value) { let f = ctx.currFun if (f) { if (!f.symInfo.pyRetType) error(n, 9536, lf("function '{0}' missing return type", f.symInfo.pyQName)); unifyTypeOf(n.value, f.symInfo.pyRetType!) } return B.mkStmt(B.mkText("return "), expr(n.value)) } else { return B.mkStmt(B.mkText("return")) } }, AugAssign: (n: py.AugAssign) => { let op = opMapping[n.op] if (op.length > 3) return B.mkStmt(B.mkInfix( expr(n.target), "=", B.H.mkCall(op, [expr(n.target), expr(n.value)]) )) else return B.mkStmt( expr(n.target), B.mkText(" " + op + "= "), expr(n.value) ) }, Assign: (n: py.Assign) => { return convertAssign(n) }, AnnAssign: (n: py.AnnAssign) => { return convertAssign(n) }, For: (n: py.For) => { U.assert(n.orelse.length == 0) n.target.forTargetEndPos = n.endPos if (isCallTo(n.iter, "range")) { let r = n.iter as py.Call let def = expr(n.target) let ref = quote(getName(n.target)) unifyTypeOf(n.target, tpNumber) let start = r.args.length == 1 ? B.mkText("0") : expr(r.args[0]) let stop = expr(r.args[r.args.length == 1 ? 0 : 1]) if (r.args.length <= 2) { return B.mkStmt( B.mkText("for ("), B.mkInfix(def, "=", start), B.mkText("; "), B.mkInfix(ref, "<", stop), B.mkText("; "), B.mkPostfix([ref], "++"), B.mkText(")"), stmts(n.body) ); } // If there are three range arguments, the comparator we need to use // will either be > or < depending on the sign of the third argument. let numValue = r.args[2].kind === "Num" ? (r.args[2] as Num).n : undefined; if (numValue == undefined && r.args[2].kind === "UnaryOp") { const uOp = r.args[2] as UnaryOp; if (uOp.operand.kind === "Num") { if (uOp.op === "UAdd") numValue = (uOp.operand as Num).n; else if (uOp.op === "USub") numValue = -(uOp.operand as Num).n } } // If the third argument is not a number, we can't know the sign so we // have to emit a for-of loop instead if (numValue !== undefined) { const comparator = numValue > 0 ? "<" : ">"; return B.mkStmt( B.mkText("for ("), B.mkInfix(def, "=", start), B.mkText("; "), B.mkInfix(ref, comparator, stop), B.mkText("; "), B.mkInfix(ref, "+=", expr(r.args[2])), B.mkText(")"), stmts(n.body) ); } } if (currIteration > 1) { const typeOfTarget = typeOf(n.target); /** * The type the variable to iterate over must be `string | Iterable<typeof Target>`, * but we can't model that with the current state of the python type checker. * If we can identify the type of the value we're iterating over to be a string elsewhere, * try and allow this by unifying with just the target type; * otherwise, it is assumed to be an array. */ unifyTypeOf(n.iter, typeOf(n.iter) == tpString ? typeOfTarget : mkArrayType(typeOfTarget)); } return B.mkStmt( B.mkText("for ("), expr(n.target), B.mkText(" of "), expr(n.iter), B.mkText(")"), stmts(n.body) ); }, While: (n: py.While) => { U.assert(n.orelse.length == 0) return B.mkStmt( B.mkText("while ("), expr(n.test), B.mkText(")"), stmts(n.body)) }, If: (n: py.If) => { let innerIf = (n: py.If) => { let nodes = [ B.mkText("if ("), expr(n.test), B.mkText(")"), stmts(n.body) ] if (n.orelse.length) { nodes[nodes.length - 1].noFinalNewline = true if (n.orelse.length == 1 && n.orelse[0].kind == "If") { // else if nodes.push(B.mkText(" else ")) U.pushRange(nodes, innerIf(n.orelse[0] as py.If)) } else { nodes.push(B.mkText(" else"), stmts(n.orelse)) } } return nodes } return B.mkStmt(B.mkGroup(innerIf(n))) }, With: (n: py.With) => { if (n.items.length == 1 && isOfType(n.items[0].context_expr, "pins.I2CDevice")) { let it = n.items[0] let res: B.JsNode[] = [] let devRef = expr(it.context_expr) if (it.optional_vars) { let id = tryGetName(it.optional_vars) if (id) { let scopeV = defvar(id, { isLocal: true }) let v = scopeV?.symbol id = quoteStr(id) res.push(B.mkStmt(B.mkText("const " + id + " = "), devRef)) if (!v.pyRetType) error(n, 9537, lf("function '{0}' missing return type", v.pyQName)); unifyTypeOf(it.context_expr, v.pyRetType!) devRef = B.mkText(id) } } res.push(B.mkStmt(B.mkInfix(devRef, ".", B.mkText("begin()")))) U.pushRange(res, n.body.map(stmt)) res.push(B.mkStmt(B.mkInfix(devRef, ".", B.mkText("end()")))) return B.mkGroup(res) } let cleanup: B.JsNode[] = [] let stmts = n.items.map((it, idx) => { let varName = "with" + idx if (it.optional_vars) { let id = getName(it.optional_vars) defvar(id, { isLocal: true }) varName = quoteStr(id) } cleanup.push(B.mkStmt(B.mkText(varName + ".end()"))) return B.mkStmt(B.mkText("const " + varName + " = "), B.mkInfix(expr(it.context_expr), ".", B.mkText("begin()"))) }) U.pushRange(stmts, n.body.map(stmt)) U.pushRange(stmts, cleanup) return B.mkBlock(stmts) }, Raise: (n: py.Raise) => { let ex = n.exc || n.cause if (!ex) return B.mkStmt(B.mkText("throw")) let msg: B.JsNode | undefined = undefined if (ex && ex.kind == "Call") { let cex = ex as py.Call if (cex.args.length == 1) { msg = expr(cex.args[0]) } } // didn't find string - just compile and quote; and hope for the best if (!msg) msg = B.mkGroup([B.mkText("`"), expr(ex), B.mkText("`")]) return B.mkStmt(B.H.mkCall("control.fail", [msg])) }, Assert: (n: py.Assert) => { if (!n.msg) error(n, 9537, lf("assert missing message")); return B.mkStmt(B.H.mkCall("control.assert", exprs0([n.test, n.msg!]))) }, Import: (n: py.Import) => { for (let nm of n.names) { if (nm.asname) defvar(nm.asname, { expandsTo: nm.name }) addImport(n, nm.name) } return B.mkText("") }, ImportFrom: (n: py.ImportFrom) => { let res: B.JsNode[] = [] for (let nn of n.names) { if (nn.name == "*") { if (!n.module) error(n, 9538, lf("import missing module name")); defvar(n.module!, { isImportStar: true }) } else { let fullname = n.module + "." + nn.name let sym = lookupGlobalSymbol(fullname) let currname = nn.asname || nn.name if (isModule(sym)) { defvar(currname, { isImport: sym, expandsTo: fullname }) res.push(B.mkStmt(B.mkText(`import ${quoteStr(currname)} = ${fullname}`))) } else { defvar(currname, { expandsTo: fullname }) } } } return B.mkGroup(res) }, ExprStmt: (n: py.ExprStmt) => n.value.kind == "Str" ? docComment((n.value as py.Str).s) : B.mkStmt(expr(n.value)), Pass: (n: py.Pass) => B.mkStmt(B.mkText("")), Break: (n: py.Break) => B.mkStmt(B.mkText("break")), Continue: (n: py.Continue) => B.mkStmt(B.mkText("continue")), Delete: (n: py.Delete) => { error(n, 9550, U.lf("delete statements are unsupported")); return stmtTODO(n) }, Try: (n: py.Try) => { let r = [ B.mkText("try"), stmts(n.body.concat(n.orelse)), ] for (let e of n.handlers) { r.push(B.mkText("catch ("), e.name ? quote(e.name) : B.mkText("_")) // This isn't JS syntax, but PXT doesn't support try at all anyway if (e.type) r.push(B.mkText("/* instanceof "), expr(e.type), B.mkText(" */")) r.push(B.mkText(")"), stmts(e.body)) } if (n.finalbody.length) r.push(B.mkText("finally"), stmts(n.finalbody)) return B.mkStmt(B.mkGroup(r)) }, AsyncFunctionDef: (n: py.AsyncFunctionDef) => { error(n, 9551, U.lf("async function definitions are unsupported")); return stmtTODO(n) }, AsyncFor: (n: py.AsyncFor) => { error(n, 9552, U.lf("async for statements are unsupported")); return stmtTODO(n) }, AsyncWith: (n: py.AsyncWith) => { error(n, 9553, U.lf("async with statements are unsupported")); return stmtTODO(n) }, Global: (n: py.Global) => { const globalScope = topScope(); const current = currentScope(); for (const name of n.names) { const existing = U.lookup(globalScope.vars, name); if (!existing) { error(n, 9521, U.lf("No binding found for global variable")); } const sym = defvar(name, {}, VarModifier.Global); if (sym.firstRefPos! < n.startPos) { error(n, 9522, U.lf("Variable referenced before global declaration")) } } return B.mkStmt(B.mkText("")); }, Nonlocal: (n: py.Nonlocal) => { const globalScope = topScope(); const current = currentScope(); for (const name of n.names) { const declaringScope = findNonlocalDeclaration(name, current); // Python nonlocal variables cannot refer to globals if (!declaringScope || declaringScope === globalScope || declaringScope.vars[name].modifier === VarModifier.Global) { error(n, 9523, U.lf("No binding found for nonlocal variable")); } const sym = defvar(name, {}, VarModifier.NonLocal); if (sym.firstRefPos! < n.startPos) { error(n, 9524, U.lf("Variable referenced before nonlocal declaration")) } } return B.mkStmt(B.mkText("")); } } function convertAssign(n: py.AnnAssign | py.Assign): B.JsNode { let annotation: Expr | null; let annotAsType: Type | null; let value: Expr | null; let target: Expr; // TODO handle more than 1 target if (n.kind === "Assign") { if (n.targets.length != 1) { error(n, 9553, U.lf("multi-target assignment statements are unsupported")); return stmtTODO(n) } target = n.targets[0] value = n.value annotation = null annotAsType = null } else if (n.kind === "AnnAssign") { target = n.target value = n.value || null annotation = n.annotation annotAsType = compileType(annotation); // process annotated type, unify with target unifyTypeOf(target, annotAsType); } else { return n; } let pref = "" let isConstCall = value ? isCallTo(value, "const") : false let nm = tryGetName(target) || "" if (!isTopLevel() && !ctx.currClass && !ctx.currFun && nm[0] != "_") pref = "export " if (nm && ctx.currClass && !ctx.currFun) { // class fields can't be const // hack: value in @namespace should always be const isConstCall = !!(value && ctx.currClass.isNamespace); let fd = getClassField(ctx.currClass.symInfo, nm, true) if (!fd) error(n, 9544, lf("cannot get class field")); // TODO: use or remove this code /* let src = expr(value) let attrTp = typeOf(value) let getter = getTypeField(value, "__get__", true) if (getter) { unify(n, fd.pyRetType, getter.pyRetType) let implNm = "_" + nm let fdBack = getClassField(ctx.currClass.symInfo, implNm) unify(n, fdBack.pyRetType, attrTp) let setter = getTypeField(attrTp, "__set__", true) let res = [ B.mkNewLine(), B.mkStmt(B.mkText("private "), quote(implNm), typeAnnot(attrTp)) ] if (!getter.fundef.alwaysThrows) res.push(B.mkStmt(B.mkText(`get ${quoteStr(nm)}()`), typeAnnot(fd.type), B.mkBlock([ B.mkText(`return this.${quoteStr(implNm)}.get(this.i2c_device)`), B.mkNewLine() ]))) if (!setter.fundef.alwaysThrows) res.push(B.mkStmt(B.mkText(`set ${quoteStr(nm)}(value`), typeAnnot(fd.type), B.mkText(`) `), B.mkBlock([ B.mkText(`this.${quoteStr(implNm)}.set(this.i2c_device, value)`), B.mkNewLine() ]))) fdBack.initializer = value fd.isGetSet = true fdBack.isGetSet = true return B.mkGroup(res) } else */ if (currIteration == 0) { return B.mkText("/* skip for now */") } if (!fd!.pyRetType) error(n, 9539, lf("function '{0}' missing return type", fd!.pyQName)); unifyTypeOf(target, fd!.pyRetType!) fd!.isInstance = false if (ctx.currClass.isNamespace) { pref = `export ${isConstCall ? "const" : "let"} `; } } if (value) unifyTypeOf(target, typeOf(value)) else { error(n, 9555, U.lf("unable to determine value of assignment")); return stmtTODO(n) } if (isConstCall) { // first run would have "let" in it defvar(getName(target), {}) if (!/^static /.test(pref) && !/const/.test(pref)) pref += "const "; return B.mkStmt(B.mkText(pref), B.mkInfix(expr(target), "=", expr(value))) } if (!pref && target.kind == "Tuple") { let tup = target as py.Tuple let targs = [B.mkText("let "), B.mkText("[")] let nonNames = tup.elts.filter(e => e.kind !== "Name") if (nonNames.length) { error(n, 9556, U.lf("non-trivial tuple assignment unsupported")); return stmtTODO(n) } let tupNames = tup.elts .map(e => e as py.Name) .map(convertName) targs.push(B.mkCommaSep(tupNames)) targs.push(B.mkText("]")) let res = B.mkStmt(B.mkInfix(B.mkGroup(targs), "=", expr(value))) return res } if (target.kind === "Name") { const scopeSym = currentScope().vars[nm]; const sym = scopeSym?.symbol // Mark the assignment only if the variable is declared in this scope if (sym && sym.kind === SK.Variable && scopeSym.modifier === undefined) { if (scopeSym.firstAssignPos === undefined || scopeSym.firstAssignPos > target.startPos) { scopeSym.firstAssignPos = target.startPos scopeSym.firstAssignDepth = ctx.blockDepth; } } } let lExp: B.JsNode | undefined = undefined; if (annotation && annotAsType) { // if we have a type annotation, emit it in these cases if the r-value is: // - null / undefined // - empty list if (value.kind === "NameConstant" && (value as NameConstant).value === null || value.kind === "List" && (value as List).elts.length === 0) { const annotStr = t2s(annotAsType); lExp = B.mkInfix(expr(target), ":", B.mkText(annotStr)) } } if (!lExp) lExp = expr(target) return B.mkStmt(B.mkText(pref), B.mkInfix(lExp, "=", expr(value))) function convertName(n: py.Name) { // TODO resuse with Name expr markInfoNode(n, "identifierCompletion") typeOf(n) let v = lookupName(n) return possibleDef(n, /*excludeLet*/true) } } function possibleDef(n: py.Name, excludeLet: boolean = false) { let id = n.id let currScopeVar = lookupScopeSymbol(id) let curr = currScopeVar?.symbol let localScopeVar = currentScope().vars[id]; let local = localScopeVar?.symbol if (n.isdef === undefined) { if (!curr || (curr.kind === SK.Variable && curr !== local)) { if (ctx.currClass && !ctx.currFun) { n.isdef = false // field currScopeVar = defvar(id, {}) } else { n.isdef = true currScopeVar = defvar(id, { isLocal: true }) } curr = currScopeVar.symbol } else { n.isdef = false } n.symbolInfo = curr if (!n.tsType) error(n, 9540, lf("definition missing ts type")); if (!curr.pyRetType) error(n, 9568, lf("missing py return type")); unify(n, n.tsType!, curr.pyRetType!) } if (n.isdef && shouldHoist(currScopeVar!, currentScope())) { n.isdef = false; } markUsage(currScopeVar, n); if (n.isdef && !excludeLet) { return B.mkGroup([B.mkText("let "), quote(id)]) } else if (curr?.namespace && curr?.qName && !(ctx.currClass?.isNamespace && ctx.currClass?.name === curr?.namespace)) { // If this is a static variable in a class, we want the full qname return quote(curr.qName); } else return quote(id) } function quoteStr(id: string) { if (B.isReservedWord(id)) return id + "_" else if (!id) return id else return id //return id.replace(/([a-z0-9])_([a-zA-Z0-9])/g, (f: string, x: string, y: string) => x + y.toUpperCase()) } function tryGetName(e: py.Expr): string | undefined { if (e.kind == "Name") { let s = (e as py.Name).id let scopeV = lookupVar(s) let v = scopeV?.symbol if (v) { if (v.expandsTo) return v.expandsTo else if (ctx.currClass && !ctx.currFun && !scopeV?.modifier && v.qName) return v.qName } return s } if (e.kind == "Attribute") { let pref = tryGetName((e as py.Attribute).value) if (pref) return pref + "." + (e as py.Attribute).attr } if (isSuper(e) && ctx.currClass?.baseClass) { return ctx.currClass.baseClass.qName } return undefined! } function getName(e: py.Expr): string { let name = tryGetName(e) if (!name) error(null, 9542, lf("Cannot get name of unknown expression kind '{0}'", e.kind)); return name! } function quote(id: py.identifier) { if (id == "self") return B.mkText("this") return B.mkText(quoteStr(id)) } function isCallTo(n: py.Expr, fn: string) { if (n.kind != "Call") return false let c = n as py.Call return tryGetName(c.func) === fn } function binop(left: B.JsNode, pyName: string, right: B.JsNode) { let op = opMapping[pyName] U.assert(!!op) if (op.length > 3) return B.H.mkCall(op, [left, right]) else return B.mkInfix(left, op, right) } interface FunOverride extends pxtc.FunOverride { t: Type | undefined; } const funMapExtension: Map<FunOverride> = { "memoryview": { n: "", t: tpBuffer }, "const": { n: "", t: tpNumber }, "micropython.const": { n: "", t: tpNumber } } function getPy2TsFunMap(): Map<FunOverride> { let funMap: Map<FunOverride> = {}; Object.keys(pxtc.ts2PyFunNameMap).forEach(k => { let tsOverride = pxtc.ts2PyFunNameMap[k]; if (tsOverride && tsOverride.n) { let py2TsOverride: FunOverride = { n: k, t: ts2PyType(tsOverride.t), scale: tsOverride.scale } funMap[tsOverride.n] = py2TsOverride; } }) Object.keys(funMapExtension).forEach(k => { funMap[k] = funMapExtension[k] }) return funMap } const py2TsFunMap: Map<FunOverride> = getPy2TsFunMap(); function isSuper(v: py.Expr) { return isCallTo(v, "super") && (v as py.Call).args.length == 0 } function isThis(v: py.Expr) { return v.kind == "Name" && (v as py.Name).id == "self" } function handleFmt(n: py.BinOp) { if (n.op == "Mod" && n.left.kind == "Str" && (n.right.kind == "Tuple" || n.right.kind == "List")) { let fmt = (n.left as py.Str).s let elts = (n.right as py.List).elts elts = elts.slice() let res = [B.mkText("`")] fmt.replace(/([^%]+)|(%[\d\.]*([a-zA-Z%]))/g, (f: string, reg: string, f2: string, flet: string) => { if (reg) res.push(B.mkText(reg.replace(/[`\\$]/g, f => "\\" + f))) else { let ee = elts.shift() let et = ee ? expr(ee) : B.mkText("???") res.push(B.mkText("${"), et, B.mkText("}")) } return "" }) res.push(B.mkText("`")) return B.mkGroup(res) } return null } function forceBackticks(n: B.JsNode) { if (n.type == B.NT.Prefix && n.op[0] == "\"") { return B.mkText(B.backtickLit(JSON.parse(n.op))) } return n } function nodeInInfoRange(n: AST) { return syntaxInfo && n.startPos <= syntaxInfo.position && syntaxInfo.position <= n.endPos } function markInfoNode(n: AST, tp: pxtc.InfoType) { if (currIteration > 100 && syntaxInfo && infoNode == null && (syntaxInfo.type == tp || syntaxInfo.type == "symbol") && nodeInInfoRange(n)) { infoNode = n infoScope = currentScope() } } function addCaller(e: Expr, v: SymbolInfo) { if (v && v.pyAST && v.pyAST.kind == "FunctionDef") { let fn = v.pyAST as FunctionDef if (!fn.callers) fn.callers = [] if (fn.callers.indexOf(e) < 0) fn.callers.push(e) } } const exprMap: Map<(v: py.Expr) => B.JsNode> = { BoolOp: (n: py.BoolOp) => { let r = expr(n.values[0]) for (let i = 1; i < n.values.length; ++i) { r = binop(r, n.op, expr(n.values[i])) } return r }, BinOp: (n: py.BinOp) => { let r = handleFmt(n) if (r) return r const left = expr(n.left); const right = expr(n.right); if (isArrayType(n.left) && isArrayType(n.right)) { if (n.op === "Add") { return B.H.extensionCall("concat", [left, right], false); } } r = binop(left, n.op, right) if (numOps[n.op]) { unifyTypeOf(n.left, tpNumber) unifyTypeOf(n.right, tpNumber) if (!n.tsType) error(n, 9570, lf("binary op missing ts type")); unify(n, n.tsType!, tpNumber) } return r }, UnaryOp: (n: py.UnaryOp) => { let op = prefixOps[n.op] U.assert(!!op) return B.mkInfix(null!, op, expr(n.operand)) }, Lambda: (n: py.Lambda) => { error(n, 9574, U.lf("lambda expressions are not supported yet")) return exprTODO(n) }, IfExp: (n: py.IfExp) => B.mkInfix(B.mkInfix(expr(n.test), "?", expr(n.body)), ":", expr(n.orelse)), Dict: (n: py.Dict) => { ctx.blockDepth++; const elts = n.keys.map((k, i) => { const v = n.values[i] if (k === undefined) return exprTODO(n) return B.mkStmt(B.mkInfix(expr(k), ":", expr(v)), B.mkText(",")) }) const res = B.mkBlock(elts); ctx.blockDepth--; return res }, Set: (n: py.Set) => exprTODO(n), ListComp: (n: py.ListComp) => exprTODO(n), SetComp: (n: py.SetComp) => exprTODO(n), DictComp: (n: py.DictComp) => exprTODO(n), GeneratorExp: (n: py.GeneratorExp) => { if (n.generators.length == 1 && n.generators[0].kind == "Comprehension") { let comp = n.generators[0] as py.Comprehension if (comp.ifs.length == 0) { return scope(() => { let v = getName(comp.target) defvar(v, { isParam: true }) // TODO this leaks the scope... return B.mkInfix(expr(comp.iter), ".", B.H.mkCall("map", [ B.mkGroup([quote(v), B.mkText(" => "), expr(n.elt)]) ])) }) } } return exprTODO(n) }, Await: (n: py.Await) => exprTODO(n), Yield: (n: py.Yield) => exprTODO(n), YieldFrom: (n: py.YieldFrom) => exprTODO(n), Compare: (n: py.Compare) => { if (n.ops.length == 1 && (n.ops[0] == "In" || n.ops[0] == "NotIn")) { if (canonicalize(typeOf(n.comparators[0])) == tpString) unifyTypeOf(n.left, tpString) let idx = B.mkInfix(expr(n.comparators[0]), ".", B.H.mkCall("indexOf", [expr(n.left)])) return B.mkInfix(idx, n.ops[0] == "In" ? ">=" : "<", B.mkText("0")) } let left = expr(n.left); let right = expr(n.comparators[0]); // Special handling for comparisons of literal types, e.g. 0 === 5 const castIfLiteralComparison = (op: string, leftExpr: Expr, rightExpr: Expr) => { if (arithmeticCompareOps[op]) { if (isNumStringOrBool(leftExpr) && isNumStringOrBool(rightExpr) && B.flattenNode([left]) !== B.flattenNode([right])) { left = B.H.mkParenthesizedExpression( B.mkGroup([left, B.mkText(" as any")]) ); right = B.H.mkParenthesizedExpression( B.mkGroup([right, B.mkText(" as any")]) ); } } } castIfLiteralComparison(n.ops[0], n.left, n.comparators[0]); let r = binop(left, n.ops[0], right) for (let i = 1; i < n.ops.length; ++i) { left = expr(n.comparators[i - 1]); right = expr(n.comparators[i]); castIfLiteralComparison(n.ops[i], n.comparators[i - 1], n.comparators[i]); r = binop(r, "And", binop(left, n.ops[i], right)) } return r }, Call: (n: py.Call) => { // TODO(dz): move body out; needs seperate PR that doesn't touch content n.func.inCalledPosition = true let nm = tryGetName(n.func) let namedSymbol = lookupSymbol(nm) let isClass = namedSymbol && namedSymbol.kind == SK.Class let fun = namedSymbol let recvTp: Type | undefined = undefined; let recv: py.Expr | undefined = undefined let methName: string = "" if (isClass) { fun = lookupSymbol(namedSymbol!.pyQName + ".__constructor") if (!fun) { fun = addSymbolFor(SK.Function, createDummyConstructorSymbol(namedSymbol?.pyAST as ClassDef)) } } else { if (n.func.kind == "Attribute") { let attr = n.func as py.Attribute recv = attr.value recvTp = typeOf(recv) if (recvTp.classType || recvTp.primType) { methName = attr.attr fun = getTypeField(recv, methName, true) if (fun) methName = fun.name } } } let orderedArgs: (Expr | null)[] = n.args.slice() if (nm == "super" && orderedArgs.length == 0) { if (ctx.currClass && ctx.currClass.baseClass) { if (!n.tsType) error(n, 9543, lf("call expr missing ts type")); unifyClass(n, n.tsType!, ctx.currClass.baseClass) } return B.mkText("super") } if (isCallTo(n, "int") && orderedArgs.length === 1 && orderedArgs[0]) { // int() compiles to either Math.trunc or parseInt depending on how it's used. Our builtin // function mapping doesn't handle this well so we special case that here. // TODO: consider generalizing this approach. const arg = orderedArgs[0] const argN = expr(arg) const argT = typeOf(arg) if (argT.primType === "string") { return B.mkGroup([ B.mkText(`parseInt`), B.mkText("("), argN, B.mkText(")") ]); } else if (argT.primType === "number") { return B.mkGroup([ B.mkInfix(B.mkText(`Math`), ".", B.mkText(`trunc`)), B.mkText("("), argN, B.mkText(")") ]); } } if (!fun) { let over = U.lookup(py2TsFunMap, nm!) if (over) methName = "" if (methName) { nm = t2s(recvTp!) + "." + methName over = U.lookup(py2TsFunMap, nm) if (!over && typeCtor(canonicalize(recvTp!)) == "@array") { nm = "Array." + methName over = U.lookup(py2TsFunMap, nm) } } methName = "" if (over) { if (over.n[0] == "." && orderedArgs.length) { recv = orderedArgs.shift()! recvTp = typeOf(recv) methName = over.n.slice(1) fun = getTypeField(recv, methName) if (fun && fun.kind == SK.Property) return B.mkInfix(expr(recv), ".", B.mkText(methName)) } else { fun = lookupGlobalSymbol(over.n) } } } if (isCallTo(n, "str")) { // Our standard method of toString in TypeScript is to concatenate with the empty string unify(n, n.tsType!, tpString); return B.mkInfix(B.mkText(`""`), "+", expr(n.args[0])) } const isSuperAttribute = n.func.kind === "Attribute" && isSuper((n.func as Attribute).value); if (!fun && isSuperAttribute) { fun = lookupGlobalSymbol(nm!); } const isSuperConstructor = ctx.currFun?.name === "__init__" && fun?.name === "__constructor" && ctx.currClass?.baseClass?.pyQName === fun?.namespace && isSuperAttribute; if (isSuperConstructor) { fun = lookupSymbol(ctx.currClass?.baseClass?.pyQName + ".__constructor"); } if (!fun) { error(n, 9508, U.lf("can't find called function '{0}'", nm)) } let formals = fun ? fun.parameters : null let allargs: B.JsNode[] = [] if (!formals) { if (fun) error(n, 9509, U.lf("calling non-function")) allargs = orderedArgs.map(expr) } else { if (orderedArgs.length > formals.length) error(n, 9510, U.lf("too many arguments in call to '{0}'", fun!.pyQName)) while (orderedArgs.length < formals.length) orderedArgs.push(null) orderedArgs = orderedArgs.slice(0, formals.length) for (let kw of n.keywords) { let idx = formals.findIndex(f => f.name == kw.arg) if (idx < 0) error(kw, 9511, U.lf("'{0}' doesn't have argument named '{1}'", fun!.pyQName, kw.arg)) else if (orderedArgs[idx] != null) error(kw, 9512, U.lf("argument '{0} already specified in call to '{1}'", kw.arg, fun!.pyQName)) else orderedArgs[idx] = kw.value } // skip optional args or args with initializers for (let i = orderedArgs.length - 1; i >= 0; i--) { if (!!formals[i].initializer && orderedArgs[i] == null) orderedArgs.pop() else break } for (let i = 0; i < orderedArgs.length; ++i) { let arg = orderedArgs[i] if (arg == null && !formals[i].initializer) { error(n, 9513, U.lf("missing argument '{0}' in call to '{1}'", formals[i].name, fun!.pyQName)) allargs.push(B.mkText("null")) } else if (arg) { if (!formals[i].pyType) error(n, 9545, lf("formal arg missing py type")); const expectedType = formals[i].pyType!; if (expectedType.primType !== "any") { narrow(arg, expectedType) } if (arg.kind == "Name" && shouldInlineFunction(arg.symbolInfo)) { allargs.push(emitFunctionDef(arg.symbolInfo!.pyAST as FunctionDef, true)) } else { allargs.push(expr(arg)) } } else { if (!formals[i].initializer) error(n, 9547, lf("formal arg missing initializer")); allargs.push(B.mkText(formals[i].initializer!)) } } } if (!infoNode && syntaxInfo && syntaxInfo.type == "signature" && nodeInInfoRange(n)) { infoNode = n infoScope = currentScope() syntaxInfo.auxResult = 0 // foo, bar for (let i = 0; i < orderedArgs.length; ++i) { syntaxInfo.auxResult = i let arg = orderedArgs[i] if (!arg) { // if we can't parse this next argument, but the cursor is beyond the // previous arguments, assume it's here break } if (arg.startPos <= syntaxInfo.position && syntaxInfo.position <= arg.endPos) { break } } } if (fun) { if (!fun.pyRetType) error(n, 9549, lf("function missing pyRetType")); if (recv && isArrayType(recv) && recvTp) { unifyArrayType(n, fun, recvTp); } else { unifyTypeOf(n, fun.pyRetType!) } n.symbolInfo = fun if (fun.attributes.py2tsOverride) { const override = parseTypeScriptOverride(fun.attributes.py2tsOverride); if (override) { if (methName && !recv) error(n, 9550, lf("missing recv")); let res = buildOverride(override, allargs, methName ? expr(recv!) : undefined); if (!res) error(n, 9555, lf("buildOverride failed unexpectedly")); return res! } } else if (fun.attributes.pyHelper) { return B.mkGroup([ B.mkInfix(B.mkText("_py"), ".", B.mkText(fun.attributes.pyHelper)), B.mkText("("), B.mkCommaSep(recv ? [expr(recv)].concat(allargs) : allargs), B.mkText(")") ]); } } let fn: B.JsNode; if (isSuperConstructor) { fn = B.mkText("super"); } else { fn = methName ? B.mkInfix(expr(recv!), ".", B.mkText(methName)) : expr(n.func) } let nodes = [ fn, B.mkText("("), B.mkCommaSep(allargs), B.mkText(")") ] if (fun && allargs.length == 1 && pxtc.service.isTaggedTemplate(fun)) nodes = [fn, forceBackticks(allargs[0])] if (isClass) { if (!namedSymbol || !namedSymbol.pyQName) error(n, 9551, lf("missing namedSymbol or pyQName")); nodes[0] = B.mkText(applyTypeMap(namedSymbol!.pyQName!)) nodes.unshift(B.mkText("new ")) } return B.mkGroup(nodes) }, Num: (n: py.Num) => { if (!n.tsType) error(n, 9556, lf("tsType missing")); unify(n, n.tsType!, tpNumber) return B.mkText(n.ns) }, Str: (n: py.Str) => { if (!n.tsType) error(n, 9557, lf("tsType missing")); unify(n, n.tsType!, tpString) return B.mkText(B.stringLit(n.s)) }, FormattedValue: (n: py.FormattedValue) => exprTODO(n), JoinedStr: (n: py.JoinedStr) => exprTODO(n), Bytes: (n: py.Bytes) => { return B.mkText(`hex\`${U.toHex(new Uint8Array(n.s))}\``) }, NameConstant: (n: py.NameConstant) => { if (n.value !== null) { if (!n.tsType) error(n, 9558, lf("tsType missing")); unify(n, n.tsType!, tpBoolean) } return B.mkText(JSON.stringify(n.value)) }, Ellipsis: (n: py.Ellipsis) => exprTODO(n), Constant: (n: py.Constant) => exprTODO(n), Attribute: (n: py.Attribute) => { // e.g. in "foo.bar", n.value is ["foo" expression] and n.attr is "bar" let lhs = expr(n.value) // run it first, in case it wants to capture infoNode let lhsType = typeOf(n.value) let fieldSymbol = getTypeField(n.value, n.attr) let fieldName = n.attr markInfoNode(n, "memberCompletion") if (fieldSymbol) { n.symbolInfo = fieldSymbol addCaller(n, fieldSymbol) if (!n.tsType || !fieldSymbol.pyRetType) error(n, 9559, lf("tsType or pyRetType missing")); unify(n, n.tsType!, fieldSymbol.pyRetType!) fieldName = fieldSymbol.name } else if (lhsType.moduleType) { let sym = lookupGlobalSymbol(lhsType.moduleType.pyQName + "." + n.attr) if (sym) { n.symbolInfo = sym addCaller(n, sym) unifyTypeOf(n, getOrSetSymbolType(sym)) fieldName = sym.name } else error(n, 9514, U.lf("module '{0}' has no attribute '{1}'", lhsType.moduleType.pyQName, n.attr)) } else { if (currIteration > 2) { error(n, 9515, U.lf("unknown object type; cannot lookup attribute '{0}'", n.attr)) } } return B.mkInfix(lhs, ".", B.mkText(quoteStr(fieldName))) }, Subscript: (n: py.Subscript) => { if (n.slice.kind == "Index") { const objType = canonicalize(typeOf(n.value)); if (isArrayType(n.value)) { // indexing into an array const eleType = objType.typeArgs![0]; unifyTypeOf(n, eleType) } else if (objType.primType === "string") { // indexing into a string unifyTypeOf(n, objType) } else if (currIteration > 2 && isFree(typeOf(n))) { // indexing into an object unifyTypeOf(n, tpAny) } let idx = (n.slice as py.Index).value if (currIteration > 2 && isFree(typeOf(idx))) { unifyTypeOf(idx, tpNumber) } return B.mkGroup([ expr(n.value), B.mkText("["), expr(idx), B.mkText("]"), ]) } else if (n.slice.kind == "Slice") { const valueType = typeOf(n.value); unifyTypeOf(n, valueType); let s = n.slice as py.Slice if (s.step) { const isString = valueType?.primType === "string"; return B.H.mkCall(isString ? "_py.stringSlice" : "_py.slice", [ expr(n.value), s.lower ? expr(s.lower) : B.mkText("null"), s.upper ? expr(s.upper) : B.mkText("null"), expr(s.step) ]); } return B.mkInfix(expr(n.value), ".", B.H.mkCall("slice", [s.lower ? expr(s.lower) : B.mkText("0"), s.upper ? expr(s.upper) : null].filter(isTruthy))) } else { return exprTODO(n) } }, Starred: (n: py.Starred) => B.mkGroup([B.mkText("... "), expr(n.value)]), Name: (n: py.Name) => { markInfoNode(n, "identifierCompletion") // shortcut, but should work if (n.id == "self" && ctx.currClass) { if (!n.tsType) error(n, 9560, lf("missing tsType")); unifyClass(n, n.tsType!, ctx.currClass.symInfo) return B.mkText("this") } let scopeV = lookupName(n) let v = scopeV?.symbol // handle import if (v && v.isImport) { return quote(v.name) // it's import X = Y.Z.X, use X not Y.Z.X } markUsage(scopeV, n); if (n.ctx.indexOf("Load") >= 0) { if (!v) return quote(getName(n)) if (!v?.qName) { error(n, 9561, lf("missing qName")); return quote("unknown") } // Note: We track types like String as "String@type" but when actually emitting them // we want to elide the the "@type" const nm = v.qName.replace("@type", "") return quote(nm) } else { return possibleDef(n) } }, List: mkArrayExpr, Tuple: mkArrayExpr, } function lookupName(n: py.Name): ScopeSymbolInfo { let scopeV = lookupScopeSymbol(n.id) let v = scopeV?.symbol if (!scopeV) { // check if the symbol has an override py<->ts mapping let over = U.lookup(py2TsFunMap, n.id) if (over) { scopeV = lookupScopeSymbol(over.n) } } if (scopeV && v) { n.symbolInfo = v if (!n.tsType) error(n, 9562, lf("missing tsType")); unify(n, n.tsType!, getOrSetSymbolType(v)) if (v.isImport) return scopeV addCaller(n, v) if (n.forTargetEndPos && scopeV.forVariableEndPos !== n.forTargetEndPos) { if (scopeV.forVariableEndPos) // defined in more than one 'for'; make sure it's hoisted scopeV.lastRefPos = scopeV.forVariableEndPos + 1 else scopeV.forVariableEndPos = n.forTargetEndPos } } else if (currIteration > 0) { error(n, 9516, U.lf("name '{0}' is not defined", n.id)) } return scopeV! } function markUsage(s: ScopeSymbolInfo | null | undefined, location: py.AST) { if (s) { if (s.modifier === VarModifier.Global) { const declaringScope = topScope(); if (declaringScope && declaringScope.vars[s.symbol.name]) { s = declaringScope.vars[s.symbol.name]; } } else if (s.modifier === VarModifier.NonLocal) { const declaringScope = findNonlocalDeclaration(s.symbol.name, currentScope()); if (declaringScope) { s = declaringScope.vars[s.symbol.name]; } } if (s.firstRefPos === undefined || s.firstRefPos > location.startPos) { s.firstRefPos = location.startPos; } if (s.lastRefPos === undefined || s.lastRefPos < location.startPos) { s.lastRefPos = location.startPos; } } } function mkArrayExpr(n: py.List | py.Tuple) { if (!n.tsType) error(n, 9563, lf("missing tsType")); unify(n, n.tsType!, mkArrayType(n.elts[0] ? typeOf(n.elts[0]) : mkType())) return B.mkGroup([ B.mkText("["), B.mkCommaSep(n.elts.map(expr)), B.mkText("]"), ]) } function sourceMapId(e: py.AST): string { return `${e.startPos}:${e.endPos}` } function expr(e: py.Expr): B.JsNode { lastAST = e let f = exprMap[e.kind] if (!f) { U.oops(e.kind + " - unknown expr") } typeOf(e) const r = f(e) r.id = sourceMapId(e) return r } function stmt(e: py.Stmt): B.JsNode { lastAST = e let f = stmtMap[e.kind] if (!f) { U.oops(e.kind + " - unknown stmt") } let cmts: string[] = (e._comments || []).map(c => c.value) let r = f(e) if (cmts.length) { r = B.mkGroup(cmts.map(c => B.mkStmt(B.H.mkComment(c))).concat(r)) } r.id = sourceMapId(e) return r } function isEmpty(b: B.JsNode): boolean { if (!b) return true if (b.type == B.NT.Prefix && b.op == "") return b.children.every(isEmpty) if (b.type == B.NT.NewLine) return true return false } function declareVariable(s: SymbolInfo) { const name = quote(s.name); const type = t2s(getOrSetSymbolType(s)); return B.mkStmt(B.mkGroup([B.mkText("let "), name, B.mkText(": " + type + ";")])); } function findNonlocalDeclaration(name: string, scope: py.ScopeDef | undefined): py.ScopeDef | undefined { if (!scope) return undefined const symbolInfo = scope.vars && scope.vars[name]; if (symbolInfo && symbolInfo.modifier != VarModifier.NonLocal) { return scope; } else { return findNonlocalDeclaration(name, scope.parent); } } function collectHoistedDeclarations(scope: py.ScopeDef) { const hoisted: B.JsNode[] = []; let current: ScopeSymbolInfo; for (const varName of Object.keys(scope.vars)) { current = scope.vars[varName]; if (shouldHoist(current, scope)) { hoisted.push(declareVariable(current?.symbol)); } } return hoisted; } function shouldHoist(sym: ScopeSymbolInfo, scope: py.ScopeDef): boolean { let result = sym.symbol.kind === SK.Variable && !sym.symbol.isParam && sym.modifier === undefined && (sym.lastRefPos! > sym.forVariableEndPos! || sym.firstRefPos! < sym.firstAssignPos! || sym.firstAssignDepth! > scope.blockDepth!) && !(isTopLevelScope(scope) && sym.firstAssignDepth! === 0); return !!result } function isTopLevelScope(scope: py.ScopeDef) { return scope.kind === "Module" && (scope as py.Module).name === "main"; } // TODO look at scopes of let function toTS(mod: py.Module): B.JsNode[] | undefined { U.assert(mod.kind == "Module") if (mod.tsBody) return undefined resetCtx(mod) if (!mod.vars) mod.vars = {} const hoisted = collectHoistedDeclarations(mod); let res = hoisted.concat(mod.body.map(stmt)) if (res.every(isEmpty)) return undefined else if (mod.name == "main") return res return [ B.mkText("namespace " + mod.name + " "), B.mkBlock(res) ] } function iterPy(e: py.AST, f: (v: py.AST) => void) { if (!e) return f(e) U.iterMap(e as any, (k: string, v: any) => { if (!v || k == "parent") return if (v && v.kind) iterPy(v, f) else if (Array.isArray(v)) v.forEach((x: any) => iterPy(x, f)) }) } function resetPass(iter: number) { currIteration = iter diagnostics = [] numUnifies = 0 lastAST = undefined } export interface Py2TsRes { diagnostics: pxtc.KsDiagnostic[], success: boolean, outfiles: { [key: string]: string }, syntaxInfo?: pxtc.SyntaxInfo, globalNames?: pxt.Map<SymbolInfo>, sourceMap: pxtc.SourceInterval[] } export function py2ts(opts: pxtc.CompileOptions): Py2TsRes { let modules: py.Module[] = [] const outfiles: Map<string> = {} diagnostics = [] U.assert(!!opts.sourceFiles, "missing sourceFiles! Cannot convert py to ts") // find .ts files that are copies of / shadowed by the .py files let pyFiles = opts.sourceFiles!.filter(fn => U.endsWith(fn, ".py")) if (pyFiles.length == 0) return { outfiles, diagnostics, success: diagnostics.length === 0, sourceMap: [] } let removeEnd = (file: string, ext: string) => file.substr(0, file.length - ext.length) let pyFilesSet = U.toDictionary(pyFiles, p => removeEnd(p, ".py")) let tsFiles = opts.sourceFiles! .filter(fn => U.endsWith(fn, ".ts")) let tsShadowFiles = tsFiles .filter(fn => removeEnd(fn, ".ts") in pyFilesSet) U.assert(!!opts.apisInfo, "missing apisInfo! Cannot convert py to ts") lastFile = pyFiles[0] // make sure there's some location info for errors from API init initApis(opts.apisInfo!, tsShadowFiles) compileOptions = opts syntaxInfo = undefined if (!opts.generatedFiles) opts.generatedFiles = [] for (const fn of pyFiles) { let sn = fn let modname = fn.replace(/\.py$/, "").replace(/.*\//, "") let src = opts.fileSystem[fn] try { lastFile = fn let tokens = pxt.py.lex(src) //console.log(pxt.py.tokensToString(tokens)) let res = pxt.py.parse(src, sn, tokens) //console.log(pxt.py.dump(stmts)) U.pushRange(diagnostics, res.diagnostics) modules.push({ kind: "Module", body: res.stmts, blockDepth: 0, name: modname, source: src, tsFilename: sn.replace(/\.py$/, ".ts") } as any) } catch (e) { // TODO console.log("Parse error", e) } } const parseDiags = diagnostics for (let i = 0; i < 5; ++i) { resetPass(i) for (let m of modules) { try { toTS(m) // console.log(`after ${currIteration} - ${numUnifies}`) } catch (e) { console.log("Conv pass error", e); } } if (numUnifies == 0) break } resetPass(1000) infoNode = undefined syntaxInfo = opts.syntaxInfo || { position: 0, type: "symbol" } let sourceMap: pxtc.SourceInterval[] = [] for (let m of modules) { try { let nodes = toTS(m) if (!nodes) continue let res = B.flattenNode(nodes) opts.sourceFiles!.push(m.tsFilename) opts.generatedFiles.push(m.tsFilename) opts.fileSystem[m.tsFilename] = res.output outfiles[m.tsFilename] = res.output let rawSrcMap = res.sourceMap function unpackInterval(i: B.BlockSourceInterval): pxtc.SourceInterval | undefined { let splits = i.id.split(":") if (splits.length != 2) return undefined let py = splits.map(i => parseInt(i)) return { py: { startPos: py[0], endPos: py[1] }, ts: { startPos: i.startPos, endPos: i.endPos } } } sourceMap = rawSrcMap .map(unpackInterval) .filter(i => !!i) as pxtc.SourceInterval[] } catch (e) { console.log("Conv error", e); } } diagnostics = parseDiags.concat(diagnostics) const isGlobalSymbol = (si: SymbolInfo) => { switch (si.kind) { case SK.Enum: case SK.EnumMember: case SK.Variable: case SK.Function: case SK.Module: return true case SK.Property: case SK.Method: return !si.isInstance default: return false } } // always return global symbols because we might need to check for // name collisions downstream let globalNames: pxt.Map<SymbolInfo> = {} const apis = U.values(externalApis).concat(U.values(internalApis)) let existing: SymbolInfo[] = [] const addSym = (v: SymbolInfo) => { if (isGlobalSymbol(v) && existing.indexOf(v) < 0) { let s = cleanSymbol(v) globalNames[s.qName || s.name] = s } } for (let s: ScopeDef | undefined = infoScope; !!s; s = s.parent) { if (s && s.vars) U.values(s.vars) .map(v => v.symbol) .forEach(addSym) } apis.forEach(addSym) if (syntaxInfo && infoNode) { infoNode = infoNode as AST syntaxInfo.beginPos = infoNode.startPos syntaxInfo.endPos = infoNode.endPos if (!syntaxInfo.symbols) syntaxInfo.symbols = [] existing = syntaxInfo.symbols.slice() if (syntaxInfo.type == "memberCompletion" && infoNode.kind == "Attribute") { const attr = infoNode as Attribute const tp = typeOf(attr.value) if (tp.moduleType) { for (let v of apis) { if (!v.isInstance && v.namespace == tp.moduleType.qName) { syntaxInfo.symbols.push(v) } } } else if (tp.classType || tp.primType) { const ct = tp.classType || resolvePrimTypes(tp.primType).reduce((p, n) => p || n, null); if (ct) { if (!ct.extendsTypes || !ct.qName) error(null, 9567, lf("missing extendsTypes or qName")); let types = ct.extendsTypes!.concat(ct.qName!) for (let v of apis) { if (v.isInstance && types.indexOf(v.namespace) >= 0) { syntaxInfo.symbols.push(v) } } } } } else if (syntaxInfo.type == "identifierCompletion") { syntaxInfo.symbols = pxt.U.values(globalNames) } else { let sym = (infoNode as Expr).symbolInfo if (sym) syntaxInfo.symbols.push(sym) } syntaxInfo.symbols = syntaxInfo.symbols.map(cleanSymbol) } let outDiag = patchedDiags() return { outfiles: outfiles, success: outDiag.length === 0, diagnostics: outDiag, syntaxInfo, globalNames, sourceMap: sourceMap } function patchedDiags() { for (let d of diagnostics) { patchPosition(d, opts.fileSystem[d.fileName]) } return diagnostics } } /** * Override example syntax: * indexOf() (no arguments) * indexOf($1, $0) (arguments in different order) * indexOf($0?) (optional argument) * indexOf($0=0) (default value; can be numbers, single quoted strings, false, true, null, undefined) */ function parseTypeScriptOverride(src: string): TypeScriptOverride { const regex = new RegExp(/([^\$]*\()?([^\$\(]*)\$(\d)(?:(?:(?:=(\d+|'[a-zA-Z0-9_]*'|false|true|null|undefined))|(\?)|))/, 'y'); const parts: OverridePart[] = []; let match; let lastIndex = 0; do { lastIndex = regex.lastIndex; match = regex.exec(src); if (match) { if (match[1]) { parts.push({ kind: "text", text: match[1] }); } parts.push({ kind: "arg", prefix: match[2], index: parseInt(match[3]), default: match[4], isOptional: !!match[5] }) } } while (match) if (lastIndex != undefined) { parts.push({ kind: "text", text: src.substr(lastIndex) }); } else { parts.push({ kind: "text", text: src }); } return { parts }; } function isArrayType(expr: py.Expr) { const t = canonicalize(typeOf(expr)); return t && t.primType === "@array"; } function isNumStringOrBool(expr: py.Expr) { switch (expr.kind) { case "Num": case "Str": return true; case "NameConstant": return (expr as NameConstant).value !== null; } return false; } function buildOverride(override: TypeScriptOverride, args: B.JsNode[], recv?: B.JsNode) { const result: B.JsNode[] = []; for (const part of override.parts) { if (part.kind === "text") { result.push(B.mkText(part.text)); } else if (args[part.index] || part.default) { if (part.prefix) result.push(B.mkText(part.prefix)) if (args[part.index]) { result.push(args[part.index]); } else { result.push(B.mkText(part.default!)) } } else if (part.isOptional) { // do nothing } else { return undefined; } } if (recv) { return B.mkInfix(recv, ".", B.mkGroup(result)); } return B.mkGroup(result); } function unifyArrayType(e: Expr, fun: SymbolInfo, arrayType: Type) { // Do our best to unify the generic types by special casing everything switch (fun.qName!) { case "Array.pop": case "Array.removeAt": case "Array.shift": case "Array.find": case "Array.get": case "Array._pickRandom": unifyTypeOf(e, arrayType.typeArgs![0]); break; case "Array.concat": case "Array.slice": case "Array.filter": case "Array.fill": unifyTypeOf(e, arrayType); break; case "Array.reduce": if (e.kind === "Call" && (e as Call).args.length > 1) { const accumulatorType = typeOf((e as Call).args[1]); if (accumulatorType) unifyTypeOf(e, accumulatorType) } break; case "Array.map": // TODO: infer type properly from function instead of bailing out here unifyTypeOf(e, mkArrayType(tpAny)); break; default: unifyTypeOf(e, fun.pyRetType!); break; } } function createDummyConstructorSymbol(def: py.ClassDef, sym = def.symInfo): py.Symbol { const existing = lookupApi(sym.pyQName + ".__constructor"); if (!existing && sym.extendsTypes?.length) { const parentSymbol = lookupSymbol(sym.extendsTypes[0]) || lookupGlobalSymbol(sym.extendsTypes[0]); if (parentSymbol) { return createDummyConstructorSymbol(def, parentSymbol); } } const result = { kind: "FunctionDef", name: "__init__", startPos: def.startPos, endPos: def.endPos, parent: def, body: [], args: { kind: "Arguments", startPos: 0, endPos: 0, args: [{ startPos: 0, endPos: 0, kind: "Arg", arg: "self" }], kw_defaults: [], kwonlyargs: [], defaults: [] }, decorator_list: [], vars: {}, symInfo: mkSymbol(SK.Function, def.symInfo.qName + ".__constructor") } as any as py.FunctionDef; result.symInfo.parameters = []; result.symInfo.pyRetType = mkType({ classType: def.symInfo }); if (existing) { result.args.args.push(...existing.parameters.map(p => ({ startPos: 0, endPos: 0, kind: "Arg", arg: p.name, } as Arg))) result.symInfo.parameters.push(...existing.parameters.map(p => { if (p.pyType) return p; const res = { ...p, pyType: mapTsType(p.type) } return res; })) } return result; } function declareLocalStatic(className: string, name: string, type: string) { const isSetVar = `___${name}_is_set`; const localVar = `___${name}`; return B.mkStmt( B.mkStmt(B.mkText(`private ${isSetVar}: boolean`)), B.mkStmt(B.mkText(`private ${localVar}: ${type}`)), B.mkStmt( B.mkText(`get ${name}(): ${type}`), B.mkBlock([ B.mkText(`return this.${isSetVar} ? this.${localVar} : ${className}.${name}`) ]) ), B.mkStmt( B.mkText(`set ${name}(value: ${type})`), B.mkBlock([ B.mkStmt(B.mkText(`this.${isSetVar} = true`)), B.mkStmt(B.mkText(`this.${localVar} = value`)), ]) ) ); } }
{ "content_hash": "8d2655ff6236a11871a80699e5e64b89", "timestamp": "", "source": "github", "line_count": 3262, "max_line_length": 146, "avg_line_length": 35.32096873083997, "alnum_prop": 0.4612166607358289, "repo_name": "Microsoft/pxt", "id": "b43eee39fc8131e18a9eaef17e91e56781dbe9f4", "size": "115217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pxtpy/converter.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "142135" }, { "name": "HTML", "bytes": "134785" }, { "name": "JavaScript", "bytes": "130358" }, { "name": "Makefile", "bytes": "98" }, { "name": "Python", "bytes": "25261" }, { "name": "Shell", "bytes": "3605" }, { "name": "TypeScript", "bytes": "4344063" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" /> <title>Coverage for changes/compat.py: 100%</title> <link rel="icon" sizes="32x32" href="favicon_32.png"> <link rel="stylesheet" href="style.css" type="text/css"> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="jquery.hotkeys.js"></script> <script type="text/javascript" src="jquery.isonscreen.js"></script> <script type="text/javascript" src="coverage_html.js"></script> <script type="text/javascript"> jQuery(document).ready(coverage.pyfile_ready); </script> </head> <body class="pyfile"> <div id="header"> <div class="content"> <h1>Coverage for <b>changes/compat.py</b> : <span class="pc_cov">100%</span> </h1> <img id="keyboard_icon" src="keybd_closed.png" alt="Show keyboard shortcuts" /> <h2 class="stats"> 2 statements &nbsp; <button type="button" class="run shortkey_r button_toggle_run" title="Toggle lines run">2 run</button> <button type="button" class="mis show_mis shortkey_m button_toggle_mis" title="Toggle lines missing">0 missing</button> <button type="button" class="exc show_exc shortkey_x button_toggle_exc" title="Toggle lines excluded">0 excluded</button> </h2> </div> </div> <div class="help_panel"> <img id="panel_icon" src="keybd_open.png" alt="Hide keyboard shortcuts" /> <p class="legend">Hot-keys on this page</p> <div> <p class="keyhelp"> <span class="key">r</span> <span class="key">m</span> <span class="key">x</span> <span class="key">p</span> &nbsp; toggle line displays </p> <p class="keyhelp"> <span class="key">j</span> <span class="key">k</span> &nbsp; next/prev highlighted chunk </p> <p class="keyhelp"> <span class="key">0</span> &nbsp; (zero) top of page </p> <p class="keyhelp"> <span class="key">1</span> &nbsp; (one) first highlighted chunk </p> </div> </div> <div id="source"> <p id="t1" class="run"><span class="n"><a href="#t1">1</a></span><span class="t"><span class="key">import</span> <span class="nam">sys</span>&nbsp;</span><span class="r"></span></p> <p id="t2" class="pln"><span class="n"><a href="#t2">2</a></span><span class="t">&nbsp;</span><span class="r"></span></p> <p id="t3" class="run"><span class="n"><a href="#t3">3</a></span><span class="t"><span class="nam">IS_WINDOWS</span> <span class="op">=</span> <span class="str">'win32'</span> <span class="key">in</span> <span class="nam">str</span><span class="op">(</span><span class="nam">sys</span><span class="op">.</span><span class="nam">platform</span><span class="op">)</span><span class="op">.</span><span class="nam">lower</span><span class="op">(</span><span class="op">)</span>&nbsp;</span><span class="r"></span></p> </div> <div id="footer"> <div class="content"> <p> <a class="nav" href="index.html">&#xab; index</a> &nbsp; &nbsp; <a class="nav" href="https://coverage.readthedocs.io">coverage.py v5.5</a>, created at 2021-06-15 21:55 +0000 </p> </div> </div> </body> </html>
{ "content_hash": "cf8e14457e7a15709ef10631321d5e2a", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 517, "avg_line_length": 49.13235294117647, "alnum_prop": 0.6019155941334929, "repo_name": "michaeljoseph/changes", "id": "3f6b46eebf12380ebcaec71f5a9b458ab721e8bb", "size": "3341", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "coverage_html/changes_compat_py.html", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "823" }, { "name": "Python", "bytes": "82766" } ], "symlink_target": "" }
package mapstore import ( "errors" "fmt" "net" "regexp" "sort" "sync" "github.com/forestgiant/stela" ) // MapStore implements the Store interface creating an in memory map of stela.Services type MapStore struct { services map[string][]*stela.Service // Map of service names that holds a slice of registered services clients []*stela.Client subscribers map[string][]*stela.Client // Store clients that subscribe to a service name muServices sync.RWMutex // Mutex used to lock services map muSubscribers sync.RWMutex // Mutex used to lock subscriber map muClients sync.RWMutex // Mutex used to lock client slice } // byPriority is a sort interface to sort []srvWithKey slices type byPriority []*stela.Service func (s byPriority) Len() int { return len(s) } func (s byPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s byPriority) Less(i, j int) bool { return s[i].Priority < s[j].Priority } func (m *MapStore) init() { if m.services == nil { m.services = make(map[string][]*stela.Service) } if m.subscribers == nil { m.subscribers = make(map[string][]*stela.Client) } } // Register takes a service adding it to the services map and let's all client subscriers know func (m *MapStore) Register(s *stela.Service) error { if !s.Valid() { return fmt.Errorf("%v registered is invalid", s) } m.init() // Error if it has been added before if m.hasService(s) { return fmt.Errorf("%v is already registered", s) } // Rotate before the other services add the new service m.rotateServices(s.Name) // Set all new incoming services Priority to 0 s.Priority = 0 // Generate a unique id for the service if err := s.GenerateID(); err != nil { return err } // Add service to the beginning of the services map since it's new m.muServices.Lock() defer m.muServices.Unlock() m.services[s.Name] = append([]*stela.Service{s}, m.services[s.Name]...) // Prepend new service // Let subscribers know about new service // m.NotifyClients(s, stela.RegisterAction) return nil } // Deregister removes a service from the map and returns the service it deregistered func (m *MapStore) Deregister(s *stela.Service) *stela.Service { // Notify clients that a new service is deregistered (for service name) // m.NotifyClients(s, stela.DeregisterAction) m.muServices.Lock() defer m.muServices.Unlock() // Remove service from services slice services := m.services[s.Name] for i := len(services) - 1; i >= 0; i-- { rs := services[i] if rs.Equal(s) { // Remove from slice services = append(services[:i], services[i+1:]...) // If that was the last service in the slice delete the key if len(services) == 0 { delete(m.services, s.Name) } else { m.services[s.Name] = services } rs.Action = stela.DeregisterAction return rs } } return nil } // NotifyClients let's all locally subscribed clients, on this stela instance, know about service subscription changes func (m *MapStore) NotifyClients(s *stela.Service) { // Let subscribers know about service change for _, c := range m.subscribers[s.Name] { c.Notify(s) } } // Subscribe allows a stela.Client to subscribe to a specific serviceName func (m *MapStore) Subscribe(serviceName string, c *stela.Client) error { if serviceName == "" { return errors.New("Unable to subscribe to empty serviceName") } if c == nil { return errors.New("Client must not be nil") } m.init() // Add client to list of subscribers m.muSubscribers.Lock() defer m.muSubscribers.Unlock() m.subscribers[serviceName] = append(m.subscribers[serviceName], c) return nil } // Unsubscribe quits sending service changes to the stela.Client func (m *MapStore) Unsubscribe(serviceName string, c *stela.Client) error { m.init() // Remove client to list of subscribers m.muSubscribers.Lock() defer m.muSubscribers.Unlock() subscribers := m.subscribers[serviceName] for i := len(subscribers) - 1; i >= 0; i-- { rc := subscribers[i] // Make sure the client is registered if c == rc { // Remove it from the subscriber slice subscribers = append(subscribers[:i], subscribers[i+1:]...) // If that was the last subscriber in the slice delete the key if len(subscribers) == 0 { delete(m.subscribers, serviceName) } else { m.subscribers[serviceName] = subscribers } return nil } } return fmt.Errorf("Client not find in subscriber list: %v", c) } // Discover finds all services registered under a serviceName func (m *MapStore) Discover(serviceName string) ([]*stela.Service, error) { m.muServices.RLock() results := m.services[serviceName] m.muServices.RUnlock() if len(results) == 0 { return nil, fmt.Errorf("No services discovered with the service name: %s", serviceName) } return results, nil } // DiscoverRegex finds all services registered from a regular expression // https://golang.org/pkg/regexp/#MatchString func (m *MapStore) DiscoverRegex(reg string) ([]*stela.Service, error) { results := []*stela.Service{} // Looks like the string may contain a regex so let's match r, err := regexp.Compile(reg) if err != nil { return nil, fmt.Errorf("No services discovered with the regex: %s", reg) } m.muServices.RLock() for k, v := range m.services { if r.MatchString(k) { results = append(results, v...) } } m.muServices.RUnlock() if len(results) == 0 { return nil, fmt.Errorf("No services discovered with the regex: %s", reg) } return results, nil } // DiscoverOne returns only one of the services registered under a serviceName func (m *MapStore) DiscoverOne(serviceName string) (*stela.Service, error) { services, err := m.Discover(serviceName) if err != nil { return nil, err } // Get Service with lowest priority sort.Sort(byPriority(services)) // Store the service with the lowest priority s := services[0] // Rotate services m.rotateServices(serviceName) return s, nil } // DiscoverAll returns all the services registered with the store func (m *MapStore) DiscoverAll() []*stela.Service { var all []*stela.Service m.muServices.RLock() for _, v := range m.services { all = append(all, v...) } m.muServices.RUnlock() return all } // AddClient adds to client slice m.clients and return the client id func (m *MapStore) AddClient(c *stela.Client) error { // Validate client ip address if ip := net.ParseIP(c.Address); ip == nil { return fmt.Errorf("Client has invalid address: %s", c.Address) } // Don't add duplicate clients if m.hasClient(c) { return errors.New("Client is already registered") } m.init() m.muClients.Lock() defer m.muClients.Unlock() m.clients = append(m.clients, c) // client id is the index of the client just added if err := c.GenerateID(); err != nil { return err } return nil } // RemoveClient removes client from the slice m.clients, services it registered and any subscriptions func (m *MapStore) RemoveClient(c *stela.Client) { m.init() m.muClients.Lock() defer m.muClients.Unlock() for i := len(m.clients) - 1; i >= 0; i-- { rc := m.clients[i] if rc == c { m.clients = append(m.clients[:i], m.clients[i+1:]...) } } m.muSubscribers.Lock() defer m.muSubscribers.Unlock() // Remove client from Subscribers for k, v := range m.subscribers { for i := len(v) - 1; i >= 0; i-- { rc := v[i] if rc == c { // Remove from slice v = append(v[:i], v[i+1:]...) } } // If that was the last client subscribed delete the key if len(v) == 0 { delete(m.subscribers, k) } else { m.subscribers[k] = v } } } // ServicesByClient returns all services a client has registered func (m *MapStore) ServicesByClient(c *stela.Client) []*stela.Service { var clientServices []*stela.Service m.muServices.RLock() // Find any service the client registered for _, services := range m.services { for i := len(services) - 1; i >= 0; i-- { s := services[i] if s == nil || s.Client == nil { continue } if s.Client.Equal(c) { clientServices = append(clientServices, s) } } } m.muServices.RUnlock() return clientServices } // RemoveClients convenience method to RemoveClient for each client in provided slice // func (m *MapStore) RemoveClients(clients []*stela.Client) { // for _, c := range clients { // m.RemoveClient(c) // } // } // Client returns a client from m.clients based on id func (m *MapStore) Client(id string) (*stela.Client, error) { m.init() m.muClients.Lock() defer m.muClients.Unlock() for _, c := range m.clients { if c.ID == id { return c, nil } } return nil, fmt.Errorf("Couldn't find a client from id: %s", id) } // // Clients returns a slice of clients from m.clients based on ip address // func (m *MapStore) Clients(address string) ([]*stela.Client, error) { // m.init() // m.muClients.Lock() // defer m.muClients.Unlock() // // Look for clients matching the address // var clients []*stela.Client // for _, c := range m.clients { // if c.Address == address { // clients = append(clients, c) // } // } // if len(clients) == 0 { // return nil, fmt.Errorf("No clients found with the address: %s", address) // } // return clients, nil // } func (m *MapStore) hasService(s *stela.Service) bool { m.init() m.muServices.RLock() defer m.muServices.RUnlock() for _, rs := range m.services[s.Name] { if s.Equal(rs) { return true // service is already a registered } } return false } func (m *MapStore) hasClient(c *stela.Client) bool { m.init() m.muClients.Lock() defer m.muClients.Unlock() for _, rc := range m.clients { if c.Equal(rc) { return true // client is already a registered } } return false } // rotateServices updates service priority func (m *MapStore) rotateServices(serviceName string) error { // Use length of all services to modulate priority mod := int32(len(m.services[serviceName])) // Now update all the Priorities m.muServices.Lock() for i, s := range m.services[serviceName] { // Update SRV priority m.services[serviceName][i].Priority = (s.Priority + 1) % mod } m.muServices.Unlock() return nil }
{ "content_hash": "5eba2201ed7bf7f2a601e3a1dabc3e3d", "timestamp": "", "source": "github", "line_count": 392, "max_line_length": 118, "avg_line_length": 25.854591836734695, "alnum_prop": 0.6750863344844598, "repo_name": "forestgiant/stela", "id": "713ec809100af870180d5d5c18fabdbb2a3f2fae", "size": "10135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "store/mapstore/mapstore.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "97362" } ], "symlink_target": "" }
package com.github.florent37.materialleanback.cell; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import com.github.florent37.materialleanback.MaterialLeanBack; import com.github.florent37.materialleanback.MaterialLeanBackSettings; import com.github.florent37.materialleanback.PlaceHolderViewHolder; import com.github.florent37.materialleanback.R; /** * Created by florentchampigny on 31/08/15. */ public class CellAdapter extends RecyclerView.Adapter { public static final int PLACEHOLDER_START = 3000; public static final int PLACEHOLDER_END = 3001; public static final int PLACEHOLDER_START_SIZE = 1; public static final int PLACEHOLDER_END_SIZE = 1; public static final int CELL = 3002; final protected int row; final protected MaterialLeanBack.Adapter adapter; final protected MaterialLeanBackSettings settings; protected HeightCalculatedCallback heightCalculatedCallback; public CellAdapter(int row, MaterialLeanBack.Adapter adapter, MaterialLeanBackSettings settings, HeightCalculatedCallback heightCalculatedCallback) { this.row = row; this.adapter = adapter; this.settings = settings; this.heightCalculatedCallback = heightCalculatedCallback; } @Override public int getItemViewType(int position) { if (position == 0) return PLACEHOLDER_START; else if (position == getItemCount() - 1) return PLACEHOLDER_END; else return CELL; } public interface HeightCalculatedCallback { void onHeightCalculated(int height); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) { final View view; switch (type) { case PLACEHOLDER_START: view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.mlb_placeholder, viewGroup, false); return new PlaceHolderViewHolder(view, true, settings.paddingLeft); case PLACEHOLDER_END: view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.mlb_placeholder, viewGroup, false); return new PlaceHolderViewHolder(view, true, settings.paddingRight); default: view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.mlb_cell, viewGroup, false); //simulate wrap_content view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (heightCalculatedCallback != null) heightCalculatedCallback.onHeightCalculated(view.getHeight()); view.getViewTreeObserver().removeOnPreDrawListener(this); return false; } }); } return new CellViewHolder(view, this.row, adapter, settings); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { if (viewHolder instanceof CellViewHolder) { CellViewHolder cellViewHolder = (CellViewHolder) viewHolder; if (position == 1) cellViewHolder.setEnlarged(false); else cellViewHolder.setEnlarged(true); cellViewHolder.newPosition(position-PLACEHOLDER_START_SIZE); cellViewHolder.onBind(); } } @Override public int getItemCount() { return this.adapter.getCellsCount(this.row)+PLACEHOLDER_START_SIZE+PLACEHOLDER_END_SIZE; } }
{ "content_hash": "b90cbf774d7e74a216055b3b54c6de90", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 153, "avg_line_length": 38.5, "alnum_prop": 0.6718791412668964, "repo_name": "Dreezydraig/MaterialLeanBack", "id": "fb806aa5a753907d6e7c7b85c49169e59ea234d1", "size": "3773", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "materialleanback/src/main/java/com/github/florent37/materialleanback/cell/CellAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "30591" } ], "symlink_target": "" }
package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multiset; import com.google.javascript.jscomp.CompilerOptions.AliasTransformation; import com.google.javascript.jscomp.CompilerOptions.AliasTransformationHandler; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SourcePosition; import com.google.javascript.rhino.Token; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Process aliases in goog.scope blocks. * * <pre> * goog.scope(function() { * var dom = goog.dom; * var DIV = dom.TagName.DIV; * * dom.createElement(DIV); * }); * </pre> * * should become * * <pre> * goog.dom.createElement(goog.dom.TagName.DIV); * </pre> * * The advantage of using goog.scope is that the compiler will *guarantee* * the anonymous function will be inlined, even if it can't prove * that it's semantically correct to do so. For example, consider this case: * * <pre> * goog.scope(function() { * goog.getBar = function () { return alias; }; * ... * var alias = foo.bar; * }) * </pre> * * <p>In theory, the compiler can't inline 'alias' unless it can prove that * goog.getBar is called only after 'alias' is defined. In practice, the * compiler will inline 'alias' anyway, at the risk of 'fixing' bad code. * * @author robbyw@google.com (Robby Walker) */ class ScopedAliases implements HotSwapCompilerPass { /** Name used to denote an scoped function block used for aliasing. */ static final String SCOPING_METHOD_NAME = "goog.scope"; // The scope depth when inside the body of the function passed to goog.scope. private final int scopeFunctionDepth; private final AbstractCompiler compiler; private final PreprocessorSymbolTable preprocessorSymbolTable; private final AliasTransformationHandler transformationHandler; // Errors static final DiagnosticType GOOG_SCOPE_MUST_BE_ALONE = DiagnosticType.error( "JSC_GOOG_SCOPE_MUST_BE_ALONE", "The call to goog.scope must be alone in a single statement."); static final DiagnosticType GOOG_SCOPE_MUST_BE_IN_GLOBAL_SCOPE = DiagnosticType.error( "JSC_GOOG_SCOPE_MUST_BE_IN_GLOBAL_SCOPE", "The call to goog.scope must be in the global scope."); static final DiagnosticType GOOG_SCOPE_HAS_BAD_PARAMETERS = DiagnosticType.error( "JSC_GOOG_SCOPE_HAS_BAD_PARAMETERS", "The call to goog.scope must take only a single parameter. It must" + " be an anonymous function that itself takes no parameters."); static final DiagnosticType GOOG_SCOPE_REFERENCES_THIS = DiagnosticType.error( "JSC_GOOG_SCOPE_REFERENCES_THIS", "The body of a goog.scope function cannot reference 'this'."); static final DiagnosticType GOOG_SCOPE_USES_RETURN = DiagnosticType.error( "JSC_GOOG_SCOPE_USES_RETURN", "The body of a goog.scope function cannot use 'return'."); static final DiagnosticType GOOG_SCOPE_USES_THROW = DiagnosticType.error( "JSC_GOOG_SCOPE_USES_THROW", "The body of a goog.scope function cannot use 'throw'."); static final DiagnosticType GOOG_SCOPE_ALIAS_REDEFINED = DiagnosticType.error( "JSC_GOOG_SCOPE_ALIAS_REDEFINED", "The alias {0} is assigned a value more than once."); static final DiagnosticType GOOG_SCOPE_ALIAS_CYCLE = DiagnosticType.error( "JSC_GOOG_SCOPE_ALIAS_CYCLE", "The aliases {0} has a cycle."); static final DiagnosticType GOOG_SCOPE_NON_ALIAS_LOCAL = DiagnosticType.error( "JSC_GOOG_SCOPE_NON_ALIAS_LOCAL", "The local variable {0} is in a goog.scope and is not an alias."); private Multiset<String> scopedAliasNames = HashMultiset.create(); ScopedAliases(AbstractCompiler compiler, @Nullable PreprocessorSymbolTable preprocessorSymbolTable, AliasTransformationHandler transformationHandler) { this.compiler = compiler; scopeFunctionDepth = compiler.getLanguageMode().isEs6OrHigher() ? 3 : 2; this.preprocessorSymbolTable = preprocessorSymbolTable; this.transformationHandler = transformationHandler; } @Override public void process(Node externs, Node root) { hotSwapScript(root, null); } @Override public void hotSwapScript(Node root, Node originalRoot) { Traversal traversal = new Traversal(); NodeTraversal.traverse(compiler, root, traversal); if (!traversal.hasErrors()) { // Apply the aliases. List<AliasUsage> aliasWorkQueue = new ArrayList<>(traversal.getAliasUsages()); while (!aliasWorkQueue.isEmpty()) { List<AliasUsage> newQueue = new ArrayList<>(); for (AliasUsage aliasUsage : aliasWorkQueue) { if (aliasUsage.referencesOtherAlias()) { newQueue.add(aliasUsage); } else { aliasUsage.applyAlias(); } } // Prevent an infinite loop. if (newQueue.size() == aliasWorkQueue.size()) { Var cycleVar = newQueue.get(0).aliasVar; compiler.report(JSError.make( cycleVar.getNode(), GOOG_SCOPE_ALIAS_CYCLE, cycleVar.getName())); break; } else { aliasWorkQueue = newQueue; } } // Remove the alias definitions. for (Node aliasDefinition : traversal.getAliasDefinitionsInOrder()) { if (NodeUtil.isNameDeclaration(aliasDefinition.getParent()) && aliasDefinition.getParent().hasOneChild()) { aliasDefinition.getParent().detachFromParent(); } else { aliasDefinition.detachFromParent(); } } // Collapse the scopes. for (Node scopeCall : traversal.getScopeCalls()) { Node expressionWithScopeCall = scopeCall.getParent(); Node scopeClosureBlock = scopeCall.getLastChild().getLastChild(); scopeClosureBlock.detachFromParent(); expressionWithScopeCall.getParent().replaceChild( expressionWithScopeCall, scopeClosureBlock); NodeUtil.tryMergeBlock(scopeClosureBlock); } if (!traversal.getAliasUsages().isEmpty() || !traversal.getAliasDefinitionsInOrder().isEmpty() || !traversal.getScopeCalls().isEmpty()) { compiler.reportCodeChange(); } } } private abstract static class AliasUsage { final Var aliasVar; final Node aliasReference; AliasUsage(Var aliasVar, Node aliasReference) { this.aliasVar = aliasVar; this.aliasReference = aliasReference; } /** Checks to see if this references another alias. */ public boolean referencesOtherAlias() { Node aliasDefinition = aliasVar.getInitialValue(); Node root = NodeUtil.getRootOfQualifiedName(aliasDefinition); Var otherAliasVar = aliasVar.getScope().getOwnSlot(root.getString()); return otherAliasVar != null; } public abstract void applyAlias(); } private static class AliasedNode extends AliasUsage { AliasedNode(Var aliasVar, Node aliasReference) { super(aliasVar, aliasReference); } @Override public void applyAlias() { Node aliasDefinition = aliasVar.getInitialValue(); Node replacement = aliasDefinition.cloneTree(); replacement.useSourceInfoFromForTree(aliasReference); if (aliasReference.getType() == Token.STRING_KEY) { Preconditions.checkState(!aliasReference.hasChildren()); aliasReference.addChildToFront(replacement); } else { aliasReference.getParent().replaceChild(aliasReference, replacement); } } } private static class AliasedTypeNode extends AliasUsage { AliasedTypeNode(Var aliasVar, Node aliasReference) { super(aliasVar, aliasReference); } @Override public void applyAlias() { Node aliasDefinition = aliasVar.getInitialValue(); String aliasName = aliasVar.getName(); String typeName = aliasReference.getString(); if (typeName.startsWith("$jscomp.scope.")) { // Already visited. return; } String aliasExpanded = Preconditions.checkNotNull(aliasDefinition.getQualifiedName()); Preconditions.checkState(typeName.startsWith(aliasName), "%s must start with %s", typeName, aliasName); String replacement = aliasExpanded + typeName.substring(aliasName.length()); aliasReference.setString(replacement); } } private class Traversal extends NodeTraversal.AbstractPostOrderCallback implements NodeTraversal.ScopedCallback { // The job of this class is to collect these three data sets. // The order of this list determines the order that aliases are applied. private final List<Node> aliasDefinitionsInOrder = new ArrayList<>(); private final List<Node> scopeCalls = new ArrayList<>(); private final List<AliasUsage> aliasUsages = new ArrayList<>(); // This map is temporary and cleared for each scope. private final Map<String, Var> aliases = new HashMap<>(); // Also temporary and cleared for each scope. private final Set<Node> injectedDecls = new HashSet<>(); // Suppose you create an alias. // var x = goog.x; // As a side-effect, this means you can shadow the namespace 'goog' // in inner scopes. When we inline the namespaces, we have to rename // these shadows. // // Fortunately, we already have a name uniquifier that runs during tree // normalization (before optimizations). We run it here on a limited // set of variables, but only as a last resort (because this will screw // up warning messages downstream). private final Set<String> forbiddenLocals = new HashSet<>( ImmutableSet.of("$jscomp")); private boolean hasNamespaceShadows = false; private boolean hasErrors = false; private AliasTransformation transformation = null; Collection<Node> getAliasDefinitionsInOrder() { return aliasDefinitionsInOrder; } private List<AliasUsage> getAliasUsages() { return aliasUsages; } List<Node> getScopeCalls() { return scopeCalls; } boolean hasErrors() { return hasErrors; } private boolean isCallToScopeMethod(Node n) { return n.isCall() && n.getFirstChild().matchesQualifiedName(SCOPING_METHOD_NAME); } /** * @param scopeRoot the Node which is the root of the current scope * @return the goog.scope() CALL node containing the scopeRoot, or null if scopeRoot is not * in a goog.scope() call. */ private Node findScopeMethodCall(Node scopeRoot) { // In ES5 and below, the scope is rooted at the FUNCTION node, so if we are inside a // goog.scope call, that call is the parent of the scope root. Node n = scopeRoot.getParent(); if (compiler.getLanguageMode().isEs6OrHigher()) { // But, in ES6, the scope we care about is rooted at the BLOCK node, so the // goog.scope() call is the parent of the parent of the scope root. n = n.getParent(); } if (isCallToScopeMethod(n)) { return n; } return null; } @Override public void enterScope(NodeTraversal t) { if (t.getScope().isGlobal()) { return; } Node scopeMethodCall = findScopeMethodCall(t.getScope().getRootNode()); if (scopeMethodCall != null) { transformation = transformationHandler.logAliasTransformation( scopeMethodCall.getSourceFileName(), getSourceRegion(scopeMethodCall)); findAliases(t); } } @Override public void exitScope(NodeTraversal t) { if (t.getScopeDepth() > scopeFunctionDepth) { findNamespaceShadows(t); } if (t.getScopeDepth() == scopeFunctionDepth) { renameNamespaceShadows(t); injectedDecls.clear(); aliases.clear(); forbiddenLocals.clear(); transformation = null; hasNamespaceShadows = false; } } private SourcePosition<AliasTransformation> getSourceRegion(Node n) { Node testNode = n; Node next = null; for (; next != null || testNode.isScript();) { next = testNode.getNext(); testNode = testNode.getParent(); } int endLine = next == null ? Integer.MAX_VALUE : next.getLineno(); int endChar = next == null ? Integer.MAX_VALUE : next.getCharno(); SourcePosition<AliasTransformation> pos = new SourcePosition<AliasTransformation>() {}; pos.setPositionInformation( n.getLineno(), n.getCharno(), endLine, endChar); return pos; } private void report(NodeTraversal t, Node n, DiagnosticType error, String... arguments) { compiler.report(t.makeError(n, error, arguments)); hasErrors = true; } private void findAliases(NodeTraversal t) { Scope scope = t.getScope(); for (Var v : scope.getVarIterable()) { Node n = v.getNode(); Node parent = n.getParent(); // We use isBlock to avoid variables declared in loop headers. boolean isVar = NodeUtil.isNameDeclaration(parent) && parent.getParent().isBlock(); boolean isFunctionDecl = NodeUtil.isFunctionDeclaration(parent); if (isVar && n.getFirstChild() != null && n.getFirstChild().isQualifiedName()) { recordAlias(v); } else if (v.isBleedingFunction()) { // Bleeding functions already get a BAD_PARAMETERS error, so just // do nothing. } else if (parent.getType() == Token.PARAM_LIST) { // Parameters of the scope function also get a BAD_PARAMETERS // error. } else if (isVar || isFunctionDecl || NodeUtil.isClassDeclaration(parent)) { boolean isHoisted = NodeUtil.isHoistedFunctionDeclaration(parent); Node grandparent = parent.getParent(); Node value = v.getInitialValue(); Node varNode = null; // Grab the docinfo before we do any AST manipulation. JSDocInfo varDocInfo = v.getJSDocInfo(); String name = n.getString(); int nameCount = scopedAliasNames.count(name); scopedAliasNames.add(name); String globalName = "$jscomp.scope." + name + (nameCount == 0 ? "" : ("$" + nameCount)); compiler.ensureLibraryInjected("base", true); // First, we need to free up the function expression (EXPR) // to be used in another expression. if (isFunctionDecl || NodeUtil.isClassDeclaration(parent)) { // Replace "function NAME() { ... }" with "var NAME;". // Replace "class NAME { ... }" with "var NAME;". // We can't keep the local name on the function expression, // because IE is buggy and will leak the name into the global // scope. This is covered in more detail here: // http://wiki.ecmascript.org/lib/exe/fetch.php?id=resources:resources&cache=cache&media=resources:jscriptdeviationsfromes3.pdf // // This will only cause problems if this is a hoisted, recursive // function, and the programmer is using the hoisting. Node newName; if (isFunctionDecl) { newName = IR.name(""); } else { newName = IR.empty(); } newName.useSourceInfoFrom(n); value.replaceChild(n, newName); varNode = IR.var(n).useSourceInfoFrom(n); grandparent.replaceChild(parent, varNode); } else { if (value != null) { // If this is a VAR, we can just detach the expression and // the tree will still be valid. value.detachFromParent(); } varNode = parent; } // Add $jscomp.scope.name = EXPR; // Make sure we copy over all the jsdoc and debug info. if (value != null || varDocInfo != null) { Node newDecl = NodeUtil.newQNameDeclaration( compiler, globalName, value, varDocInfo) .useSourceInfoIfMissingFromForTree(n); NodeUtil.setDebugInformation( newDecl.getFirstChild().getFirstChild(), n, name); if (isHoisted) { grandparent.addChildToFront(newDecl); } else { grandparent.addChildBefore(newDecl, varNode); } injectedDecls.add(newDecl.getFirstChild()); } // Rewrite "var name = EXPR;" to "var name = $jscomp.scope.name;" v.getNameNode().addChildToFront( NodeUtil.newQName( compiler, globalName, n, name)); recordAlias(v); } else { // Do not other kinds of local symbols, like catch params. report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString()); } } } private void recordAlias(Var aliasVar) { String name = aliasVar.getName(); aliases.put(name, aliasVar); String qualifiedName = aliasVar.getInitialValue().getQualifiedName(); transformation.addAlias(name, qualifiedName); int rootIndex = qualifiedName.indexOf('.'); if (rootIndex != -1) { String qNameRoot = qualifiedName.substring(0, rootIndex); if (!aliases.containsKey(qNameRoot)) { forbiddenLocals.add(qNameRoot); } } } /** Find out if there are any local shadows of namespaces. */ private void findNamespaceShadows(NodeTraversal t) { if (hasNamespaceShadows) { return; } Scope scope = t.getScope(); for (Var v : scope.getVarIterable()) { if (forbiddenLocals.contains(v.getName())) { hasNamespaceShadows = true; return; } } } /** * Rename any local shadows of namespaces. * This should be a very rare occurrence, so only do this traversal * if we know that we need it. */ private void renameNamespaceShadows(NodeTraversal t) { if (hasNamespaceShadows) { MakeDeclaredNamesUnique.Renamer renamer = new MakeDeclaredNamesUnique.WhitelistedRenamer( new MakeDeclaredNamesUnique.ContextualRenamer(), forbiddenLocals); for (String s : forbiddenLocals) { renamer.addDeclaredName(s); } MakeDeclaredNamesUnique uniquifier = new MakeDeclaredNamesUnique(renamer); NodeTraversal.traverse(compiler, t.getScopeRoot(), uniquifier); } } private void validateScopeCall(NodeTraversal t, Node n, Node parent) { if (preprocessorSymbolTable != null) { preprocessorSymbolTable.addReference(n.getFirstChild()); } if (!parent.isExprResult()) { report(t, n, GOOG_SCOPE_MUST_BE_ALONE); } if (t.getScope().isLocal()) { report(t, n, GOOG_SCOPE_MUST_BE_IN_GLOBAL_SCOPE); } if (n.getChildCount() != 2) { // The goog.scope call should have exactly 1 parameter. The first // child is the "goog.scope" and the second should be the parameter. report(t, n, GOOG_SCOPE_HAS_BAD_PARAMETERS); } else { Node anonymousFnNode = n.getChildAtIndex(1); if (!anonymousFnNode.isFunction() || NodeUtil.getFunctionName(anonymousFnNode) != null || NodeUtil.getFunctionParameters(anonymousFnNode).hasChildren()) { report(t, anonymousFnNode, GOOG_SCOPE_HAS_BAD_PARAMETERS); } else { scopeCalls.add(n); } } } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (isCallToScopeMethod(n)) { validateScopeCall(t, n, n.getParent()); } if (t.getScopeDepth() < scopeFunctionDepth) { return; } int type = n.getType(); boolean isObjLitShorthand = type == Token.STRING_KEY && !n.hasChildren(); Var aliasVar = null; if (type == Token.NAME || isObjLitShorthand) { String name = n.getString(); Var lexicalVar = t.getScope().getVar(name); if (lexicalVar != null && lexicalVar == aliases.get(name)) { aliasVar = lexicalVar; } } // Validate the top-level of the goog.scope block. if (t.getScopeDepth() == scopeFunctionDepth && findScopeMethodCall(t.getScope().getRootNode()) != null) { if (aliasVar != null && !isObjLitShorthand && NodeUtil.isLValue(n)) { if (aliasVar.getNode() == n) { aliasDefinitionsInOrder.add(n); // Return early, to ensure that we don't record a definition // twice. return; } else { report(t, n, GOOG_SCOPE_ALIAS_REDEFINED, n.getString()); } } if (type == Token.RETURN) { report(t, n, GOOG_SCOPE_USES_RETURN); } else if (type == Token.THIS) { report(t, n, GOOG_SCOPE_REFERENCES_THIS); } else if (type == Token.THROW) { report(t, n, GOOG_SCOPE_USES_THROW); } } // Validate all descendent scopes of the goog.scope block. if (t.getScopeDepth() >= scopeFunctionDepth) { // Check if this name points to an alias. if (aliasVar != null) { // Note, to support the transitive case, it's important we don't // clone aliasedNode here. For example, // var g = goog; var d = g.dom; d.createElement('DIV'); // The node in aliasedNode (which is "g") will be replaced in the // changes pass above with "goog". If we cloned here, we'd end up // with <code>g.dom.createElement('DIV')</code>. aliasUsages.add(new AliasedNode(aliasVar, n)); } // When we inject declarations, we duplicate jsdoc. Make sure // we only process that jsdoc once. JSDocInfo info = n.getJSDocInfo(); if (info != null && !injectedDecls.contains(n)) { for (Node node : info.getTypeNodes()) { fixTypeNode(node); } } } } private void fixTypeNode(Node typeNode) { if (typeNode.isString()) { String name = typeNode.getString(); int endIndex = name.indexOf('.'); if (endIndex == -1) { endIndex = name.length(); } String baseName = name.substring(0, endIndex); Var aliasVar = aliases.get(baseName); if (aliasVar != null) { aliasUsages.add(new AliasedTypeNode(aliasVar, typeNode)); } } for (Node child = typeNode.getFirstChild(); child != null; child = child.getNext()) { fixTypeNode(child); } } } }
{ "content_hash": "809dd2304d1c7629b67d47d08b622ff9", "timestamp": "", "source": "github", "line_count": 646, "max_line_length": 139, "avg_line_length": 35.64705882352941, "alnum_prop": 0.6337067917318048, "repo_name": "vrkansagara/closure-compiler", "id": "fbebf4d47b34ca10efbf16022e2bc4825c913982", "size": "23640", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/com/google/javascript/jscomp/ScopedAliases.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1696" }, { "name": "Java", "bytes": "11309673" }, { "name": "JavaScript", "bytes": "4149360" }, { "name": "Protocol Buffer", "bytes": "7625" } ], "symlink_target": "" }
#import <UIKit/UIView.h> @interface UIView (UITextEffectsWindowAdditions) - (void)_windowDidChangeTransform; @end
{ "content_hash": "d653b4564c29a3c0f27a027515993d5f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 48, "avg_line_length": 14.75, "alnum_prop": 0.7796610169491526, "repo_name": "matthewsot/CocoaSharp", "id": "6643bcbf1d4d9cf362020ebfc56abb0f598d19ec", "size": "258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Headers/Frameworks/UIKit/UIView-UITextEffectsWindowAdditions.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "259784" }, { "name": "C#", "bytes": "2789005" }, { "name": "C++", "bytes": "252504" }, { "name": "Objective-C", "bytes": "24301417" }, { "name": "Smalltalk", "bytes": "167909" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login Page - Photon Admin Panel Theme</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <link rel="shortcut icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/favicon.ico"/> <link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/iosicon.png"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" /> <![endif]--> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" /> <script type="text/javascript" src="js/plugins/excanvas.js"></script> <script type="text/javascript" src="js/plugins/html5shiv.js"></script> <script type="text/javascript" src="js/plugins/respond.min.js"></script> <script type="text/javascript" src="js/plugins/fixFontIcons.js"></script> <![endif]--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/bootstrap/bootstrap.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/modernizr.custom.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.pnotify.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/less-1.3.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/xbreadcrumbs.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/charCount.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.textareaCounter.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/elrte.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/elrte.en.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/select2.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery-picklist.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.validate.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/additional-methods.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.form.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.metadata.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.mockjax.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.uniform.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.tagsinput.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.rating.pack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/farbtastic.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.timeentry.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.dataTables.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.jstree.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/dataTables.bootstrap.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.flot.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.flot.stack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.flot.pie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.flot.resize.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/raphael.2.1.0.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/justgage.1.0.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.qrcode.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.clock.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.countdown.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.jqtweet.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/jquery.cookie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/prettify/prettify.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/bootstrapSwitch.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/plugins/mfupload.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/js/common.js"></script> </head> <body class="body-login"> <div class="nav-fixed-topright" style="visibility: hidden"> <ul class="nav nav-user-menu"> <li class="user-sub-menu-container"> <a href="javascript:;"> <i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i> </a> <ul class="nav user-sub-menu"> <li class="light"> <a href="javascript:;"> <i class='icon-photon stop'></i>Light Version </a> </li> <li class="dark"> <a href="javascript:;"> <i class='icon-photon stop'></i>Dark Version </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-photon mail"></i> </a> </li> <li> <a href="javascript:;"> <i class="icon-photon comment_alt2_stroke"></i> <div class="notification-count">12</div> </a> </li> </ul> </div> <script> $(function(){ setTimeout(function(){ $('.nav-fixed-topright').removeAttr('style'); }, 300); $(window).scroll(function(){ if($('.breadcrumb-container').length){ var scrollState = $(window).scrollTop(); if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released'); else $('.nav-fixed-topright').removeClass('nav-released') } }); $('.user-sub-menu-container').on('click', function(){ $(this).toggleClass('active-user-menu'); }); $('.user-sub-menu .light').on('click', function(){ if ($('body').is('.light-version')) return; $('body').addClass('light-version'); setTimeout(function() { $.cookie('themeColor', 'light', { expires: 7, path: '/' }); }, 500); }); $('.user-sub-menu .dark').on('click', function(){ if ($('body').is('.light-version')) { $('body').removeClass('light-version'); $.cookie('themeColor', 'dark', { expires: 7, path: '/' }); } }); }); </script> <div class="container-login"> <div class="form-centering-wrapper"> <div class="form-window-login"> <div class="form-window-login-logo"> <div class="login-logo"> <img src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/images/photon/login-logo@2x.png" alt="Photon UI"/> </div> <h2 class="login-title">Welcome to Photon UI!</h2> <div class="login-member">Not a Member?&nbsp;<a href="farbtastic.js.html#">Sign Up &#187;</a> <a href="farbtastic.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a> </div> <div class="login-or">Or</div> <div class="login-input-area"> <form method="POST" action="dashboard.php"> <span class="help-block">Login With Your Photon Account</span> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit" class="btn btn-large btn-success btn-login">Login</button> </form> <a href="farbtastic.js.html#" class="forgot-pass">Forgot Your Password?</a> </div> </div> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1936460-27']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
{ "content_hash": "491df5e819391344b6be9692276a6b17", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 232, "avg_line_length": 84.77472527472527, "alnum_prop": 0.742238641519217, "repo_name": "user-tony/photon-rails", "id": "d768d95048c5f05124e483aabf25cd9cf1ac5c21", "size": "15429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/assets/css/css_compiled/@{photonImagePath}plugins/elrte/css/css_compiled/js/bootstrap/js/bootstrap/js/plugins/farbtastic.js.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "291750913" }, { "name": "JavaScript", "bytes": "59305" }, { "name": "Ruby", "bytes": "203" }, { "name": "Shell", "bytes": "99" } ], "symlink_target": "" }
@implementation EKObjectMapping + (EKObjectMapping *)mappingForClass:(Class)objectClass withBlock:(void (^)(EKObjectMapping *))mappingBlock { EKObjectMapping *mapping = [[EKObjectMapping alloc] initWithObjectClass:objectClass]; if (mappingBlock) { mappingBlock(mapping); } return mapping; } + (EKObjectMapping *)mappingForClass:(Class)objectClass withRootPath:(NSString *)rootPath withBlock:(void (^)(EKObjectMapping *))mappingBlock { EKObjectMapping *mapping = [[EKObjectMapping alloc] initWithObjectClass:objectClass withRootPath:rootPath]; if (mappingBlock) { mappingBlock(mapping); } return mapping; } - (id)initWithObjectClass:(Class)objectClass { self = [super init]; if (self) { _objectClass = objectClass; _propertyMappings = [NSMutableDictionary dictionary]; _hasOneMappings = [NSMutableDictionary dictionary]; _hasManyMappings = [NSMutableDictionary dictionary]; } return self; } - (id)initWithObjectClass:(Class)objectClass withRootPath:(NSString *)rootPath { self = [self initWithObjectClass:objectClass]; if (self) { _rootPath = rootPath; } return self; } - (void)mapKeyPath:(NSString *)keyPath toProperty:(NSString *)property { NSParameterAssert(keyPath); NSParameterAssert(property); EKPropertyMapping *mapping = [[EKPropertyMapping alloc] init]; mapping.property = property; mapping.keyPath = keyPath; [self addPropertyMappingToDictionary:mapping]; } - (void)mapKeyPath:(NSString *)keyPath toProperty:(NSString *)property withDateFormat:(NSString *)dateFormat { [self mapKeyPath:keyPath toProperty:property withDateFormatter:[NSDateFormatter ek_formatterForCurrentThread]]; } -(void)mapKeyPath:(NSString *)keyPath toProperty:(NSString *)property withDateFormatter:(NSDateFormatter *)formatter { NSParameterAssert(keyPath); NSParameterAssert(property); NSParameterAssert(formatter); [self mapKeyPath:keyPath toProperty:property withValueBlock:^id(NSString * key, id value) { if (value == nil) return nil; return [value isKindOfClass:[NSString class]] ? [formatter dateFromString:value] : [NSNull null]; } reverseBlock:^id(id value) { if (value == nil) return nil; return [value isKindOfClass:[NSDate class]] ? [formatter stringFromDate:value] : [NSNull null]; }]; } - (void)mapPropertiesFromArray:(NSArray *)propertyNamesArray { NSParameterAssert([propertyNamesArray isKindOfClass:[NSArray class]]); for (NSString *key in propertyNamesArray) { [self mapKeyPath:key toProperty:key]; } } -(void)mapPropertiesFromArrayToPascalCase:(NSArray *)propertyNamesArray { NSParameterAssert([propertyNamesArray isKindOfClass:[NSArray class]]); for (NSString *key in propertyNamesArray) { NSString *pascalKey = [key stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[key substringToIndex:1] uppercaseString]]; [self mapKeyPath:pascalKey toProperty:key]; } } - (void)mapPropertiesFromDictionary:(NSDictionary *)propertyDictionary { NSParameterAssert([propertyDictionary isKindOfClass:[NSDictionary class]]); [propertyDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [self mapKeyPath:key toProperty:obj]; }]; } -(void)mapPropertiesFromMappingObject:(EKObjectMapping *)mappingObj { NSParameterAssert([mappingObj isKindOfClass:EKObjectMapping.class]); for (NSString *key in mappingObj.propertyMappings) { [self addPropertyMappingToDictionary:mappingObj.propertyMappings[key]]; } for (NSString *key in mappingObj.hasOneMappings) { EKRelationshipMapping *mapping = mappingObj.hasOneMappings[key]; [self.hasOneMappings setObject:mapping forKey:mapping.keyPath]; } for (NSString *key in mappingObj.hasManyMappings) { EKRelationshipMapping *mapping = mappingObj.hasManyMappings[key]; [self.hasManyMappings setObject:mapping forKey:mapping.keyPath]; } } - (void)mapKeyPath:(NSString *)keyPath toProperty:(NSString *)property withValueBlock:(id (^)(NSString *, id))valueBlock { NSParameterAssert(keyPath); NSParameterAssert(property); NSParameterAssert(valueBlock); EKPropertyMapping *mapping = [[EKPropertyMapping alloc] init]; mapping.property = property; mapping.keyPath = keyPath; mapping.valueBlock = valueBlock; [self addPropertyMappingToDictionary:mapping]; } - (void)mapKeyPath:(NSString *)keyPath toProperty:(NSString *)property withObjectValueBlock:(EKMappingObjectValueBlock)objectValueBlock { NSParameterAssert(keyPath); NSParameterAssert(property); NSParameterAssert(objectValueBlock); EKPropertyMapping *mapping = [[EKPropertyMapping alloc] init]; mapping.property = property; mapping.keyPath = keyPath; mapping.objectValueBlock = objectValueBlock; [self addPropertyMappingToDictionary:mapping]; } - (void)mapKeyPath:(NSString *)keyPath toProperty:(NSString *)property withValueBlock:(id (^)(NSString *, id))valueBlock reverseBlock:(id (^)(id))reverseBlock { NSParameterAssert(keyPath); NSParameterAssert(property); NSParameterAssert(valueBlock); NSParameterAssert(reverseBlock); EKPropertyMapping *mapping = [[EKPropertyMapping alloc] init]; mapping.property = property; mapping.keyPath = keyPath; mapping.valueBlock = valueBlock; mapping.reverseBlock = reverseBlock; [self addPropertyMappingToDictionary:mapping]; } -(void)hasOne:(Class)objectClass forKeyPath:(NSString *)keyPath { [self hasOne:objectClass forKeyPath:keyPath forProperty:keyPath withObjectMapping:nil]; } -(void)hasOne:(Class)objectClass forKeyPath:(NSString *)keyPath forProperty:(NSString *)property { [self hasOne:objectClass forKeyPath:keyPath forProperty:property withObjectMapping:nil]; } -(void)hasOne:(Class)objectClass forKeyPath:(NSString *)keyPath forProperty:(NSString *)property withObjectMapping:(EKObjectMapping*)objectMapping { if (!objectMapping) { NSParameterAssert([objectClass conformsToProtocol:@protocol(EKMappingProtocol)] || [objectClass conformsToProtocol:@protocol(EKManagedMappingProtocol)]); } NSParameterAssert(keyPath); NSParameterAssert(property); EKRelationshipMapping * relationship = [EKRelationshipMapping new]; relationship.objectClass = objectClass; relationship.keyPath = keyPath; relationship.property = property; relationship.objectMapping = objectMapping; [self.hasOneMappings setObject:relationship forKey:keyPath]; } -(void)hasOne:(Class)objectClass forDictionaryFromKeyPaths:(NSArray *)keyPaths forProperty:(NSString *)property withObjectMapping:(EKObjectMapping *)mapping { if (!mapping) { NSParameterAssert([objectClass conformsToProtocol:@protocol(EKMappingProtocol)] || [objectClass conformsToProtocol:@protocol(EKManagedMappingProtocol)]); } NSParameterAssert(keyPaths); NSParameterAssert(property); EKRelationshipMapping * relationship = [EKRelationshipMapping new]; relationship.objectClass = objectClass; relationship.nonNestedKeyPaths = keyPaths; relationship.property = property; relationship.objectMapping = mapping; self.hasOneMappings[keyPaths.firstObject] = relationship; } -(void)hasMany:(Class)objectClass forKeyPath:(NSString *)keyPath { [self hasMany:objectClass forKeyPath:keyPath forProperty:keyPath withObjectMapping:nil]; } -(void)hasMany:(Class)objectClass forKeyPath:(NSString *)keyPath forProperty:(NSString *)property { [self hasMany:objectClass forKeyPath:keyPath forProperty:property withObjectMapping:nil]; } -(void)hasMany:(Class)objectClass forKeyPath:(NSString *)keyPath forProperty:(NSString *)property withObjectMapping:(EKObjectMapping*)objectMapping { if (!objectMapping) { NSParameterAssert([objectClass conformsToProtocol:@protocol(EKMappingProtocol)] || [objectClass conformsToProtocol:@protocol(EKManagedMappingProtocol)]); } NSParameterAssert(keyPath); NSParameterAssert(property); EKRelationshipMapping * relationship = [EKRelationshipMapping new]; relationship.objectClass = objectClass; relationship.keyPath = keyPath; relationship.property = property; relationship.objectMapping = objectMapping; [self.hasManyMappings setObject:relationship forKey:keyPath]; } - (void)addPropertyMappingToDictionary:(EKPropertyMapping *)propertyMapping { [self.propertyMappings setObject:propertyMapping forKey:propertyMapping.keyPath]; } @end
{ "content_hash": "cf1efb62fcfabe8ec701c46d94fd97fd", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 156, "avg_line_length": 35.45564516129032, "alnum_prop": 0.732628226998749, "repo_name": "maximgolunov/EasyMapping", "id": "4a45447fd61dd3fb006abb9a6cce29d5d48ffc41", "size": "10107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EasyMapping/EKObjectMapping.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "314686" }, { "name": "Ruby", "bytes": "2393" }, { "name": "Swift", "bytes": "4403" } ], "symlink_target": "" }
import _ from "lodash"; import shortid from "shortid"; import Promise from "bluebird"; export default class PortMessaging { constructor() { this.connected = false; this.messageQueue = []; this.unsentMessages = []; this.pendingMessages = {}; this.onRequest = _.noop; this.onBroadcast = _.noop; this.middlewares = { receive: [], send: [] }; this.listeners = { onMessage: ::this.onMessage, onDisconnect: ::this.onDisconnect }; } isConnected() { return this.connected && this.port; } setup(port, setupListeners) { this.port = port; this.connected = true; setupListeners(port, this.listeners); this.resendMessages(); } changePort(newPort, setupListeners, doDisconnect, removeListeners) { doDisconnect(this.port); (removeListeners || _.noop)(this.port, this.listeners); this.setup(newPort, setupListeners); } middleware(type, middleware) { if (_.isArray(middleware)) { _.each(middleware, ::this.middleware); return; } this.middlewares[type].push(middleware); } runMiddlewares(type, message) { return new Promise((resolve, reject) => { // go through the middlewares const next = (nextMessage, index) => { if (index >= this.middlewares[type].length) { resolve(nextMessage); return; } this.middlewares[type][index](nextMessage, (anotherMessage) => { next(anotherMessage, ++index); }, reject); }; next(message, 0); }); } onMessage(originalMessage) { this.runMiddlewares("receive", originalMessage).then((message) => { if (!message.id) return; if (message.type == "request") { this.onRequest.call(this, message, (response, success) => { this.sendResponse(message.id, message.action, response, success); }); } else if (message.type == "response") { this.dequeueMessage(message.id, message.payload, message.success); } else if (message.type == "broadcast") { this.onBroadcast.call(this, message); } }, ::console.error); } onDisconnect() { this.connected = false; } queueMessage(message, timeout) { return new Promise((resolve, reject) => { const id = shortid.generate(); message.id = id; this.messageQueue.push(id); this.pendingMessages[id] = {message, resolve, reject}; this.sendMessage(message); if (_.isNumber(timeout) && timeout > 0) { setTimeout(() => { this.dequeueMessage(id, new Error("Timed out!"), false); }, timeout); } }); } dequeueMessage(id, result, success) { const pending = this.pendingMessages[id]; if (!pending) return; const index = this.messageQueue.indexOf(pending); if (index >= 0) { this.messageQueue.splice(index, 1); } delete this.pendingMessages[id]; if (success) { pending.resolve(result); } else { pending.reject(result); } } resendMessages() { _.each(this.messageQueue, (id) => { const pending = this.pendingMessages[id]; if (!pending) return; this.sendMessage(pending.message); }); while (this.unsentMessages.length > 0) { const message = this.unsentMessages.pop(); this.sendMessage(message); } } sendRequest(action, payload, timeout) { const message = {action, payload, type: "request", timeout}; return this.queueMessage(message, timeout); } sendResponse(id, action, payload, success) { this.sendMessage({ id, action, payload, type: "response", success: success !== false }); } sendBroadcast(id, action, payload) { this.sendMessage({ id, action, payload, type: "broadcast", }); } sendMessage(originalMessage) { if (!this.isConnected()) { this.unsentMessages.push(originalMessage); return; } this.runMiddlewares("send", originalMessage).then((message) => { this.port.postMessage(message); }, ::console.error); } }
{ "content_hash": "65407a0a938acf4d9e771af60af2498a", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 75, "avg_line_length": 26.26451612903226, "alnum_prop": 0.6062392532547286, "repo_name": "Frizz925/gbf-autopilot", "id": "1122a3b7459c2ade207e1c2e8c664ef4632e7e0a", "size": "4071", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/lib/messaging/PortMessaging.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1039" }, { "name": "JavaScript", "bytes": "65878" }, { "name": "Python", "bytes": "15416" } ], "symlink_target": "" }
layout: pdf title: View Resume permalink: /resume/ --- <iframe src="https://drive.google.com/file/d/1V4OmqvOuKuPcCfEoBiybxkBaAei2rfbW/view?usp=sharing" width="100%" height="100%"></iframe>
{ "content_hash": "6ff66d6792f504bac3be638f460e9d83", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 133, "avg_line_length": 38, "alnum_prop": 0.7473684210526316, "repo_name": "adityaKushwaha/adityaKushwaha.github.io", "id": "cf72e61735a4a0db05c5fd27d7995bd01518bb76", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resume.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "41302" }, { "name": "HTML", "bytes": "16396" }, { "name": "JavaScript", "bytes": "35" } ], "symlink_target": "" }
using System; using System.Linq; using System.Net; using NuGet.Resources; namespace NuGet { public class SettingsCredentialProvider : ICredentialProvider { private readonly ICredentialProvider _credentialProvider; private readonly IPackageSourceProvider _packageSourceProvider; private readonly ILogger _logger; public SettingsCredentialProvider(ICredentialProvider credentialProvider, IPackageSourceProvider packageSourceProvider) : this(credentialProvider, packageSourceProvider, NullLogger.Instance) { } public SettingsCredentialProvider(ICredentialProvider credentialProvider, IPackageSourceProvider packageSourceProvider, ILogger logger) { if (credentialProvider == null) { throw new ArgumentNullException("credentialProvider"); } if (packageSourceProvider == null) { throw new ArgumentNullException("packageSourceProvider"); } _credentialProvider = credentialProvider; _packageSourceProvider = packageSourceProvider; _logger = logger; } public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying) { NetworkCredential credentials; // If we are retrying, the stored credentials must be invalid. if (!retrying && (credentialType == CredentialType.RequestCredentials) && TryGetCredentials(uri, out credentials)) { _logger.Log(MessageLevel.Info, NuGetResources.SettingsCredentials_UsingSavedCredentials, credentials.UserName); return credentials; } return _credentialProvider.GetCredentials(uri, proxy, credentialType, retrying); } private bool TryGetCredentials(Uri uri, out NetworkCredential configurationCredentials) { var source = _packageSourceProvider.LoadPackageSources().FirstOrDefault(p => { Uri sourceUri; return !String.IsNullOrEmpty(p.UserName) && !String.IsNullOrEmpty(p.Password) && Uri.TryCreate(p.Source, UriKind.Absolute, out sourceUri) && UriUtility.UriEquals(sourceUri, uri); }); if (source == null) { // The source is not in the config file configurationCredentials = null; return false; } configurationCredentials = new NetworkCredential(source.UserName, source.Password); return true; } } }
{ "content_hash": "8a70600d96c63fcf601856c6aa3eea8e", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 143, "avg_line_length": 39.779411764705884, "alnum_prop": 0.6277264325323475, "repo_name": "aaasoft/NuGet.Server", "id": "3a2c898d60a6f19d44b721a2eeabf9ba89688927", "size": "2707", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Core/Configuration/SettingsCredentialProvider.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "1910" }, { "name": "Batchfile", "bytes": "1182" }, { "name": "C#", "bytes": "1028636" }, { "name": "Pascal", "bytes": "1140" }, { "name": "Shell", "bytes": "126" } ], "symlink_target": "" }
angular.module("myApp").service("spiderService", [ "spider", function (spider) { var self = this; this.messages = []; var randomString = function() { return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5); }; this.sendMessage = function (message) { spider.invoke("redSpider",{ message: message, sender: randomString() + "spider" }); spider.invoke("blueSpider", { message: message, sender: randomString() + "spider" }); // this is just to illustrate i use a random string, spider.invoke("mytopic", { message: message, sender: "mytopic" }); }; spider.on(/spider/, function (message) { self.messages.unshift(message); }); spider.on(/mytopic/, function (message) { self.messages.unshift(message); }); } ]).factory("spider", ["xsocketsController", function (xsocketsController) { return xsocketsController("generic"); // get generic as spider }]);
{ "content_hash": "1ed9634544dc30ab6bf763b34e87859f", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 83, "avg_line_length": 32.583333333333336, "alnum_prop": 0.5106564364876386, "repo_name": "MagnusThor/xsocketsAngularJS", "id": "15e5ac8a55e83488d565fecb3b586f4455913a52", "size": "1175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/js/services/spiderService.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "523" }, { "name": "HTML", "bytes": "3937" }, { "name": "JavaScript", "bytes": "39330" } ], "symlink_target": "" }
#define JPEG_INTERNALS #include "jinclude16.h" #include "jpeglib16.h" /* Pointer to routine to downsample a single component */ typedef JMETHOD(void, downsample1_ptr, (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data)); /* Private subobject */ typedef struct { struct jpeg_downsampler pub; /* public fields */ /* Downsampling method pointers, one per component */ downsample1_ptr methods[MAX_COMPONENTS]; } my_downsampler; typedef my_downsampler * my_downsample_ptr; /* * Initialize for a downsampling pass. */ METHODDEF(void) start_pass_downsample (j_compress_ptr cinfo) { /* no work for now */ } /* * Expand a component horizontally from width input_cols to width output_cols, * by duplicating the rightmost samples. */ LOCAL(void) expand_right_edge (JSAMPARRAY image_data, int num_rows, JDIMENSION input_cols, JDIMENSION output_cols) { register JSAMPROW ptr; register JSAMPLE pixval; register int count; int row; int numcols = (int) (output_cols - input_cols); if (numcols > 0) { for (row = 0; row < num_rows; row++) { ptr = image_data[row] + input_cols; pixval = ptr[-1]; /* don't need GETJSAMPLE() here */ for (count = numcols; count > 0; count--) *ptr++ = pixval; } } } /* * Do downsampling for a whole row group (all components). * * In this version we simply downsample each component independently. */ METHODDEF(void) sep_downsample (j_compress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION in_row_index, JSAMPIMAGE output_buf, JDIMENSION out_row_group_index) { my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample; int ci; jpeg_component_info * compptr; JSAMPARRAY in_ptr, out_ptr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { in_ptr = input_buf[ci] + in_row_index; out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor); (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr); } } /* * Downsample pixel values of a single component. * One row group is processed per call. * This version handles arbitrary integral sampling ratios, without smoothing. * Note that this version is not actually used for customary sampling ratios. */ METHODDEF(void) int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v; JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */ JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit; JSAMPROW inptr, outptr; IJG_INT32 outvalue; h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor; v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor; numpix = h_expand * v_expand; numpix2 = numpix/2; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * h_expand); inrow = 0; for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; for (outcol = 0, outcol_h = 0; outcol < output_cols; outcol++, outcol_h += h_expand) { outvalue = 0; for (v = 0; v < v_expand; v++) { inptr = input_data[inrow+v] + outcol_h; for (h = 0; h < h_expand; h++) { outvalue += (IJG_INT32) GETJSAMPLE(*inptr++); } } *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix); } inrow += v_expand; } } /* * Downsample pixel values of a single component. * This version handles the special case of a full-size component, * without smoothing. */ METHODDEF(void) fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { /* Copy the data */ jcopy_sample_rows(input_data, 0, output_data, 0, cinfo->max_v_samp_factor, cinfo->image_width); /* Edge-expand */ expand_right_edge(output_data, cinfo->max_v_samp_factor, cinfo->image_width, compptr->width_in_data_units * cinfo->data_unit); } /* * Downsample pixel values of a single component. * This version handles the common case of 2:1 horizontal and 1:1 vertical, * without smoothing. * * A note about the "bias" calculations: when rounding fractional values to * integer, we do not want to always round 0.5 up to the next integer. * If we did that, we'd introduce a noticeable bias towards larger values. * Instead, this code is arranged so that 0.5 will be rounded up or down at * alternate pixel locations (a simple ordered dither pattern). */ METHODDEF(void) h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int outrow; JDIMENSION outcol; JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit; register JSAMPROW inptr, outptr; register int bias; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * 2); for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr = input_data[outrow]; bias = 0; /* bias = 0,1,0,1,... for successive samples */ for (outcol = 0; outcol < output_cols; outcol++) { *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1]) + bias) >> 1); bias ^= 1; /* 0=>1, 1=>0 */ inptr += 2; } } } /* * Downsample pixel values of a single component. * This version handles the standard case of 2:1 horizontal and 2:1 vertical, * without smoothing. */ METHODDEF(void) h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow; JDIMENSION outcol; JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit; register JSAMPROW inptr0, inptr1, outptr; register int bias; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * 2); inrow = 0; for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr0 = input_data[inrow]; inptr1 = input_data[inrow+1]; bias = 1; /* bias = 1,2,1,2,... for successive samples */ for (outcol = 0; outcol < output_cols; outcol++) { *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]) + bias) >> 2); bias ^= 3; /* 1=>2, 2=>1 */ inptr0 += 2; inptr1 += 2; } inrow += 2; } } #ifdef INPUT_SMOOTHING_SUPPORTED /* * Downsample pixel values of a single component. * This version handles the standard case of 2:1 horizontal and 2:1 vertical, * with smoothing. One row of context is required. */ METHODDEF(void) h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow; JDIMENSION colctr; JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit; register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr; IJG_INT32 membersum, neighsum, memberscale, neighscale; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, cinfo->image_width, output_cols * 2); /* We don't bother to form the individual "smoothed" input pixel values; * we can directly compute the output which is the average of the four * smoothed values. Each of the four member pixels contributes a fraction * (1-8*SF) to its own smoothed image and a fraction SF to each of the three * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final * output. The four corner-adjacent neighbor pixels contribute a fraction * SF to just one smoothed pixel, or SF/4 to the final output; while the * eight edge-adjacent neighbors contribute SF to each of two smoothed * pixels, or SF/2 overall. In order to use integer arithmetic, these * factors are scaled by 2^16 = 65536. * Also recall that SF = smoothing_factor / 1024. */ memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */ neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */ inrow = 0; for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr0 = input_data[inrow]; inptr1 = input_data[inrow+1]; above_ptr = input_data[inrow-1]; below_ptr = input_data[inrow+2]; /* Special case for first column: pretend column -1 is same as column 0 */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]); neighsum += neighsum; neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]); membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; for (colctr = output_cols - 2; colctr > 0; colctr--) { /* sum of pixels directly mapped to this output element */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); /* sum of edge-neighbor pixels */ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]); /* The edge-neighbors count twice as much as corner-neighbors */ neighsum += neighsum; /* Add in the corner-neighbors */ neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]); /* form final output scaled up by 2^16 */ membersum = membersum * memberscale + neighsum * neighscale; /* round, descale and output it */ *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; } /* Special case for last column */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]); neighsum += neighsum; neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]); membersum = membersum * memberscale + neighsum * neighscale; *outptr = (JSAMPLE) ((membersum + 32768) >> 16); inrow += 2; } } /* * Downsample pixel values of a single component. * This version handles the special case of a full-size component, * with smoothing. One row of context is required. */ METHODDEF(void) fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int outrow; JDIMENSION colctr; JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit; register JSAMPROW inptr, above_ptr, below_ptr, outptr; IJG_INT32 membersum, neighsum, memberscale, neighscale; int colsum, lastcolsum, nextcolsum; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, cinfo->image_width, output_cols); /* Each of the eight neighbor pixels contributes a fraction SF to the * smoothed pixel, while the main pixel contributes (1-8*SF). In order * to use integer arithmetic, these factors are multiplied by 2^16 = 65536. * Also recall that SF = smoothing_factor / 1024. */ memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */ neighscale = cinfo->smoothing_factor * 64; /* scaled SF */ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr = input_data[outrow]; above_ptr = input_data[outrow-1]; below_ptr = input_data[outrow+1]; /* Special case for first column */ colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) + GETJSAMPLE(*inptr); membersum = GETJSAMPLE(*inptr++); nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(*inptr); neighsum = colsum + (colsum - membersum) + nextcolsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); lastcolsum = colsum; colsum = nextcolsum; for (colctr = output_cols - 2; colctr > 0; colctr--) { membersum = GETJSAMPLE(*inptr++); above_ptr++; below_ptr++; nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(*inptr); neighsum = lastcolsum + (colsum - membersum) + nextcolsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); lastcolsum = colsum; colsum = nextcolsum; } /* Special case for last column */ membersum = GETJSAMPLE(*inptr); neighsum = lastcolsum + (colsum - membersum) + colsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr = (JSAMPLE) ((membersum + 32768) >> 16); } } #endif /* INPUT_SMOOTHING_SUPPORTED */ /* * Module initialization routine for downsampling. * Note that we must select a routine for each component. */ GLOBAL(void) jinit_downsampler (j_compress_ptr cinfo) { my_downsample_ptr downsample; int ci; jpeg_component_info * compptr; boolean smoothok = TRUE; downsample = (my_downsample_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_downsampler)); cinfo->downsample = (struct jpeg_downsampler *) downsample; downsample->pub.start_pass = start_pass_downsample; downsample->pub.downsample = sep_downsample; downsample->pub.need_context_rows = FALSE; if (cinfo->CCIR601_sampling) ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); /* Verify we can handle the sampling factors, and set up method pointers */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (compptr->h_samp_factor == cinfo->max_h_samp_factor && compptr->v_samp_factor == cinfo->max_v_samp_factor) { #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor) { downsample->methods[ci] = fullsize_smooth_downsample; downsample->pub.need_context_rows = TRUE; } else #endif downsample->methods[ci] = fullsize_downsample; } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor && compptr->v_samp_factor == cinfo->max_v_samp_factor) { smoothok = FALSE; downsample->methods[ci] = h2v1_downsample; } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor && compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) { #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor) { downsample->methods[ci] = h2v2_smooth_downsample; downsample->pub.need_context_rows = TRUE; } else #endif downsample->methods[ci] = h2v2_downsample; } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 && (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) { smoothok = FALSE; downsample->methods[ci] = int_downsample; } else ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); } #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor && !smoothok) TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL); #endif }
{ "content_hash": "e660c6e2beecdc3b33602f2e9a8fe46e", "timestamp": "", "source": "github", "line_count": 474, "max_line_length": 79, "avg_line_length": 34.89873417721519, "alnum_prop": 0.6684802321363801, "repo_name": "OpenXIP/xip-libraries", "id": "1735ffcf20c37ca411e6446ddddb5f32049686cd", "size": "18957", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/extern/dcmtk-3.5.4/dcmjpeg/libijg16/jcsample.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "8314" }, { "name": "C", "bytes": "21064260" }, { "name": "C#", "bytes": "41726" }, { "name": "C++", "bytes": "33308677" }, { "name": "D", "bytes": "373" }, { "name": "Java", "bytes": "59889" }, { "name": "JavaScript", "bytes": "35954" }, { "name": "Objective-C", "bytes": "272450" }, { "name": "Perl", "bytes": "727865" }, { "name": "Prolog", "bytes": "101780" }, { "name": "Puppet", "bytes": "371631" }, { "name": "Python", "bytes": "162364" }, { "name": "Shell", "bytes": "906979" }, { "name": "Smalltalk", "bytes": "10530" }, { "name": "SuperCollider", "bytes": "2169433" }, { "name": "Tcl", "bytes": "10289" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>ARDP: /Developer/school/ardp/build/doc/html/search/typedefs_2.js Source File</title> <link href="../../tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../jquery.js"></script> <script type="text/javascript" src="../../dynsections.js"></script> <link href="../../search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../search/searchdata.js"></script> <script type="text/javascript" src="../../search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="../../doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">ARDP &#160;<span id="projectnumber">2.1.3</span> </div> <div id="projectbrief">Another RDF Document Parser</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "../../search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="../../index.html"><span>Main&#160;Page</span></a></li> <li><a href="../../pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="../../annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="../../files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="../../search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="../../search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="../../files.html"><span>File&#160;List</span></a></li> <li><a href="../../globals.html"><span>Globals</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="../../dir_4fef79e7177ba769987a8da36c892c5f.html">build</a></li><li class="navelem"><a class="el" href="../../dir_6c89d1ed406002b4e6ebce07fb51a507.html">doc</a></li><li class="navelem"><a class="el" href="../../dir_6d59e61439e3c30df274bbb82d8db25d.html">html</a></li><li class="navelem"><a class="el" href="../../dir_2556a4a0510dd1645ff20abdc7f57c5f.html">search</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">typedefs_2.js</div> </div> </div><!--header--> <div class="contents"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<a class="code" href="../../d8/d3c/util_8h.html#a335628f2e9085305224b4f9cc6e95ed5">var</a> searchData=</div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;[</div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160; [<span class="stringliteral">&#39;datatype_5fsys_5ft&#39;</span>,[<span class="stringliteral">&#39;datatype_sys_t&#39;</span>,[<span class="stringliteral">&#39;../parser_8h.html#adae28bf22d9d2b6f0261a1aa60093041&#39;</span>,1,<span class="stringliteral">&#39;parser.h&#39;</span>]]]</div> <div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;];</div> <div class="ttc" id="util_8h_html_a335628f2e9085305224b4f9cc6e95ed5"><div class="ttname"><a href="../../d8/d3c/util_8h.html#a335628f2e9085305224b4f9cc6e95ed5">var</a></div><div class="ttdeci">void * var</div><div class="ttdoc">Shortcut for void pointer. </div><div class="ttdef"><b>Definition:</b> <a href="../../d8/d3c/util_8h_source.html#l00043">util.h:43</a></div></div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Apr 19 2016 03:12:33 for ARDP by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="../../doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "256e232c253e4f116f725e40864ad2c1", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 417, "avg_line_length": 52.26168224299065, "alnum_prop": 0.6391273247496424, "repo_name": "michto01/ardp", "id": "8e981f98d330e4f6d8d1102323a0377f754711dd", "size": "5592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/d1/d31/typedefs__2_8js_source.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "66102" }, { "name": "Ragel in Ruby Host", "bytes": "24868" }, { "name": "Ruby", "bytes": "2869" }, { "name": "Shell", "bytes": "1003" } ], "symlink_target": "" }
/** * tree v3.0.6 * tree * author : yonyou FED * homepage : https://github.com/iuap-design/tree#readme * bugs : https://github.com/iuap-design/tree/issues **/ /* * JQuery zTree core v3.5.18 * http://zTree.me/ * * Copyright (c) 2010 Hunter.z * * Licensed same as jquery - MIT License * http://www.opensource.org/licenses/mit-license.php * * email: hunter.z@263.net * Date: 2015-06-18 */ (function($){ var settings = {}, roots = {}, caches = {}, //default consts of core _consts = { className: { BUTTON: "button", LEVEL: "level", ICO_LOADING: "ico_loading", SWITCH: "switch" }, event: { NODECREATED: "ztree_nodeCreated", CLICK: "ztree_click", EXPAND: "ztree_expand", COLLAPSE: "ztree_collapse", ASYNC_SUCCESS: "ztree_async_success", ASYNC_ERROR: "ztree_async_error", REMOVE: "ztree_remove", SELECTED: "ztree_selected", UNSELECTED: "ztree_unselected" }, id: { A: "_a", ICON: "_ico", SPAN: "_span", SWITCH: "_switch", UL: "_ul" }, line: { ROOT: "root", ROOTS: "roots", CENTER: "center", BOTTOM: "bottom", NOLINE: "noline", LINE: "line" }, folder: { OPEN: "open", CLOSE: "close", DOCU: "docu" }, node: { CURSELECTED: "curSelectedNode" } }, //default setting of core _setting = { treeId: "", treeObj: null, view: { addDiyDom: null, autoCancelSelected: true, dblClickExpand: true, expandSpeed: "fast", fontCss: {}, nameIsHTML: false, selectedMulti: true, showIcon: true, showLine: false, showTitle: true, txtSelectedEnable: false }, data: { key: { children: "children", name: "name", title: "", url: "url" }, simpleData: { enable: false, idKey: "id", pIdKey: "pId", rootPId: null }, keep: { parent: false, leaf: false } }, async: { enable: false, contentType: "application/x-www-form-urlencoded", type: "post", dataType: "text", url: "", autoParam: [], otherParam: [], dataFilter: null }, callback: { beforeAsync:null, beforeClick:null, beforeDblClick:null, beforeRightClick:null, beforeMouseDown:null, beforeMouseUp:null, beforeExpand:null, beforeCollapse:null, beforeRemove:null, onAsyncError:null, onAsyncSuccess:null, onNodeCreated:null, onClick:null, onDblClick:null, onRightClick:null, onMouseDown:null, onMouseUp:null, onExpand:null, onCollapse:null, onRemove:null } }, //default root of core //zTree use root to save full data _initRoot = function (setting) { var r = data.getRoot(setting); if (!r) { r = {}; data.setRoot(setting, r); } r[setting.data.key.children] = []; r.expandTriggerFlag = false; r.curSelectedList = []; r.noSelection = true; r.createdNodes = []; r.zId = 0; r._ver = (new Date()).getTime(); }, //default cache of core _initCache = function(setting) { var c = data.getCache(setting); if (!c) { c = {}; data.setCache(setting, c); } c.nodes = []; c.doms = []; }, //default bindEvent of core _bindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.bind(c.NODECREATED, function (event, treeId, node) { tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); }); o.bind(c.CLICK, function (event, srcEvent, treeId, node, clickFlag) { tools.apply(setting.callback.onClick, [srcEvent, treeId, node, clickFlag]); }); o.bind(c.EXPAND, function (event, treeId, node) { tools.apply(setting.callback.onExpand, [event, treeId, node]); }); o.bind(c.COLLAPSE, function (event, treeId, node) { tools.apply(setting.callback.onCollapse, [event, treeId, node]); }); o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); }); o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); }); o.bind(c.REMOVE, function (event, treeId, treeNode) { tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); }); o.bind(c.SELECTED, function (event, srcEvent, treeId, node) { tools.apply(setting.callback.onSelected, [srcEvent, treeId, node]); }); o.bind(c.UNSELECTED, function (event, srcEvent, treeId, node) { tools.apply(setting.callback.onUnSelected, [srcEvent, treeId, node]); }); }, _unbindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.unbind(c.NODECREATED) .unbind(c.CLICK) .unbind(c.EXPAND) .unbind(c.COLLAPSE) .unbind(c.ASYNC_SUCCESS) .unbind(c.ASYNC_ERROR) .unbind(c.REMOVE) .unbind(c.SELECTED) .unbind(c.UNSELECTED); }, //default event proxy of core _eventProxy = function(event) { var target = event.target, setting = data.getSetting(event.data.treeId), tId = "", node = null, nodeEventType = "", treeEventType = "", nodeEventCallback = null, treeEventCallback = null, tmp = null; if (tools.eqs(event.type, "mousedown")) { treeEventType = "mousedown"; } else if (tools.eqs(event.type, "mouseup")) { treeEventType = "mouseup"; } else if (tools.eqs(event.type, "contextmenu")) { treeEventType = "contextmenu"; } else if (tools.eqs(event.type, "click")) { if (tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.SWITCH) !== null) { tId = tools.getNodeMainDom(target).id; nodeEventType = "switchNode"; } else { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tools.getNodeMainDom(tmp).id; nodeEventType = "clickNode"; } } } else if (tools.eqs(event.type, "dblclick")) { treeEventType = "dblclick"; tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tools.getNodeMainDom(tmp).id; nodeEventType = "switchNode"; } } if (treeEventType.length > 0 && tId.length == 0) { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) {tId = tools.getNodeMainDom(tmp).id;} } // event to node if (tId.length>0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { case "switchNode" : if (!node.isParent) { nodeEventType = ""; } else if (tools.eqs(event.type, "click") || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { nodeEventCallback = handler.onSwitchNode; } else { nodeEventType = ""; } break; case "clickNode" : nodeEventCallback = handler.onClickNode; break; } } // event to zTree switch (treeEventType) { case "mousedown" : treeEventCallback = handler.onZTreeMousedown; break; case "mouseup" : treeEventCallback = handler.onZTreeMouseup; break; case "dblclick" : treeEventCallback = handler.onZTreeDblclick; break; case "contextmenu" : treeEventCallback = handler.onZTreeContextmenu; break; } var proxyResult = { stop: false, node: node, nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, treeEventCallback: treeEventCallback }; return proxyResult }, //default init node of core _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { if (!n) return; var r = data.getRoot(setting), childKey = setting.data.key.children; n.level = level; n.tId = setting.treeId + "_" + (++r.zId); n.parentTId = parentNode ? parentNode.tId : null; n.open = (typeof n.open == "string") ? tools.eqs(n.open, "true") : !!n.open; if (n[childKey] && n[childKey].length > 0) { n.isParent = true; n.zAsync = true; } else { n.isParent = (typeof n.isParent == "string") ? tools.eqs(n.isParent, "true") : !!n.isParent; n.open = (n.isParent && !setting.async.enable) ? n.open : false; n.zAsync = !n.isParent; } n.isFirstNode = isFirstNode; n.isLastNode = isLastNode; n.getParentNode = function() {return data.getNodeCache(setting, n.parentTId);}; n.getPreNode = function() {return data.getPreNode(setting, n);}; n.getNextNode = function() {return data.getNextNode(setting, n);}; n.isAjaxing = false; data.fixPIdKeyValue(setting, n); }, _init = { bind: [_bindEvent], unbind: [_unbindEvent], caches: [_initCache], nodes: [_initNode], proxys: [_eventProxy], roots: [_initRoot], beforeA: [], afterA: [], innerBeforeA: [], innerAfterA: [], zTreeTools: [] }, //method of operate data data = { addNodeCache: function(setting, node) { data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = node; }, getNodeCacheId: function(tId) { return tId.substring(tId.lastIndexOf("_")+1); }, addAfterA: function(afterA) { _init.afterA.push(afterA); }, addBeforeA: function(beforeA) { _init.beforeA.push(beforeA); }, addInnerAfterA: function(innerAfterA) { _init.innerAfterA.push(innerAfterA); }, addInnerBeforeA: function(innerBeforeA) { _init.innerBeforeA.push(innerBeforeA); }, addInitBind: function(bindEvent) { _init.bind.push(bindEvent); }, addInitUnBind: function(unbindEvent) { _init.unbind.push(unbindEvent); }, addInitCache: function(initCache) { _init.caches.push(initCache); }, addInitNode: function(initNode) { _init.nodes.push(initNode); }, addInitProxy: function(initProxy, isFirst) { if (!!isFirst) { _init.proxys.splice(0,0,initProxy); } else { _init.proxys.push(initProxy); } }, addInitRoot: function(initRoot) { _init.roots.push(initRoot); }, addNodesData: function(setting, parentNode, nodes) { var childKey = setting.data.key.children; if (!parentNode[childKey]) parentNode[childKey] = []; if (parentNode[childKey].length > 0) { parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); } parentNode.isParent = true; parentNode[childKey] = parentNode[childKey].concat(nodes); }, addSelectedNode: function(setting, node) { var root = data.getRoot(setting); if (!data.isSelectedNode(setting, node)) { root.curSelectedList.push(node); } }, addCreatedNode: function(setting, node) { if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { var root = data.getRoot(setting); root.createdNodes.push(node); } }, addZTreeTools: function(zTreeTools) { _init.zTreeTools.push(zTreeTools); }, exSetting: function(s) { $.extend(true, _setting, s); }, fixPIdKeyValue: function(setting, node) { if (setting.data.simpleData.enable) { node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; } }, getAfterA: function(setting, node, array) { for (var i=0, j=_init.afterA.length; i<j; i++) { _init.afterA[i].apply(this, arguments); } }, getBeforeA: function(setting, node, array) { for (var i=0, j=_init.beforeA.length; i<j; i++) { _init.beforeA[i].apply(this, arguments); } }, getInnerAfterA: function(setting, node, array) { for (var i=0, j=_init.innerAfterA.length; i<j; i++) { _init.innerAfterA[i].apply(this, arguments); } }, getInnerBeforeA: function(setting, node, array) { for (var i=0, j=_init.innerBeforeA.length; i<j; i++) { _init.innerBeforeA[i].apply(this, arguments); } }, getCache: function(setting) { return caches[setting.treeId]; }, getNextNode: function(setting, node) { if (!node) return null; var childKey = setting.data.key.children, p = node.parentTId ? node.getParentNode() : data.getRoot(setting); for (var i=0, l=p[childKey].length-1; i<=l; i++) { if (p[childKey][i] === node) { return (i==l ? null : p[childKey][i+1]); } } return null; }, getNodeByParam: function(setting, nodes, key, value) { if (!nodes || !key) return null; var childKey = setting.data.key.children; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i][key] == value) { return nodes[i]; } var tmp = data.getNodeByParam(setting, nodes[i][childKey], key, value); if (tmp) return tmp; } return null; }, getNodeCache: function(setting, tId) { if (!tId) return null; var n = caches[setting.treeId].nodes[data.getNodeCacheId(tId)]; return n ? n : null; }, getNodeName: function(setting, node) { var nameKey = setting.data.key.name; return "" + node[nameKey]; }, getNodeTitle: function(setting, node) { var t = setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title; return "" + node[t]; }, getNodes: function(setting) { return data.getRoot(setting)[setting.data.key.children]; }, getNodesByParam: function(setting, nodes, key, value) { if (!nodes || !key) return []; var childKey = setting.data.key.children, result = []; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i][key] == value) { result.push(nodes[i]); } result = result.concat(data.getNodesByParam(setting, nodes[i][childKey], key, value)); } return result; }, getNodesByParamFuzzy: function(setting, nodes, key, value) { if (!nodes || !key) return []; var childKey = setting.data.key.children, result = []; value = value.toLowerCase(); for (var i = 0, l = nodes.length; i < l; i++) { if (typeof nodes[i][key] == "string" && nodes[i][key].toLowerCase().indexOf(value)>-1) { result.push(nodes[i]); } result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); } return result; }, getNodesByFilter: function(setting, nodes, filter, isSingle, invokeParam) { if (!nodes) return (isSingle ? null : []); var childKey = setting.data.key.children, result = isSingle ? null : []; for (var i = 0, l = nodes.length; i < l; i++) { if (tools.apply(filter, [nodes[i], invokeParam], false)) { if (isSingle) {return nodes[i];} result.push(nodes[i]); } var tmpResult = data.getNodesByFilter(setting, nodes[i][childKey], filter, isSingle, invokeParam); if (isSingle && !!tmpResult) {return tmpResult;} result = isSingle ? tmpResult : result.concat(tmpResult); } return result; }, getPreNode: function(setting, node) { if (!node) return null; var childKey = setting.data.key.children, p = node.parentTId ? node.getParentNode() : data.getRoot(setting); for (var i=0, l=p[childKey].length; i<l; i++) { if (p[childKey][i] === node) { return (i==0 ? null : p[childKey][i-1]); } } return null; }, getRoot: function(setting) { return setting ? roots[setting.treeId] : null; }, getRoots: function() { return roots; }, getSetting: function(treeId) { return settings[treeId]; }, getSettings: function() { return settings; }, getZTreeTools: function(treeId) { var r = this.getRoot(this.getSetting(treeId)); return r ? r.treeTools : null; }, initCache: function(setting) { for (var i=0, j=_init.caches.length; i<j; i++) { _init.caches[i].apply(this, arguments); } }, initNode: function(setting, level, node, parentNode, preNode, nextNode) { for (var i=0, j=_init.nodes.length; i<j; i++) { _init.nodes[i].apply(this, arguments); } }, initRoot: function(setting) { for (var i=0, j=_init.roots.length; i<j; i++) { _init.roots[i].apply(this, arguments); } }, isSelectedNode: function(setting, node) { var root = data.getRoot(setting); for (var i=0, j=root.curSelectedList.length; i<j; i++) { if(node === root.curSelectedList[i]) return true; } return false; }, removeNodeCache: function(setting, node) { var childKey = setting.data.key.children; if (node[childKey]) { for (var i=0, l=node[childKey].length; i<l; i++) { arguments.callee(setting, node[childKey][i]); } } data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = null; }, removeSelectedNode: function(setting, node) { var root = data.getRoot(setting); for (var i=0, j=root.curSelectedList.length; i<j; i++) { if(node === root.curSelectedList[i] || !data.getNodeCache(setting, root.curSelectedList[i].tId)) { root.curSelectedList.splice(i, 1); i--;j--; } } }, setCache: function(setting, cache) { caches[setting.treeId] = cache; }, setRoot: function(setting, root) { roots[setting.treeId] = root; }, setZTreeTools: function(setting, zTreeTools) { for (var i=0, j=_init.zTreeTools.length; i<j; i++) { _init.zTreeTools[i].apply(this, arguments); } }, transformToArrayFormat: function (setting, nodes) { if (!nodes) return []; var childKey = setting.data.key.children, r = []; if (tools.isArray(nodes)) { for (var i=0, l=nodes.length; i<l; i++) { r.push(nodes[i]); if (nodes[i][childKey]) r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey])); } } else { r.push(nodes); if (nodes[childKey]) r = r.concat(data.transformToArrayFormat(setting, nodes[childKey])); } return r; }, transformTozTreeFormat: function(setting, sNodes) { var i,l, key = setting.data.simpleData.idKey, parentKey = setting.data.simpleData.pIdKey, childKey = setting.data.key.children; if (!key || key=="" || !sNodes) return []; if (tools.isArray(sNodes)) { var r = []; var tmpMap = []; for (i=0, l=sNodes.length; i<l; i++) { tmpMap[sNodes[i][key]] = sNodes[i]; } for (i=0, l=sNodes.length; i<l; i++) { if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) { if (!tmpMap[sNodes[i][parentKey]][childKey]) tmpMap[sNodes[i][parentKey]][childKey] = []; tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]); } else { r.push(sNodes[i]); } } return r; }else { return [sNodes]; } } }, //method of event proxy event = { bindEvent: function(setting) { for (var i=0, j=_init.bind.length; i<j; i++) { _init.bind[i].apply(this, arguments); } }, unbindEvent: function(setting) { for (var i=0, j=_init.unbind.length; i<j; i++) { _init.unbind[i].apply(this, arguments); } }, bindTree: function(setting) { var eventParam = { treeId: setting.treeId }, o = setting.treeObj; if (!setting.view.txtSelectedEnable) { // for can't select text o.bind('selectstart', function(e){ var node var n = e.originalEvent.srcElement.nodeName.toLowerCase(); return (n === "input" || n === "textarea" ); }).css({ "-moz-user-select":"-moz-none" }); } o.bind('click', eventParam, event.proxy); o.bind('dblclick', eventParam, event.proxy); o.bind('mouseover', eventParam, event.proxy); o.bind('mouseout', eventParam, event.proxy); o.bind('mousedown', eventParam, event.proxy); o.bind('mouseup', eventParam, event.proxy); o.bind('contextmenu', eventParam, event.proxy); }, unbindTree: function(setting) { var o = setting.treeObj; o.unbind('click', event.proxy) .unbind('dblclick', event.proxy) .unbind('mouseover', event.proxy) .unbind('mouseout', event.proxy) .unbind('mousedown', event.proxy) .unbind('mouseup', event.proxy) .unbind('contextmenu', event.proxy); }, doProxy: function(e) { var results = []; for (var i=0, j=_init.proxys.length; i<j; i++) { var proxyResult = _init.proxys[i].apply(this, arguments); results.push(proxyResult); if (proxyResult.stop) { break; } } return results; }, proxy: function(e) { var setting = data.getSetting(e.data.treeId); if (!tools.uCanDo(setting, e)) return true; var results = event.doProxy(e), r = true, x = false; for (var i=0, l=results.length; i<l; i++) { var proxyResult = results[i]; if (proxyResult.nodeEventCallback) { x = true; r = proxyResult.nodeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; } if (proxyResult.treeEventCallback) { x = true; r = proxyResult.treeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; } } return r; } }, //method of event handler handler = { onSwitchNode: function (event, node) { var setting = data.getSetting(event.data.treeId); if (node.open) { if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) return true; data.getRoot(setting).expandTriggerFlag = true; view.switchNode(setting, node); } else { if (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false) return true; data.getRoot(setting).expandTriggerFlag = true; view.switchNode(setting, node); } return true; }, onClickNode: function (event, node) { //点击时取消所有超链接效果 $('#'+event.data.treeId+' a').removeClass('focusNode'); //添加focusNode样式 $('#'+node.tId+'_a').addClass('focusNode'); var setting = data.getSetting(event.data.treeId), clickFlag = ( (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey)) && data.isSelectedNode(setting, node)) ? 0 : (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey) && setting.view.selectedMulti) ? 2 : 1; if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) return true; if (clickFlag === 0) { view.cancelPreSelectedNode(setting, node); } else { view.selectNode(setting, node, clickFlag === 2); } setting.treeObj.trigger(consts.event.CLICK, [event, setting.treeId, node, clickFlag]); return true; }, onZTreeMousedown: function(event, node) { var setting = data.getSetting(event.data.treeId); if (tools.apply(setting.callback.beforeMouseDown, [setting.treeId, node], true)) { tools.apply(setting.callback.onMouseDown, [event, setting.treeId, node]); } return true; }, onZTreeMouseup: function(event, node) { var setting = data.getSetting(event.data.treeId); if (tools.apply(setting.callback.beforeMouseUp, [setting.treeId, node], true)) { tools.apply(setting.callback.onMouseUp, [event, setting.treeId, node]); } return true; }, onZTreeDblclick: function(event, node) { var setting = data.getSetting(event.data.treeId); if (tools.apply(setting.callback.beforeDblClick, [setting.treeId, node], true)) { tools.apply(setting.callback.onDblClick, [event, setting.treeId, node]); } return true; }, onZTreeContextmenu: function(event, node) { var setting = data.getSetting(event.data.treeId); if (tools.apply(setting.callback.beforeRightClick, [setting.treeId, node], true)) { tools.apply(setting.callback.onRightClick, [event, setting.treeId, node]); } return (typeof setting.callback.onRightClick) != "function"; } }, //method of tools for zTree tools = { apply: function(fun, param, defaultValue) { if ((typeof fun) == "function") { return fun.apply(zt, param?param:[]); } return defaultValue; }, canAsync: function(setting, node) { var childKey = setting.data.key.children; return (setting.async.enable && node && node.isParent && !(node.zAsync || (node[childKey] && node[childKey].length > 0))); }, clone: function (obj){ if (obj === null) return null; var o = tools.isArray(obj) ? [] : {}; for(var i in obj){ o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]); } return o; }, eqs: function(str1, str2) { return str1.toLowerCase() === str2.toLowerCase(); }, isArray: function(arr) { return Object.prototype.toString.apply(arr) === "[object Array]"; }, $: function(node, exp, setting) { if (!!exp && typeof exp != "string") { setting = exp; exp = ""; } if (typeof node == "string") { return $(node, setting ? setting.treeObj.get(0).ownerDocument : null); } else { return $("#" + node.tId + exp, setting ? setting.treeObj : null); } }, getMDom: function (setting, curDom, targetExpr) { if (!curDom) return null; while (curDom && curDom.id !== setting.treeId) { for (var i=0, l=targetExpr.length; curDom.tagName && i<l; i++) { if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) { return curDom; } } curDom = curDom.parentNode; } return null; }, getNodeMainDom:function(target) { return ($(target).parent("li").get(0) || $(target).parentsUntil("li").parent().get(0)); }, isChildOrSelf: function(dom, parentId) { return ( $(dom).closest("#" + parentId).length> 0 ); }, uCanDo: function(setting, e) { return true; } }, //method of operate ztree dom view = { addNodes: function(setting, parentNode, newNodes, isSilent) { if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { return; } if (!tools.isArray(newNodes)) { newNodes = [newNodes]; } if (setting.data.simpleData.enable) { newNodes = data.transformTozTreeFormat(setting, newNodes); } if (parentNode) { var target_switchObj = $$(parentNode, consts.id.SWITCH, setting), target_icoObj = $$(parentNode, consts.id.ICON, setting), target_ulObj = $$(parentNode, consts.id.UL, setting); if (!parentNode.open) { view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); parentNode.open = false; target_ulObj.css({ "display": "none" }); } data.addNodesData(setting, parentNode, newNodes); view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); if (!isSilent) { view.expandCollapseParentNode(setting, parentNode, true); } } else { data.addNodesData(setting, data.getRoot(setting), newNodes); view.createNodes(setting, 0, newNodes, null); } }, appendNodes: function(setting, level, nodes, parentNode, initFlag, openFlag) { if (!nodes) return []; var html = [], childKey = setting.data.key.children; for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (initFlag) { var tmpPNode = (parentNode) ? parentNode: data.getRoot(setting), tmpPChild = tmpPNode[childKey], isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), isLastNode = (i == (nodes.length - 1)); data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); data.addNodeCache(setting, node); } var childHtml = []; if (node[childKey] && node[childKey].length > 0) { //make child html first, because checkType childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); } if (openFlag) { // setting.treeObj.offsetWidth=setting.treeObj[0].offsetWidth; view.makeDOMNodeMainBefore(html, setting, node); view.makeDOMNodeLine(html, setting, node); data.getBeforeA(setting, node, html); view.makeDOMNodeNameBefore(html, setting, node); data.getInnerBeforeA(setting, node, html); view.makeDOMNodeIcon(html, setting, node); data.getInnerAfterA(setting, node, html); view.makeDOMNodeNameAfter(html, setting, node); data.getAfterA(setting, node, html); if (node.isParent && node.open) { view.makeUlHtml(setting, node, html, childHtml.join('')); } view.makeDOMNodeMainAfter(html, setting, node); data.addCreatedNode(setting, node); } } return html; }, appendParentULDom: function(setting, node) { var html = [], nObj = $$(node, setting); if (!nObj.get(0) && !!node.parentTId) { view.appendParentULDom(setting, node.getParentNode()); nObj = $$(node, setting); } var ulObj = $$(node, consts.id.UL, setting); if (ulObj.get(0)) { ulObj.remove(); } var childKey = setting.data.key.children, childHtml = view.appendNodes(setting, node.level+1, node[childKey], node, false, true); view.makeUlHtml(setting, node, html, childHtml.join('')); nObj.append(html.join('')); }, asyncNode: function(setting, node, isSilent, callback) { var i, l; if (node && !node.isParent) { tools.apply(callback); return false; } else if (node && node.isAjaxing) { return false; } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { tools.apply(callback); return false; } if (node) { node.isAjaxing = true; var icoObj = $$(node, consts.id.ICON, setting); icoObj.attr({"style":"", "class":consts.className.BUTTON + " " + consts.className.ICO_LOADING}); } var tmpParam = {}; for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { var pKey = setting.async.autoParam[i].split("="), spKey = pKey; if (pKey.length>1) { spKey = pKey[1]; pKey = pKey[0]; } tmpParam[spKey] = node[pKey]; } if (tools.isArray(setting.async.otherParam)) { for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { tmpParam[setting.async.otherParam[i]] = setting.async.otherParam[i + 1]; } } else { for (var p in setting.async.otherParam) { tmpParam[p] = setting.async.otherParam[p]; } } var _tmpV = data.getRoot(setting)._ver; if (setting.async.selfLoadFunc && typeof setting.async.selfLoadFunc == 'function'){ setting.async.selfLoadFunc.apply(this, node) } else{ $.ajax({ contentType: setting.async.contentType, cache: false, type: setting.async.type, url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), data: tmpParam, dataType: setting.async.dataType, success: function(msg) { if (_tmpV != data.getRoot(setting)._ver) { return; } var newNodes = []; try { if (!msg || msg.length == 0) { newNodes = []; } else if (typeof msg == "string") { newNodes = eval("(" + msg + ")"); } else { newNodes = msg; } } catch(err) { newNodes = msg; } if (node) { node.isAjaxing = null; node.zAsync = true; } view.setNodeLineIcos(setting, node); if (newNodes && newNodes !== "") { newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); view.addNodes(setting, node, !!newNodes ? tools.clone(newNodes) : [], !!isSilent); } else { view.addNodes(setting, node, [], !!isSilent); } setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); tools.apply(callback); }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (_tmpV != data.getRoot(setting)._ver) { return; } if (node) node.isAjaxing = null; view.setNodeLineIcos(setting, node); setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); } }); } return true; }, cancelPreSelectedNode: function (setting, node, excludeNode) { var list = data.getRoot(setting).curSelectedList, i, n; for (i=list.length-1; i>=0; i--) { n = list[i]; if (node === n || (!node && (!excludeNode || excludeNode !== n))) { $$(n, consts.id.A, setting).removeClass(consts.node.CURSELECTED); if (node) { data.removeSelectedNode(setting, node); setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); break; } else { list.splice(i, 1); setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); } } } }, createNodeCallback: function(setting) { if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { var root = data.getRoot(setting); while (root.createdNodes.length>0) { var node = root.createdNodes.shift(); tools.apply(setting.view.addDiyDom, [setting.treeId, node]); if (!!setting.callback.onNodeCreated) { setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); } } } }, createNodes: function(setting, level, nodes, parentNode) { if (!nodes || nodes.length == 0) return; var root = data.getRoot(setting), childKey = setting.data.key.children, openFlag = !parentNode || parentNode.open || !!$$(parentNode[childKey][0], setting).get(0); root.createdNodes = []; var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); if (!parentNode) { setting.treeObj.append(zTreeHtml.join('')); } else { var ulObj = $$(parentNode, consts.id.UL, setting); if (ulObj.get(0)) { ulObj.append(zTreeHtml.join('')); } } view.createNodeCallback(setting); }, destroy: function(setting) { if (!setting) return; data.initCache(setting); data.initRoot(setting); event.unbindTree(setting); event.unbindEvent(setting); setting.treeObj.empty(); delete settings[setting.treeId]; }, expandCollapseNode: function(setting, node, expandFlag, animateFlag, callback) { var root = data.getRoot(setting), childKey = setting.data.key.children; if (!node) { tools.apply(callback, []); return; } if (root.expandTriggerFlag) { var _callback = callback; callback = function(){ if (_callback) _callback(); if (node.open) { setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); } else { setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); } }; root.expandTriggerFlag = false; } if (!node.open && node.isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (node[childKey] && node[childKey].length>0 && !$$(node[childKey][0], setting).get(0)))) { view.appendParentULDom(setting, node); view.createNodeCallback(setting); } if (node.open == expandFlag) { tools.apply(callback, []); return; } var ulObj = $$(node, consts.id.UL, setting), switchObj = $$(node, consts.id.SWITCH, setting), icoObj = $$(node, consts.id.ICON, setting); if (node.isParent) { node.open = !node.open; if (node.iconOpen && node.iconClose) { icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); } if (node.open) { view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); view.replaceIcoClass(node, icoObj, consts.folder.OPEN); if (animateFlag == false || setting.view.expandSpeed == "") { ulObj.show(); tools.apply(callback, []); } else { if (node[childKey] && node[childKey].length > 0) { ulObj.slideDown(setting.view.expandSpeed, callback); } else { ulObj.show(); tools.apply(callback, []); } } } else { view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); if (animateFlag == false || setting.view.expandSpeed == "" || !(node[childKey] && node[childKey].length > 0)) { ulObj.hide(); tools.apply(callback, []); } else { ulObj.slideUp(setting.view.expandSpeed, callback); } } } else { tools.apply(callback, []); } }, expandCollapseParentNode: function(setting, node, expandFlag, animateFlag, callback) { if (!node) return; if (!node.parentTId) { view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); return; } else { view.expandCollapseNode(setting, node, expandFlag, animateFlag); } if (node.parentTId) { view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); } }, expandCollapseSonNode: function(setting, node, expandFlag, animateFlag, callback) { var root = data.getRoot(setting), childKey = setting.data.key.children, treeNodes = (node) ? node[childKey]: root[childKey], selfAnimateSign = (node) ? false : animateFlag, expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; data.getRoot(setting).expandTriggerFlag = false; if (treeNodes) { for (var i = 0, l = treeNodes.length; i < l; i++) { if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); } } data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); }, isSelectedNode: function (setting, node) { if (!node) { return false; } var list = data.getRoot(setting).curSelectedList, i; for (i=list.length-1; i>=0; i--) { if (node === list[i]) { return true; } } return false; }, makeDOMNodeIcon: function(html, setting, node) { var nameStr = data.getNodeName(setting, node), name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); html.push("<span id='", node.tId, consts.id.ICON, "' title='' treeNode", consts.id.ICON," class='", view.makeNodeIcoClass(setting, node), "' style='", view.makeNodeIcoStyle(setting, node), "'></span><span id='", node.tId, consts.id.SPAN, "'>",name,"</span>"); }, makeDOMNodeLine: function(html, setting, node) { html.push("<span id='", node.tId, consts.id.SWITCH, "' title='' class='", view.makeNodeLineClass(setting, node), "' treeNode", consts.id.SWITCH,"></span>"); }, makeDOMNodeMainAfter: function(html, setting, node) { html.push("</li>"); }, makeDOMNodeMainBefore: function(html, setting, node) { html.push("<li id='", node.tId, "' class='", consts.className.LEVEL, node.level,"' tabindex='0' hidefocus='true' treenode>"); }, makeDOMNodeNameAfter: function(html, setting, node) { html.push("</a>"); }, makeDOMNodeNameBefore: function(html, setting, node) { var title = data.getNodeTitle(setting, node), url = view.makeNodeUrl(setting, node), fontcss = view.makeNodeFontCss(setting, node), // parDomWidth=setting.treeObj.offsetWidth, // parPaddingLeft=parseInt(setting.treeObj.css('paddingLeft')), parPaddingLeft=9, checkboxLength=18, iconLength=21, pLeft, fontStyle = []; if(setting.check.enable){ pLeft=checkboxLength+parPaddingLeft+iconLength*(node.level+1)+'px'; }else{ pLeft=parPaddingLeft+iconLength*(node.level+1)+'px'; } fontStyle.push('padding-left', ":",pLeft, ";"); fontStyle.push('margin-left', ":", '-'+pLeft, ";"); // 将a标签的宽度根据上级100%再加上层级之间的padding值算出 parDomWidth='calc(100% + '+18*(node.level+1) +'px )'; fontStyle.push('min-width', ":", parDomWidth, ";"); for (var f in fontcss) { fontStyle.push(f, ":", fontcss[f], ";"); } // 添加width,padding html.push("<a id='", node.tId, consts.id.A, "' class='", consts.className.LEVEL, node.level,"' treeNode", consts.id.A," onclick=\"", (node.click || ''), "\" ", ((url != null && url.length > 0) ? "href='" + url + "'" : ""), " target='",view.makeNodeTarget(node),"' style='", fontStyle.join(''), "'"); if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) {html.push("title='", title.replace(/'/g,"&#39;").replace(/</g,'&lt;').replace(/>/g,'&gt;'),"'");} html.push(">"); }, makeNodeFontCss: function(setting, node) { var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); return (fontCss && ((typeof fontCss) != "function")) ? fontCss : {}; }, makeNodeIcoClass: function(setting, node) { var icoCss = ["ico"]; if (!node.isAjaxing) { icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; if (node.isParent) { icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); } else { icoCss.push(consts.folder.DOCU); } } return consts.className.BUTTON + " " + icoCss.join('_'); }, makeNodeIcoStyle: function(setting, node) { var icoStyle = []; if (!node.isAjaxing) { var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { icoStyle.push("width:0px;height:0px;"); } } return icoStyle.join(''); }, makeNodeLineClass: function(setting, node) { var lineClass = []; if (setting.view.showLine) { if (node.level == 0 && node.isFirstNode && node.isLastNode) { lineClass.push(consts.line.ROOT); } else if (node.level == 0 && node.isFirstNode) { lineClass.push(consts.line.ROOTS); } else if (node.isLastNode) { lineClass.push(consts.line.BOTTOM); } else { lineClass.push(consts.line.CENTER); } } else { lineClass.push(consts.line.NOLINE); } if (node.isParent) { lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); } else { lineClass.push(consts.folder.DOCU); } return view.makeNodeLineClassEx(node) + lineClass.join('_'); }, makeNodeLineClassEx: function(node) { return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; }, makeNodeTarget: function(node) { return (node.target || "_blank"); }, makeNodeUrl: function(setting, node) { var urlKey = setting.data.key.url; return node[urlKey] ? node[urlKey] : null; }, makeUlHtml: function(setting, node, html, content) { html.push("<ul id='", node.tId, consts.id.UL, "' class='", consts.className.LEVEL, node.level, " ", view.makeUlLineClass(setting, node), "' style='display:", (node.open ? "block": "none"),"'>"); html.push(content); html.push("</ul>"); }, makeUlLineClass: function(setting, node) { return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); }, removeChildNodes: function(setting, node) { if (!node) return; var childKey = setting.data.key.children, nodes = node[childKey]; if (!nodes) return; for (var i = 0, l = nodes.length; i < l; i++) { data.removeNodeCache(setting, nodes[i]); } data.removeSelectedNode(setting); delete node[childKey]; if (!setting.data.keep.parent) { node.isParent = false; node.open = false; var tmp_switchObj = $$(node, consts.id.SWITCH, setting), tmp_icoObj = $$(node, consts.id.ICON, setting); view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); $$(node, consts.id.UL, setting).remove(); } else { $$(node, consts.id.UL, setting).empty(); } }, setFirstNode: function(setting, parentNode) { var childKey = setting.data.key.children, childLength = parentNode[childKey].length; if ( childLength > 0) { parentNode[childKey][0].isFirstNode = true; } }, setLastNode: function(setting, parentNode) { var childKey = setting.data.key.children, childLength = parentNode[childKey].length; if ( childLength > 0) { parentNode[childKey][childLength - 1].isLastNode = true; } }, removeNode: function(setting, node) { var root = data.getRoot(setting), childKey = setting.data.key.children, parentNode = (node.parentTId) ? node.getParentNode() : root; node.isFirstNode = false; node.isLastNode = false; node.getPreNode = function() {return null;}; node.getNextNode = function() {return null;}; if (!data.getNodeCache(setting, node.tId)) { return; } $$(node, setting).remove(); data.removeNodeCache(setting, node); data.removeSelectedNode(setting, node); for (var i = 0, l = parentNode[childKey].length; i < l; i++) { if (parentNode[childKey][i].tId == node.tId) { parentNode[childKey].splice(i, 1); break; } } view.setFirstNode(setting, parentNode); view.setLastNode(setting, parentNode); var tmp_ulObj,tmp_switchObj,tmp_icoObj, childLength = parentNode[childKey].length; //repair nodes old parent if (!setting.data.keep.parent && childLength == 0) { //old parentNode has no child nodes parentNode.isParent = false; parentNode.open = false; tmp_ulObj = $$(parentNode, consts.id.UL, setting); tmp_switchObj = $$(parentNode, consts.id.SWITCH, setting); tmp_icoObj = $$(parentNode, consts.id.ICON, setting); view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); tmp_ulObj.css("display", "none"); } else if (setting.view.showLine && childLength > 0) { //old parentNode has child nodes var newLast = parentNode[childKey][childLength - 1]; tmp_ulObj = $$(newLast, consts.id.UL, setting); tmp_switchObj = $$(newLast, consts.id.SWITCH, setting); tmp_icoObj = $$(newLast, consts.id.ICON, setting); if (parentNode == root) { if (parentNode[childKey].length == 1) { //node was root, and ztree has only one root after move node view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); } else { var tmp_first_switchObj = $$(parentNode[childKey][0], consts.id.SWITCH, setting); view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); } } else { view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); } tmp_ulObj.removeClass(consts.line.LINE); } }, replaceIcoClass: function(node, obj, newName) { if (!obj || node.isAjaxing) return; var tmpName = obj.attr("class"); if (tmpName == undefined) return; var tmpList = tmpName.split("_"); switch (newName) { case consts.folder.OPEN: case consts.folder.CLOSE: case consts.folder.DOCU: tmpList[tmpList.length-1] = newName; break; } obj.attr("class", tmpList.join("_")); }, replaceSwitchClass: function(node, obj, newName) { if (!obj) return; var tmpName = obj.attr("class"); if (tmpName == undefined) return; var tmpList = tmpName.split("_"); switch (newName) { case consts.line.ROOT: case consts.line.ROOTS: case consts.line.CENTER: case consts.line.BOTTOM: case consts.line.NOLINE: tmpList[0] = view.makeNodeLineClassEx(node) + newName; break; case consts.folder.OPEN: case consts.folder.CLOSE: case consts.folder.DOCU: tmpList[1] = newName; break; } obj.attr("class", tmpList.join("_")); if (newName !== consts.folder.DOCU) { obj.removeAttr("disabled"); } else { obj.attr("disabled", "disabled"); } }, selectNode: function(setting, node, addFlag) { if (!addFlag) { view.cancelPreSelectedNode(setting, null, node); } $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED); data.addSelectedNode(setting, node); setting.treeObj.trigger(consts.event.SELECTED, [event, setting.treeId, node]); }, setNodeFontCss: function(setting, treeNode) { var aObj = $$(treeNode, consts.id.A, setting), fontCss = view.makeNodeFontCss(setting, treeNode); if (fontCss) { aObj.css(fontCss); } }, setNodeLineIcos: function(setting, node) { if (!node) return; var switchObj = $$(node, consts.id.SWITCH, setting), ulObj = $$(node, consts.id.UL, setting), icoObj = $$(node, consts.id.ICON, setting), ulLine = view.makeUlLineClass(setting, node); if (ulLine.length==0) { ulObj.removeClass(consts.line.LINE); } else { ulObj.addClass(ulLine); } switchObj.attr("class", view.makeNodeLineClass(setting, node)); if (node.isParent) { switchObj.removeAttr("disabled"); } else { switchObj.attr("disabled", "disabled"); } icoObj.removeAttr("style"); icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); icoObj.attr("class", view.makeNodeIcoClass(setting, node)); }, setNodeName: function(setting, node) { var title = data.getNodeTitle(setting, node), nObj = $$(node, consts.id.SPAN, setting); nObj.empty(); if (setting.view.nameIsHTML) { nObj.html(data.getNodeName(setting, node)); } else { nObj.text(data.getNodeName(setting, node)); } if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle)) { var aObj = $$(node, consts.id.A, setting); aObj.attr("title", !title ? "" : title); } }, setNodeTarget: function(setting, node) { var aObj = $$(node, consts.id.A, setting); aObj.attr("target", view.makeNodeTarget(node)); }, setNodeUrl: function(setting, node) { var aObj = $$(node, consts.id.A, setting), url = view.makeNodeUrl(setting, node); if (url == null || url.length == 0) { aObj.removeAttr("href"); } else { aObj.attr("href", url); } }, switchNode: function(setting, node) { if (node.open || !tools.canAsync(setting, node)) { view.expandCollapseNode(setting, node, !node.open); } else if (setting.async.enable) { if (!view.asyncNode(setting, node)) { view.expandCollapseNode(setting, node, !node.open); return; } } else if (node) { view.expandCollapseNode(setting, node, !node.open); } } }; // zTree defind $.fn.zTree = { consts : _consts, _z : { tools: tools, view: view, event: event, data: data }, getZTreeObj: function(treeId) { var o = data.getZTreeTools(treeId); return o ? o : null; }, destroy: function(treeId) { if (!!treeId && treeId.length > 0) { view.destroy(data.getSetting(treeId)); } else { for(var s in settings) { view.destroy(settings[s]); } } }, init: function(obj, zSetting, zNodes) { var setting = tools.clone(_setting); $.extend(true, setting, zSetting); setting.treeId = obj.attr("id"); setting.treeObj = obj; setting.treeObj.empty(); settings[setting.treeId] = setting; //For some older browser,(e.g., ie6) if(typeof document.body.style.maxHeight === "undefined") { setting.view.expandSpeed = ""; } data.initRoot(setting); var root = data.getRoot(setting), childKey = setting.data.key.children; zNodes = zNodes ? tools.clone(tools.isArray(zNodes)? zNodes : [zNodes]) : []; if (setting.data.simpleData.enable) { root[childKey] = data.transformTozTreeFormat(setting, zNodes); } else { root[childKey] = zNodes; } data.initCache(setting); event.unbindTree(setting); event.bindTree(setting); event.unbindEvent(setting); event.bindEvent(setting); var zTreeTools = { setting : setting, addNodes : function(parentNode, newNodes, isSilent) { if (!newNodes) return null; if (!parentNode) parentNode = null; if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; var xNewNodes = tools.clone(tools.isArray(newNodes)? newNodes: [newNodes]); function addCallback() { view.addNodes(setting, parentNode, xNewNodes, (isSilent==true)); } if (tools.canAsync(setting, parentNode)) { view.asyncNode(setting, parentNode, isSilent, addCallback); } else { addCallback(); } return xNewNodes; }, cancelSelectedNode : function(node) { view.cancelPreSelectedNode(setting, node); }, destroy : function() { view.destroy(setting); }, expandAll : function(expandFlag) { expandFlag = !!expandFlag; view.expandCollapseSonNode(setting, null, expandFlag, true); return expandFlag; }, expandNode : function(node, expandFlag, sonSign, focus, callbackFlag) { if (!node || !node.isParent) return null; if (expandFlag !== true && expandFlag !== false) { expandFlag = !node.open; } callbackFlag = !!callbackFlag; if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { return null; } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { return null; } if (expandFlag && node.parentTId) { view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, false); } if (expandFlag === node.open && !sonSign) { return null; } data.getRoot(setting).expandTriggerFlag = callbackFlag; if (!tools.canAsync(setting, node) && sonSign) { view.expandCollapseSonNode(setting, node, expandFlag, true, function() { if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} }); } else { node.open = !expandFlag; view.switchNode(this.setting, node); if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} } return expandFlag; }, getNodes : function() { return data.getNodes(setting); }, getNodeByParam : function(key, value, parentNode) { if (!key) return null; return data.getNodeByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); }, getNodeByTId : function(tId) { return data.getNodeCache(setting, tId); }, getNodesByParam : function(key, value, parentNode) { if (!key) return null; return data.getNodesByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); }, getNodesByParamFuzzy : function(key, value, parentNode) { if (!key) return null; return data.getNodesByParamFuzzy(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); }, getNodesByFilter: function(filter, isSingle, parentNode, invokeParam) { isSingle = !!isSingle; if (!filter || (typeof filter != "function")) return (isSingle ? null : []); return data.getNodesByFilter(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), filter, isSingle, invokeParam); }, getNodeIndex : function(node) { if (!node) return null; var childKey = setting.data.key.children, parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); for (var i=0, l = parentNode[childKey].length; i < l; i++) { if (parentNode[childKey][i] == node) return i; } return -1; }, getSelectedNodes : function() { var r = [], list = data.getRoot(setting).curSelectedList; for (var i=0, l=list.length; i<l; i++) { r.push(list[i]); } return r; }, isSelectedNode : function(node) { return data.isSelectedNode(setting, node); }, reAsyncChildNodes : function(parentNode, reloadType, isSilent) { if (!this.setting.async.enable) return; var isRoot = !parentNode; if (isRoot) { parentNode = data.getRoot(setting); } if (reloadType=="refresh") { var childKey = this.setting.data.key.children; for (var i = 0, l = parentNode[childKey] ? parentNode[childKey].length : 0; i < l; i++) { data.removeNodeCache(setting, parentNode[childKey][i]); } data.removeSelectedNode(setting); parentNode[childKey] = []; if (isRoot) { this.setting.treeObj.empty(); } else { var ulObj = $$(parentNode, consts.id.UL, setting); ulObj.empty(); } } view.asyncNode(this.setting, isRoot? null:parentNode, !!isSilent); }, refresh : function() { this.setting.treeObj.empty(); var root = data.getRoot(setting), nodes = root[setting.data.key.children] data.initRoot(setting); root[setting.data.key.children] = nodes data.initCache(setting); view.createNodes(setting, 0, root[setting.data.key.children]); }, removeChildNodes : function(node) { if (!node) return null; var childKey = setting.data.key.children, nodes = node[childKey]; view.removeChildNodes(setting, node); return nodes ? nodes : null; }, removeNode : function(node, callbackFlag) { if (!node) return; callbackFlag = !!callbackFlag; if (callbackFlag && tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return; view.removeNode(setting, node); if (callbackFlag) { this.setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]); } }, selectNode : function(node, addFlag) { if (!node) return; if (tools.uCanDo(setting)) { addFlag = setting.view.selectedMulti && addFlag; if (node.parentTId) { view.expandCollapseParentNode(setting, node.getParentNode(), true, false, function() { try{$$(node, setting).focus().blur();}catch(e){} }); } else { try{$$(node, setting).focus().blur();}catch(e){} } view.selectNode(setting, node, addFlag); } }, transformTozTreeNodes : function(simpleNodes) { return data.transformTozTreeFormat(setting, simpleNodes); }, transformToArray : function(nodes) { return data.transformToArrayFormat(setting, nodes); }, updateNode : function(node, checkTypeFlag) { if (!node) return; var nObj = $$(node, setting); if (nObj.get(0) && tools.uCanDo(setting)) { view.setNodeName(setting, node); view.setNodeTarget(setting, node); view.setNodeUrl(setting, node); view.setNodeLineIcos(setting, node); view.setNodeFontCss(setting, node); } } } root.treeTools = zTreeTools; data.setZTreeTools(setting, zTreeTools); if (root[childKey] && root[childKey].length > 0) { view.createNodes(setting, 0, root[childKey]); } else if (setting.async.enable && setting.async.url && setting.async.url !== '') { view.asyncNode(setting); } return zTreeTools; } }; var zt = $.fn.zTree, $$ = tools.$, consts = zt.consts; })(jQuery); /* * JQuery zTree excheck v3.5.18 * http://zTree.me/ * * Copyright (c) 2010 Hunter.z * * Licensed same as jquery - MIT License * http://www.opensource.org/licenses/mit-license.php * * email: hunter.z@263.net * Date: 2015-06-18 */ (function($){ //default consts of excheck var _consts = { event: { CHECK: "ztree_check" }, id: { CHECK: "_check" }, checkbox: { STYLE: "checkbox", DEFAULT: "chk", DISABLED: "disable", FALSE: "false", TRUE: "true", FULL: "full", PART: "part", FOCUS: "focus" }, radio: { STYLE: "radio", TYPE_ALL: "all", TYPE_LEVEL: "level" } }, //default setting of excheck _setting = { check: { enable: false, autoCheckTrigger: false, chkStyle: _consts.checkbox.STYLE, nocheckInherit: false, chkDisabledInherit: false, radioType: _consts.radio.TYPE_LEVEL, chkboxType: { "Y": "ps", "N": "ps" } }, data: { key: { checked: "checked" } }, callback: { beforeCheck:null, onCheck:null } }, //default root of excheck _initRoot = function (setting) { var r = data.getRoot(setting); r.radioCheckedList = []; }, //default cache of excheck _initCache = function(treeId) {}, //default bind event of excheck _bindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.bind(c.CHECK, function (event, srcEvent, treeId, node) { event.srcEvent = srcEvent; tools.apply(setting.callback.onCheck, [event, treeId, node]); }); }, _unbindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.unbind(c.CHECK); }, //default event proxy of excheck _eventProxy = function(e) { var target = e.target, setting = data.getSetting(e.data.treeId), tId = "", node = null, nodeEventType = "", treeEventType = "", nodeEventCallback = null, treeEventCallback = null; if (tools.eqs(e.type, "mouseover")) { if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = tools.getNodeMainDom(target).id; nodeEventType = "mouseoverCheck"; } } else if (tools.eqs(e.type, "mouseout")) { if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = tools.getNodeMainDom(target).id; nodeEventType = "mouseoutCheck"; } } else if (tools.eqs(e.type, "click")) { if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = tools.getNodeMainDom(target).id; nodeEventType = "checkNode"; } } if (tId.length>0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { case "checkNode" : nodeEventCallback = _handler.onCheckNode; break; case "mouseoverCheck" : nodeEventCallback = _handler.onMouseoverCheck; break; case "mouseoutCheck" : nodeEventCallback = _handler.onMouseoutCheck; break; } } var proxyResult = { stop: nodeEventType === "checkNode", node: node, nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, treeEventCallback: treeEventCallback }; return proxyResult }, //default init node of excheck _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { if (!n) return; var checkedKey = setting.data.key.checked; if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); n[checkedKey] = !!n[checkedKey]; n.checkedOld = n[checkedKey]; if (typeof n.nocheck == "string") n.nocheck = tools.eqs(n.nocheck, "true"); n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); if (typeof n.chkDisabled == "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); n.halfCheck = !!n.halfCheck; n.check_Child_State = -1; n.check_Focus = false; n.getCheckStatus = function() {return data.getCheckStatus(setting, n);}; if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { var r = data.getRoot(setting); r.radioCheckedList.push(n); } }, //add dom for check _beforeA = function(setting, node, html) { var checkedKey = setting.data.key.checked; if (setting.check.enable) { data.makeChkFlag(setting, node); html.push("<span ID='", node.tId, consts.id.CHECK, "' class='", view.makeChkClass(setting, node), "' treeNode", consts.id.CHECK, (node.nocheck === true?" style='display:none;'":""),"></span>"); } }, //update zTreeObj, add method of check _zTreeTools = function(setting, zTreeTools) { zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) { var checkedKey = this.setting.data.key.checked; if (node.chkDisabled === true) return; if (checked !== true && checked !== false) { checked = !node[checkedKey]; } callbackFlag = !!callbackFlag; if (node[checkedKey] === checked && !checkTypeFlag) { return; } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { return; } if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { node[checkedKey] = checked; var checkObj = $$(node, consts.id.CHECK, this.setting); if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); view.setChkClass(this.setting, checkObj, node); view.repairParentChkClassWithSelf(this.setting, node); if (callbackFlag) { this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); } } } zTreeTools.checkAllNodes = function(checked) { view.repairAllChk(this.setting, !!checked); } zTreeTools.getCheckedNodes = function(checked) { var childKey = this.setting.data.key.children; checked = (checked !== false); return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); } zTreeTools.getChangeCheckedNodes = function() { var childKey = this.setting.data.key.children; return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); } zTreeTools.setChkDisabled = function(node, disabled, inheritParent, inheritChildren) { disabled = !!disabled; inheritParent = !!inheritParent; inheritChildren = !!inheritChildren; view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); } var _updateNode = zTreeTools.updateNode; zTreeTools.updateNode = function(node, checkTypeFlag) { if (_updateNode) _updateNode.apply(zTreeTools, arguments); if (!node || !this.setting.check.enable) return; var nObj = $$(node, this.setting); if (nObj.get(0) && tools.uCanDo(this.setting)) { var checkObj = $$(node, consts.id.CHECK, this.setting); if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); view.setChkClass(this.setting, checkObj, node); view.repairParentChkClassWithSelf(this.setting, node); } } }, //method of operate data _data = { getRadioCheckedList: function(setting) { var checkedList = data.getRoot(setting).radioCheckedList; for (var i=0, j=checkedList.length; i<j; i++) { if(!data.getNodeCache(setting, checkedList[i].tId)) { checkedList.splice(i, 1); i--; j--; } } return checkedList; }, getCheckStatus: function(setting, node) { if (!setting.check.enable || node.nocheck || node.chkDisabled) return null; var checkedKey = setting.data.key.checked, r = { checked: node[checkedKey], half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) }; return r; }, getTreeCheckedNodes: function(setting, nodes, checked, results) { if (!nodes) return []; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); results = !results ? [] : results; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { results.push(nodes[i]); if(onlyOne) { break; } } data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); if(onlyOne && results.length > 0) { break; } } return results; }, getTreeChangeCheckedNodes: function(setting, nodes, results) { if (!nodes) return []; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked; results = !results ? [] : results; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { results.push(nodes[i]); } data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); } return results; }, makeChkFlag: function(setting, node) { if (!node) return; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, chkFlag = -1; if (node[childKey]) { for (var i = 0, l = node[childKey].length; i < l; i++) { var cNode = node[childKey][i]; var tmp = -1; if (setting.check.chkStyle == consts.radio.STYLE) { if (cNode.nocheck === true || cNode.chkDisabled === true) { tmp = cNode.check_Child_State; } else if (cNode.halfCheck === true) { tmp = 2; } else if (cNode[checkedKey]) { tmp = 2; } else { tmp = cNode.check_Child_State > 0 ? 2:0; } if (tmp == 2) { chkFlag = 2; break; } else if (tmp == 0){ chkFlag = 0; } } else if (setting.check.chkStyle == consts.checkbox.STYLE) { if (cNode.nocheck === true || cNode.chkDisabled === true) { tmp = cNode.check_Child_State; } else if (cNode.halfCheck === true) { tmp = 1; } else if (cNode[checkedKey] ) { tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; } else { tmp = (cNode.check_Child_State > 0) ? 1 : 0; } if (tmp === 1) { chkFlag = 1; break; } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { chkFlag = 1; break; } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { chkFlag = 1; break; } else if (tmp > -1) { chkFlag = tmp; } } } } node.check_Child_State = chkFlag; } }, //method of event proxy _event = { }, //method of event handler _handler = { onCheckNode: function (event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkedKey = setting.data.key.checked; if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; node[checkedKey] = !node[checkedKey]; view.checkNodeRelation(setting, node); var checkObj = $$(node, consts.id.CHECK, setting); view.setChkClass(setting, checkObj, node); view.repairParentChkClassWithSelf(setting, node); setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); return true; }, onMouseoverCheck: function(event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkObj = $$(node, consts.id.CHECK, setting); node.check_Focus = true; view.setChkClass(setting, checkObj, node); return true; }, onMouseoutCheck: function(event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkObj = $$(node, consts.id.CHECK, setting); node.check_Focus = false; view.setChkClass(setting, checkObj, node); return true; } }, //method of tools for zTree _tools = { }, //method of operate ztree dom _view = { checkNodeRelation: function(setting, node) { var pNode, i, l, childKey = setting.data.key.children, checkedKey = setting.data.key.checked, r = consts.radio; if (setting.check.chkStyle == r.STYLE) { var checkedList = data.getRadioCheckedList(setting); if (node[checkedKey]) { if (setting.check.radioType == r.TYPE_ALL) { for (i = checkedList.length-1; i >= 0; i--) { pNode = checkedList[i]; if (pNode[checkedKey] && pNode != node) { pNode[checkedKey] = false; checkedList.splice(i, 1); view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); if (pNode.parentTId != node.parentTId) { view.repairParentChkClassWithSelf(setting, pNode); } } } checkedList.push(node); } else { var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); for (i = 0, l = parentNode[childKey].length; i < l; i++) { pNode = parentNode[childKey][i]; if (pNode[checkedKey] && pNode != node) { pNode[checkedKey] = false; view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); } } } } else if (setting.check.radioType == r.TYPE_ALL) { for (i = 0, l = checkedList.length; i < l; i++) { if (node == checkedList[i]) { checkedList.splice(i, 1); break; } } } } else { if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { view.setSonNodeCheckBox(setting, node, true); } if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) { view.setSonNodeCheckBox(setting, node, false); } if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { view.setParentNodeCheckBox(setting, node, true); } if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { view.setParentNodeCheckBox(setting, node, false); } } }, makeChkClass: function(setting, node) { var checkedKey = setting.data.key.checked, c = consts.checkbox, r = consts.radio, fullStyle = ""; if (node.chkDisabled === true) { fullStyle = c.DISABLED; } else if (node.halfCheck) { fullStyle = c.PART; } else if (setting.check.chkStyle == r.STYLE) { fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART; } else { fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL:c.PART) : ((node.check_Child_State < 1)? c.FULL:c.PART); } var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; return consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; }, repairAllChk: function(setting, checked) { if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { var checkedKey = setting.data.key.checked, childKey = setting.data.key.children, root = data.getRoot(setting); for (var i = 0, l = root[childKey].length; i<l ; i++) { var node = root[childKey][i]; if (node.nocheck !== true && node.chkDisabled !== true) { node[checkedKey] = checked; } view.setSonNodeCheckBox(setting, node, checked); } } }, repairChkClass: function(setting, node) { if (!node) return; data.makeChkFlag(setting, node); if (node.nocheck !== true) { var checkObj = $$(node, consts.id.CHECK, setting); view.setChkClass(setting, checkObj, node); } }, repairParentChkClass: function(setting, node) { if (!node || !node.parentTId) return; var pNode = node.getParentNode(); view.repairChkClass(setting, pNode); view.repairParentChkClass(setting, pNode); }, repairParentChkClassWithSelf: function(setting, node) { if (!node) return; var childKey = setting.data.key.children; if (node[childKey] && node[childKey].length > 0) { view.repairParentChkClass(setting, node[childKey][0]); } else { view.repairParentChkClass(setting, node); } }, repairSonChkDisabled: function(setting, node, chkDisabled, inherit) { if (!node) return; var childKey = setting.data.key.children; if (node.chkDisabled != chkDisabled) { node.chkDisabled = chkDisabled; } view.repairChkClass(setting, node); if (node[childKey] && inherit) { for (var i = 0, l = node[childKey].length; i < l; i++) { var sNode = node[childKey][i]; view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); } } }, repairParentChkDisabled: function(setting, node, chkDisabled, inherit) { if (!node) return; if (node.chkDisabled != chkDisabled && inherit) { node.chkDisabled = chkDisabled; } view.repairChkClass(setting, node); view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); }, setChkClass: function(setting, obj, node) { if (!obj) return; if (node.nocheck === true) { obj.hide(); } else { obj.show(); } obj.attr('class', view.makeChkClass(setting, node)); }, setParentNodeCheckBox: function(setting, node, value, srcNode) { var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, checkObj = $$(node, consts.id.CHECK, setting); if (!srcNode) srcNode = node; data.makeChkFlag(setting, node); if (node.nocheck !== true && node.chkDisabled !== true) { node[checkedKey] = value; view.setChkClass(setting, checkObj, node); if (setting.check.autoCheckTrigger && node != srcNode) { setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); } } if (node.parentTId) { var pSign = true; if (!value) { var pNodes = node.getParentNode()[childKey]; for (var i = 0, l = pNodes.length; i < l; i++) { if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) || ((pNodes[i].nocheck === true || pNodes[i].chkDisabled === true) && pNodes[i].check_Child_State > 0)) { pSign = false; break; } } } if (pSign) { view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); } } }, setSonNodeCheckBox: function(setting, node, value, srcNode) { if (!node) return; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, checkObj = $$(node, consts.id.CHECK, setting); if (!srcNode) srcNode = node; var hasDisable = false; if (node[childKey]) { for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { var sNode = node[childKey][i]; view.setSonNodeCheckBox(setting, sNode, value, srcNode); if (sNode.chkDisabled === true) hasDisable = true; } } if (node != data.getRoot(setting) && node.chkDisabled !== true) { if (hasDisable && node.nocheck !== true) { data.makeChkFlag(setting, node); } if (node.nocheck !== true && node.chkDisabled !== true) { node[checkedKey] = value; if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; } else { node.check_Child_State = -1; } view.setChkClass(setting, checkObj, node); if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); } } } }, _z = { tools: _tools, view: _view, event: _event, data: _data }; $.extend(true, $.fn.zTree.consts, _consts); $.extend(true, $.fn.zTree._z, _z); var zt = $.fn.zTree, tools = zt._z.tools, consts = zt.consts, view = zt._z.view, data = zt._z.data, event = zt._z.event, $$ = tools.$; data.exSetting(_setting); data.addInitBind(_bindEvent); data.addInitUnBind(_unbindEvent); data.addInitCache(_initCache); data.addInitNode(_initNode); data.addInitProxy(_eventProxy, true); data.addInitRoot(_initRoot); data.addBeforeA(_beforeA); data.addZTreeTools(_zTreeTools); var _createNodes = view.createNodes; view.createNodes = function(setting, level, nodes, parentNode) { if (_createNodes) _createNodes.apply(view, arguments); if (!nodes) return; view.repairParentChkClassWithSelf(setting, parentNode); } var _removeNode = view.removeNode; view.removeNode = function(setting, node) { var parentNode = node.getParentNode(); if (_removeNode) _removeNode.apply(view, arguments); if (!node || !parentNode) return; view.repairChkClass(setting, parentNode); view.repairParentChkClass(setting, parentNode); } var _appendNodes = view.appendNodes; view.appendNodes = function(setting, level, nodes, parentNode, initFlag, openFlag) { var html = ""; if (_appendNodes) { html = _appendNodes.apply(view, arguments); } if (parentNode) { data.makeChkFlag(setting, parentNode); } return html; } })(jQuery); /* * JQuery zTree exedit v3.5.18 * http://zTree.me/ * * Copyright (c) 2010 Hunter.z * * Licensed same as jquery - MIT License * http://www.opensource.org/licenses/mit-license.php * * email: hunter.z@263.net * Date: 2015-06-18 */ (function($){ //default consts of exedit var _consts = { event: { DRAG: "ztree_drag", DROP: "ztree_drop", RENAME: "ztree_rename", DRAGMOVE:"ztree_dragmove" }, id: { EDIT: "_edit", INPUT: "_input", REMOVE: "_remove" }, move: { TYPE_INNER: "inner", TYPE_PREV: "prev", TYPE_NEXT: "next" }, node: { CURSELECTED_EDIT: "curSelectedNode_Edit", TMPTARGET_TREE: "tmpTargetzTree", TMPTARGET_NODE: "tmpTargetNode" } }, //default setting of exedit _setting = { edit: { enable: false, editNameSelectAll: false, showRemoveBtn: true, showRenameBtn: true, removeTitle: "remove", renameTitle: "rename", drag: { autoExpandTrigger: false, isCopy: true, isMove: true, prev: true, next: true, inner: true, minMoveSize: 5, borderMax: 10, borderMin: -5, maxShowNodeNum: 5, autoOpenTime: 500 } }, view: { addHoverDom: null, removeHoverDom: null }, callback: { beforeDrag:null, beforeDragOpen:null, beforeDrop:null, beforeEditName:null, beforeRename:null, onDrag:null, onDragMove:null, onDrop:null, onRename:null } }, //default root of exedit _initRoot = function (setting) { var r = data.getRoot(setting), rs = data.getRoots(); r.curEditNode = null; r.curEditInput = null; r.curHoverNode = null; r.dragFlag = 0; r.dragNodeShowBefore = []; r.dragMaskList = new Array(); rs.showHoverDom = true; }, //default cache of exedit _initCache = function(treeId) {}, //default bind event of exedit _bindEvent = function(setting) { var o = setting.treeObj; var c = consts.event; o.bind(c.RENAME, function (event, treeId, treeNode, isCancel) { tools.apply(setting.callback.onRename, [event, treeId, treeNode, isCancel]); }); o.bind(c.DRAG, function (event, srcEvent, treeId, treeNodes) { tools.apply(setting.callback.onDrag, [srcEvent, treeId, treeNodes]); }); o.bind(c.DRAGMOVE,function(event, srcEvent, treeId, treeNodes){ tools.apply(setting.callback.onDragMove,[srcEvent, treeId, treeNodes]); }); o.bind(c.DROP, function (event, srcEvent, treeId, treeNodes, targetNode, moveType, isCopy) { tools.apply(setting.callback.onDrop, [srcEvent, treeId, treeNodes, targetNode, moveType, isCopy]); }); }, _unbindEvent = function(setting) { var o = setting.treeObj; var c = consts.event; o.unbind(c.RENAME); o.unbind(c.DRAG); o.unbind(c.DRAGMOVE); o.unbind(c.DROP); }, //default event proxy of exedit _eventProxy = function(e) { var target = e.target, setting = data.getSetting(e.data.treeId), relatedTarget = e.relatedTarget, tId = "", node = null, nodeEventType = "", treeEventType = "", nodeEventCallback = null, treeEventCallback = null, tmp = null; if (tools.eqs(e.type, "mouseover")) { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tools.getNodeMainDom(tmp).id; nodeEventType = "hoverOverNode"; } } else if (tools.eqs(e.type, "mouseout")) { tmp = tools.getMDom(setting, relatedTarget, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (!tmp) { tId = "remove"; nodeEventType = "hoverOutNode"; } } else if (tools.eqs(e.type, "mousedown")) { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tools.getNodeMainDom(tmp).id; nodeEventType = "mousedownNode"; } } if (tId.length>0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { case "mousedownNode" : nodeEventCallback = _handler.onMousedownNode; break; case "hoverOverNode" : nodeEventCallback = _handler.onHoverOverNode; break; case "hoverOutNode" : nodeEventCallback = _handler.onHoverOutNode; break; } } var proxyResult = { stop: false, node: node, nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, treeEventCallback: treeEventCallback }; return proxyResult }, //default init node of exedit _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { if (!n) return; n.isHover = false; n.editNameFlag = false; }, //update zTreeObj, add method of edit _zTreeTools = function(setting, zTreeTools) { zTreeTools.cancelEditName = function(newName) { var root = data.getRoot(this.setting); if (!root.curEditNode) return; view.cancelCurEditNode(this.setting, newName?newName:null, true); } zTreeTools.copyNode = function(targetNode, node, moveType, isSilent) { if (!node) return null; if (targetNode && !targetNode.isParent && this.setting.data.keep.leaf && moveType === consts.move.TYPE_INNER) return null; var _this = this, newNode = tools.clone(node); if (!targetNode) { targetNode = null; moveType = consts.move.TYPE_INNER; } if (moveType == consts.move.TYPE_INNER) { function copyCallback() { view.addNodes(_this.setting, targetNode, [newNode], isSilent); } if (tools.canAsync(this.setting, targetNode)) { view.asyncNode(this.setting, targetNode, isSilent, copyCallback); } else { copyCallback(); } } else { view.addNodes(this.setting, targetNode.parentNode, [newNode], isSilent); view.moveNode(this.setting, targetNode, newNode, moveType, false, isSilent); } return newNode; } zTreeTools.editName = function(node) { if (!node || !node.tId || node !== data.getNodeCache(this.setting, node.tId)) return; if (node.parentTId) view.expandCollapseParentNode(this.setting, node.getParentNode(), true); view.editNode(this.setting, node) } zTreeTools.moveNode = function(targetNode, node, moveType, isSilent) { if (!node) return node; if (targetNode && !targetNode.isParent && this.setting.data.keep.leaf && moveType === consts.move.TYPE_INNER) { return null; } else if (targetNode && ((node.parentTId == targetNode.tId && moveType == consts.move.TYPE_INNER) || $$(node, this.setting).find("#" + targetNode.tId).length > 0)) { return null; } else if (!targetNode) { targetNode = null; } var _this = this; function moveCallback() { view.moveNode(_this.setting, targetNode, node, moveType, false, isSilent); } if (tools.canAsync(this.setting, targetNode) && moveType === consts.move.TYPE_INNER) { view.asyncNode(this.setting, targetNode, isSilent, moveCallback); } else { moveCallback(); } return node; } zTreeTools.setEditable = function(editable) { this.setting.edit.enable = editable; return this.refresh(); } }, //method of operate data _data = { setSonNodeLevel: function(setting, parentNode, node) { if (!node) return; var childKey = setting.data.key.children; node.level = (parentNode)? parentNode.level + 1 : 0; if (!node[childKey]) return; for (var i = 0, l = node[childKey].length; i < l; i++) { if (node[childKey][i]) data.setSonNodeLevel(setting, node, node[childKey][i]); } } }, //method of event proxy _event = { }, //method of event handler _handler = { onHoverOverNode: function(event, node) { var setting = data.getSetting(event.data.treeId), root = data.getRoot(setting); if (root.curHoverNode != node) { _handler.onHoverOutNode(event); } root.curHoverNode = node; view.addHoverDom(setting, node); }, onHoverOutNode: function(event, node) { var setting = data.getSetting(event.data.treeId), root = data.getRoot(setting); if (root.curHoverNode && !data.isSelectedNode(setting, root.curHoverNode)) { view.removeTreeDom(setting, root.curHoverNode); root.curHoverNode = null; } }, onMousedownNode: function(eventMouseDown, _node) { var i,l, setting = data.getSetting(eventMouseDown.data.treeId), root = data.getRoot(setting), roots = data.getRoots(); //right click can't drag & drop if (eventMouseDown.button == 2 || !setting.edit.enable || (!setting.edit.drag.isCopy && !setting.edit.drag.isMove)) return true; //input of edit node name can't drag & drop var target = eventMouseDown.target, _nodes = data.getRoot(setting).curSelectedList, nodes = []; if (!data.isSelectedNode(setting, _node)) { nodes = [_node]; } else { for (i=0, l=_nodes.length; i<l; i++) { if (_nodes[i].editNameFlag && tools.eqs(target.tagName, "input") && target.getAttribute("treeNode"+consts.id.INPUT) !== null) { return true; } nodes.push(_nodes[i]); if (nodes[0].parentTId !== _nodes[i].parentTId) { nodes = [_node]; break; } } } view.editNodeBlur = true; view.cancelCurEditNode(setting); var doc = $(setting.treeObj.get(0).ownerDocument), body = $(setting.treeObj.get(0).ownerDocument.body), curNode, tmpArrow, tmpTarget, isOtherTree = false, targetSetting = setting, sourceSetting = setting, preNode, nextNode, preTmpTargetNodeId = null, preTmpMoveType = null, tmpTargetNodeId = null, moveType = consts.move.TYPE_INNER, mouseDownX = eventMouseDown.clientX, mouseDownY = eventMouseDown.clientY, startTime = (new Date()).getTime(); if (tools.uCanDo(setting)) { doc.bind("mousemove", _docMouseMove); } function _docMouseMove(event) { //avoid start drag after click node if (root.dragFlag == 0 && Math.abs(mouseDownX - event.clientX) < setting.edit.drag.minMoveSize && Math.abs(mouseDownY - event.clientY) < setting.edit.drag.minMoveSize) { return true; } var i, l, tmpNode, tmpDom, tmpNodes, childKey = setting.data.key.children; body.css("cursor", "pointer"); if (root.dragFlag == 0) { if (tools.apply(setting.callback.beforeDrag, [setting.treeId, nodes], true) == false) { _docMouseUp(event); return true; } for (i=0, l=nodes.length; i<l; i++) { if (i==0) { root.dragNodeShowBefore = []; } tmpNode = nodes[i]; if (tmpNode.isParent && tmpNode.open) { view.expandCollapseNode(setting, tmpNode, !tmpNode.open); root.dragNodeShowBefore[tmpNode.tId] = true; } else { root.dragNodeShowBefore[tmpNode.tId] = false; } } root.dragFlag = 1; roots.showHoverDom = false; tools.showIfameMask(setting, true); //sort var isOrder = true, lastIndex = -1; if (nodes.length>1) { var pNodes = nodes[0].parentTId ? nodes[0].getParentNode()[childKey] : data.getNodes(setting); tmpNodes = []; for (i=0, l=pNodes.length; i<l; i++) { if (root.dragNodeShowBefore[pNodes[i].tId] !== undefined) { if (isOrder && lastIndex > -1 && (lastIndex+1) !== i) { isOrder = false; } tmpNodes.push(pNodes[i]); lastIndex = i; } if (nodes.length === tmpNodes.length) { nodes = tmpNodes; break; } } } if (isOrder) { preNode = nodes[0].getPreNode(); nextNode = nodes[nodes.length-1].getNextNode(); } //set node in selected curNode = $$("<ul class='zTreeDragUL'></ul>", setting); for (i=0, l=nodes.length; i<l; i++) { tmpNode = nodes[i]; tmpNode.editNameFlag = false; view.selectNode(setting, tmpNode, i>0); view.removeTreeDom(setting, tmpNode); if (i > setting.edit.drag.maxShowNodeNum-1) { continue; } tmpDom = $$("<li id='"+ tmpNode.tId +"_tmp'></li>", setting); tmpDom.append($$(tmpNode, consts.id.A, setting).clone()); tmpDom.css("padding", "0"); tmpDom.children("#" + tmpNode.tId + consts.id.A).removeClass(consts.node.CURSELECTED); curNode.append(tmpDom); if (i == setting.edit.drag.maxShowNodeNum-1) { tmpDom = $$("<li id='"+ tmpNode.tId +"_moretmp'><a> ... </a></li>", setting); curNode.append(tmpDom); } } curNode.attr("id", nodes[0].tId + consts.id.UL + "_tmp"); curNode.addClass(setting.treeObj.attr("class")); curNode.appendTo(body); tmpArrow = $$("<span class='tmpzTreeMove_arrow'></span>", setting); tmpArrow.attr("id", "zTreeMove_arrow_tmp"); tmpArrow.appendTo(body); setting.treeObj.trigger(consts.event.DRAG, [event, setting.treeId, nodes]); } if (root.dragFlag == 1) { if (tmpTarget && tmpArrow.attr("id") == event.target.id && tmpTargetNodeId && (event.clientX + doc.scrollLeft()+2) > ($("#" + tmpTargetNodeId + consts.id.A, tmpTarget).offset().left)) { var xT = $("#" + tmpTargetNodeId + consts.id.A, tmpTarget); event.target = (xT.length > 0) ? xT.get(0) : event.target; } else if (tmpTarget) { tmpTarget.removeClass(consts.node.TMPTARGET_TREE); if (tmpTargetNodeId) $("#" + tmpTargetNodeId + consts.id.A, tmpTarget).removeClass(consts.node.TMPTARGET_NODE + "_" + consts.move.TYPE_PREV) .removeClass(consts.node.TMPTARGET_NODE + "_" + _consts.move.TYPE_NEXT).removeClass(consts.node.TMPTARGET_NODE + "_" + _consts.move.TYPE_INNER); } tmpTarget = null; tmpTargetNodeId = null; //judge drag & drop in multi ztree isOtherTree = false; targetSetting = setting; var settings = data.getSettings(); for (var s in settings) { if (settings[s].treeId && settings[s].edit.enable && settings[s].treeId != setting.treeId && (event.target.id == settings[s].treeId || $(event.target).parents("#" + settings[s].treeId).length>0)) { isOtherTree = true; targetSetting = settings[s]; } } var docScrollTop = doc.scrollTop(), docScrollLeft = doc.scrollLeft(), treeOffset = targetSetting.treeObj.offset(), scrollHeight = targetSetting.treeObj.get(0).scrollHeight, scrollWidth = targetSetting.treeObj.get(0).scrollWidth, dTop = (event.clientY + docScrollTop - treeOffset.top), dBottom = (targetSetting.treeObj.height() + treeOffset.top - event.clientY - docScrollTop), dLeft = (event.clientX + docScrollLeft - treeOffset.left), dRight = (targetSetting.treeObj.width() + treeOffset.left - event.clientX - docScrollLeft), isTop = (dTop < setting.edit.drag.borderMax && dTop > setting.edit.drag.borderMin), isBottom = (dBottom < setting.edit.drag.borderMax && dBottom > setting.edit.drag.borderMin), isLeft = (dLeft < setting.edit.drag.borderMax && dLeft > setting.edit.drag.borderMin), isRight = (dRight < setting.edit.drag.borderMax && dRight > setting.edit.drag.borderMin), isTreeInner = dTop > setting.edit.drag.borderMin && dBottom > setting.edit.drag.borderMin && dLeft > setting.edit.drag.borderMin && dRight > setting.edit.drag.borderMin, isTreeTop = (isTop && targetSetting.treeObj.scrollTop() <= 0), isTreeBottom = (isBottom && (targetSetting.treeObj.scrollTop() + targetSetting.treeObj.height()+10) >= scrollHeight), isTreeLeft = (isLeft && targetSetting.treeObj.scrollLeft() <= 0), isTreeRight = (isRight && (targetSetting.treeObj.scrollLeft() + targetSetting.treeObj.width()+10) >= scrollWidth); if (event.target && tools.isChildOrSelf(event.target, targetSetting.treeId)) { //get node <li> dom var targetObj = event.target; while (targetObj && targetObj.tagName && !tools.eqs(targetObj.tagName, "li") && targetObj.id != targetSetting.treeId) { targetObj = targetObj.parentNode; } var canMove = true; //don't move to self or children of self for (i=0, l=nodes.length; i<l; i++) { tmpNode = nodes[i]; if (targetObj.id === tmpNode.tId) { canMove = false; break; } else if ($$(tmpNode, setting).find("#" + targetObj.id).length > 0) { canMove = false; break; } } if (canMove && event.target && tools.isChildOrSelf(event.target, targetObj.id + consts.id.A)) { tmpTarget = $(targetObj); tmpTargetNodeId = targetObj.id; } } //the mouse must be in zTree tmpNode = nodes[0]; if (isTreeInner && tools.isChildOrSelf(event.target, targetSetting.treeId)) { //judge mouse move in root of ztree if (!tmpTarget && (event.target.id == targetSetting.treeId || isTreeTop || isTreeBottom || isTreeLeft || isTreeRight) && (isOtherTree || (!isOtherTree && tmpNode.parentTId))) { tmpTarget = targetSetting.treeObj; } //auto scroll top if (isTop) { targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()-10); } else if (isBottom) { targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()+10); } if (isLeft) { targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()-10); } else if (isRight) { targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+10); } //auto scroll left if (tmpTarget && tmpTarget != targetSetting.treeObj && tmpTarget.offset().left < targetSetting.treeObj.offset().left) { targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+ tmpTarget.offset().left - targetSetting.treeObj.offset().left); } } curNode.css({ "top": (event.clientY + docScrollTop + 3) + "px", "left": (event.clientX + docScrollLeft + 3) + "px" }); var dX = 0; var dY = 0; if (tmpTarget && tmpTarget.attr("id")!=targetSetting.treeId) { var tmpTargetNode = tmpTargetNodeId == null ? null: data.getNodeCache(targetSetting, tmpTargetNodeId), isCopy = ((event.ctrlKey || event.metaKey) && setting.edit.drag.isMove && setting.edit.drag.isCopy) || (!setting.edit.drag.isMove && setting.edit.drag.isCopy), isPrev = !!(preNode && tmpTargetNodeId === preNode.tId), isNext = !!(nextNode && tmpTargetNodeId === nextNode.tId), isInner = (tmpNode.parentTId && tmpNode.parentTId == tmpTargetNodeId), canPrev = (isCopy || !isNext) && tools.apply(targetSetting.edit.drag.prev, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.prev), canNext = (isCopy || !isPrev) && tools.apply(targetSetting.edit.drag.next, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.next), canInner = (isCopy || !isInner) && !(targetSetting.data.keep.leaf && !tmpTargetNode.isParent) && tools.apply(targetSetting.edit.drag.inner, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.inner); if (!canPrev && !canNext && !canInner) { tmpTarget = null; tmpTargetNodeId = ""; moveType = consts.move.TYPE_INNER; tmpArrow.css({ "display":"none" }); if (window.zTreeMoveTimer) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null } } else { var tmpTargetA = $("#" + tmpTargetNodeId + consts.id.A, tmpTarget), tmpNextA = tmpTargetNode.isLastNode ? null : $("#" + tmpTargetNode.getNextNode().tId + consts.id.A, tmpTarget.next()), tmpTop = tmpTargetA.offset().top, tmpLeft = tmpTargetA.offset().left, prevPercent = canPrev ? (canInner ? 0.25 : (canNext ? 0.5 : 1) ) : -1, nextPercent = canNext ? (canInner ? 0.75 : (canPrev ? 0.5 : 0) ) : -1, dY_percent = (event.clientY + docScrollTop - tmpTop)/tmpTargetA.height(); if ((prevPercent==1 ||dY_percent<=prevPercent && dY_percent>=-.2) && canPrev) { dX = 1 - tmpArrow.width(); dY = tmpTop - tmpArrow.height()/2; moveType = consts.move.TYPE_PREV; } else if ((nextPercent==0 || dY_percent>=nextPercent && dY_percent<=1.2) && canNext) { dX = 1 - tmpArrow.width(); dY = (tmpNextA == null || (tmpTargetNode.isParent && tmpTargetNode.open)) ? (tmpTop + tmpTargetA.height() - tmpArrow.height()/2) : (tmpNextA.offset().top - tmpArrow.height()/2); moveType = consts.move.TYPE_NEXT; }else { dX = 5 - tmpArrow.width(); dY = tmpTop; moveType = consts.move.TYPE_INNER; } tmpArrow.css({ "display":"block", "top": dY + "px", "left": (tmpLeft + dX) + "px" }); tmpTargetA.addClass(consts.node.TMPTARGET_NODE + "_" + moveType); if (preTmpTargetNodeId != tmpTargetNodeId || preTmpMoveType != moveType) { startTime = (new Date()).getTime(); } if (tmpTargetNode && tmpTargetNode.isParent && moveType == consts.move.TYPE_INNER) { var startTimer = true; if (window.zTreeMoveTimer && window.zTreeMoveTargetNodeTId !== tmpTargetNode.tId) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null; }else if (window.zTreeMoveTimer && window.zTreeMoveTargetNodeTId === tmpTargetNode.tId) { startTimer = false; } if (startTimer) { window.zTreeMoveTimer = setTimeout(function() { if (moveType != consts.move.TYPE_INNER) return; if (tmpTargetNode && tmpTargetNode.isParent && !tmpTargetNode.open && (new Date()).getTime() - startTime > targetSetting.edit.drag.autoOpenTime && tools.apply(targetSetting.callback.beforeDragOpen, [targetSetting.treeId, tmpTargetNode], true)) { view.switchNode(targetSetting, tmpTargetNode); if (targetSetting.edit.drag.autoExpandTrigger) { targetSetting.treeObj.trigger(consts.event.EXPAND, [targetSetting.treeId, tmpTargetNode]); } } }, targetSetting.edit.drag.autoOpenTime+50); window.zTreeMoveTargetNodeTId = tmpTargetNode.tId; } } } } else { moveType = consts.move.TYPE_INNER; if (tmpTarget && tools.apply(targetSetting.edit.drag.inner, [targetSetting.treeId, nodes, null], !!targetSetting.edit.drag.inner)) { tmpTarget.addClass(consts.node.TMPTARGET_TREE); } else { tmpTarget = null; } tmpArrow.css({ "display":"none" }); if (window.zTreeMoveTimer) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null; } } preTmpTargetNodeId = tmpTargetNodeId; preTmpMoveType = moveType; setting.treeObj.trigger(consts.event.DRAGMOVE, [event, setting.treeId, nodes]); } return false; } doc.bind("mouseup", _docMouseUp); function _docMouseUp(event) { if (window.zTreeMoveTimer) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null; } preTmpTargetNodeId = null; preTmpMoveType = null; doc.unbind("mousemove", _docMouseMove); doc.unbind("mouseup", _docMouseUp); doc.unbind("selectstart", _docSelect); body.css("cursor", "auto"); if (tmpTarget) { tmpTarget.removeClass(consts.node.TMPTARGET_TREE); if (tmpTargetNodeId) $("#" + tmpTargetNodeId + consts.id.A, tmpTarget).removeClass(consts.node.TMPTARGET_NODE + "_" + consts.move.TYPE_PREV) .removeClass(consts.node.TMPTARGET_NODE + "_" + _consts.move.TYPE_NEXT).removeClass(consts.node.TMPTARGET_NODE + "_" + _consts.move.TYPE_INNER); } tools.showIfameMask(setting, false); roots.showHoverDom = true; if (root.dragFlag == 0) return; root.dragFlag = 0; var i, l, tmpNode; for (i=0, l=nodes.length; i<l; i++) { tmpNode = nodes[i]; if (tmpNode.isParent && root.dragNodeShowBefore[tmpNode.tId] && !tmpNode.open) { view.expandCollapseNode(setting, tmpNode, !tmpNode.open); delete root.dragNodeShowBefore[tmpNode.tId]; } } if (curNode) curNode.remove(); if (tmpArrow) tmpArrow.remove(); var isCopy = ((event.ctrlKey || event.metaKey) && setting.edit.drag.isMove && setting.edit.drag.isCopy) || (!setting.edit.drag.isMove && setting.edit.drag.isCopy); if (!isCopy && tmpTarget && tmpTargetNodeId && nodes[0].parentTId && tmpTargetNodeId==nodes[0].parentTId && moveType == consts.move.TYPE_INNER) { tmpTarget = null; } if (tmpTarget) { var dragTargetNode = tmpTargetNodeId == null ? null: data.getNodeCache(targetSetting, tmpTargetNodeId); if (tools.apply(setting.callback.beforeDrop, [targetSetting.treeId, nodes, dragTargetNode, moveType, isCopy], true) == false) { view.selectNodes(sourceSetting, nodes); return; } var newNodes = isCopy ? tools.clone(nodes) : nodes; function dropCallback() { if (isOtherTree) { if (!isCopy) { for(var i=0, l=nodes.length; i<l; i++) { view.removeNode(setting, nodes[i]); } } if (moveType == consts.move.TYPE_INNER) { view.addNodes(targetSetting, dragTargetNode, newNodes); } else { view.addNodes(targetSetting, dragTargetNode.getParentNode(), newNodes); if (moveType == consts.move.TYPE_PREV) { for (i=0, l=newNodes.length; i<l; i++) { view.moveNode(targetSetting, dragTargetNode, newNodes[i], moveType, false); } } else { for (i=-1, l=newNodes.length-1; i<l; l--) { view.moveNode(targetSetting, dragTargetNode, newNodes[l], moveType, false); } } } } else { if (isCopy && moveType == consts.move.TYPE_INNER) { view.addNodes(targetSetting, dragTargetNode, newNodes); } else { if (isCopy) { view.addNodes(targetSetting, dragTargetNode.getParentNode(), newNodes); } if (moveType != consts.move.TYPE_NEXT) { for (i=0, l=newNodes.length; i<l; i++) { view.moveNode(targetSetting, dragTargetNode, newNodes[i], moveType, false); } } else { for (i=-1, l=newNodes.length-1; i<l; l--) { view.moveNode(targetSetting, dragTargetNode, newNodes[l], moveType, false); } } } } view.selectNodes(targetSetting, newNodes); $$(newNodes[0], setting).focus().blur(); setting.treeObj.trigger(consts.event.DROP, [event, targetSetting.treeId, newNodes, dragTargetNode, moveType, isCopy]); } if (moveType == consts.move.TYPE_INNER && tools.canAsync(targetSetting, dragTargetNode)) { view.asyncNode(targetSetting, dragTargetNode, false, dropCallback); } else { dropCallback(); } } else { view.selectNodes(sourceSetting, nodes); setting.treeObj.trigger(consts.event.DROP, [event, setting.treeId, nodes, null, null, null]); } } doc.bind("selectstart", _docSelect); function _docSelect() { return false; } //Avoid FireFox's Bug //If zTree Div CSS set 'overflow', so drag node outside of zTree, and event.target is error. if(eventMouseDown.preventDefault) { eventMouseDown.preventDefault(); } return true; } }, //method of tools for zTree _tools = { getAbs: function (obj) { var oRect = obj.getBoundingClientRect(), scrollTop = document.body.scrollTop+document.documentElement.scrollTop, scrollLeft = document.body.scrollLeft+document.documentElement.scrollLeft; return [oRect.left+scrollLeft,oRect.top+scrollTop]; }, inputFocus: function(inputObj) { if (inputObj.get(0)) { inputObj.focus(); tools.setCursorPosition(inputObj.get(0), inputObj.val().length); } }, inputSelect: function(inputObj) { if (inputObj.get(0)) { inputObj.focus(); inputObj.select(); } }, setCursorPosition: function(obj, pos){ if(obj.setSelectionRange) { obj.focus(); obj.setSelectionRange(pos,pos); } else if (obj.createTextRange) { var range = obj.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, showIfameMask: function(setting, showSign) { var root = data.getRoot(setting); //clear full mask while (root.dragMaskList.length > 0) { root.dragMaskList[0].remove(); root.dragMaskList.shift(); } if (showSign) { //show mask var iframeList = $$("iframe", setting); for (var i = 0, l = iframeList.length; i < l; i++) { var obj = iframeList.get(i), r = tools.getAbs(obj), dragMask = $$("<div id='zTreeMask_" + i + "' class='zTreeMask' style='top:" + r[1] + "px; left:" + r[0] + "px; width:" + obj.offsetWidth + "px; height:" + obj.offsetHeight + "px;'></div>", setting); dragMask.appendTo($$("body", setting)); root.dragMaskList.push(dragMask); } } } }, //method of operate ztree dom _view = { addEditBtn: function(setting, node) { if (node.editNameFlag || $$(node, consts.id.EDIT, setting).length > 0) { return; } if (!tools.apply(setting.edit.showRenameBtn, [setting.treeId, node], setting.edit.showRenameBtn)) { return; } var aObj = $$(node, consts.id.A, setting), editStr = "<span class='" + consts.className.BUTTON + " edit' id='" + node.tId + consts.id.EDIT + "' title='"+tools.apply(setting.edit.renameTitle, [setting.treeId, node], setting.edit.renameTitle)+"' treeNode"+consts.id.EDIT+" style='display:none;'></span>"; aObj.append(editStr); $$(node, consts.id.EDIT, setting).bind('click', function() { if (!tools.uCanDo(setting) || tools.apply(setting.callback.beforeEditName, [setting.treeId, node], true) == false) return false; view.editNode(setting, node); return false; } ).show(); }, addRemoveBtn: function(setting, node) { if (node.editNameFlag || $$(node, consts.id.REMOVE, setting).length > 0) { return; } if (!tools.apply(setting.edit.showRemoveBtn, [setting.treeId, node], setting.edit.showRemoveBtn)) { return; } var aObj = $$(node, consts.id.A, setting), removeStr = "<span class='" + consts.className.BUTTON + " remove' id='" + node.tId + consts.id.REMOVE + "' title='"+tools.apply(setting.edit.removeTitle, [setting.treeId, node], setting.edit.removeTitle)+"' treeNode"+consts.id.REMOVE+" style='display:none;'></span>"; aObj.append(removeStr); $$(node, consts.id.REMOVE, setting).bind('click', function() { if (!tools.uCanDo(setting) || tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return false; view.removeNode(setting, node); setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]); return false; } ).bind('mousedown', function(eventMouseDown) { return true; } ).show(); }, addHoverDom: function(setting, node) { if (data.getRoots().showHoverDom) { node.isHover = true; if (setting.edit.enable) { view.addEditBtn(setting, node); view.addRemoveBtn(setting, node); } tools.apply(setting.view.addHoverDom, [setting.treeId, node]); } }, cancelCurEditNode: function (setting, forceName, isCancel) { var root = data.getRoot(setting), nameKey = setting.data.key.name, node = root.curEditNode; if (node) { var inputObj = root.curEditInput, newName = forceName ? forceName:(isCancel ? node[nameKey]: inputObj.val()); if (tools.apply(setting.callback.beforeRename, [setting.treeId, node, newName, isCancel], true) === false) { return false; } node[nameKey] = newName; var aObj = $$(node, consts.id.A, setting); aObj.removeClass(consts.node.CURSELECTED_EDIT); inputObj.unbind(); view.setNodeName(setting, node); node.editNameFlag = false; root.curEditNode = null; root.curEditInput = null; view.selectNode(setting, node, false); setting.treeObj.trigger(consts.event.RENAME, [setting.treeId, node, isCancel]); } root.noSelection = true; return true; }, editNode: function(setting, node) { var root = data.getRoot(setting); view.editNodeBlur = false; if (data.isSelectedNode(setting, node) && root.curEditNode == node && node.editNameFlag) { setTimeout(function() {tools.inputFocus(root.curEditInput);}, 0); return; } var nameKey = setting.data.key.name; node.editNameFlag = true; view.removeTreeDom(setting, node); view.cancelCurEditNode(setting); view.selectNode(setting, node, false); $$(node, consts.id.SPAN, setting).html("<input type=text class='rename' id='" + node.tId + consts.id.INPUT + "' treeNode" + consts.id.INPUT + " >"); var inputObj = $$(node, consts.id.INPUT, setting); inputObj.attr("value", node[nameKey]); if (setting.edit.editNameSelectAll) { tools.inputSelect(inputObj); } else { tools.inputFocus(inputObj); } inputObj.bind('blur', function(event) { if (!view.editNodeBlur) { view.cancelCurEditNode(setting); } }).bind('keydown', function(event) { if (event.keyCode=="13") { view.editNodeBlur = true; view.cancelCurEditNode(setting); } else if (event.keyCode=="27") { view.cancelCurEditNode(setting, null, true); } }).bind('click', function(event) { return false; }).bind('dblclick', function(event) { return false; }); $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED_EDIT); root.curEditInput = inputObj; root.noSelection = false; root.curEditNode = node; }, moveNode: function(setting, targetNode, node, moveType, animateFlag, isSilent) { var root = data.getRoot(setting), childKey = setting.data.key.children; if (targetNode == node) return; if (setting.data.keep.leaf && targetNode && !targetNode.isParent && moveType == consts.move.TYPE_INNER) return; var oldParentNode = (node.parentTId ? node.getParentNode(): root), targetNodeIsRoot = (targetNode === null || targetNode == root); if (targetNodeIsRoot && targetNode === null) targetNode = root; if (targetNodeIsRoot) moveType = consts.move.TYPE_INNER; var targetParentNode = (targetNode.parentTId ? targetNode.getParentNode() : root); if (moveType != consts.move.TYPE_PREV && moveType != consts.move.TYPE_NEXT) { moveType = consts.move.TYPE_INNER; } if (moveType == consts.move.TYPE_INNER) { if (targetNodeIsRoot) { //parentTId of root node is null node.parentTId = null; } else { if (!targetNode.isParent) { targetNode.isParent = true; targetNode.open = !!targetNode.open; view.setNodeLineIcos(setting, targetNode); } node.parentTId = targetNode.tId; } } //move node Dom var targetObj, target_ulObj; if (targetNodeIsRoot) { targetObj = setting.treeObj; target_ulObj = targetObj; } else { if (!isSilent && moveType == consts.move.TYPE_INNER) { view.expandCollapseNode(setting, targetNode, true, false); } else if (!isSilent) { view.expandCollapseNode(setting, targetNode.getParentNode(), true, false); } targetObj = $$(targetNode, setting); target_ulObj = $$(targetNode, consts.id.UL, setting); if (!!targetObj.get(0) && !target_ulObj.get(0)) { var ulstr = []; view.makeUlHtml(setting, targetNode, ulstr, ''); targetObj.append(ulstr.join('')); } target_ulObj = $$(targetNode, consts.id.UL, setting); } var nodeDom = $$(node, setting); if (!nodeDom.get(0)) { nodeDom = view.appendNodes(setting, node.level, [node], null, false, true).join(''); } else if (!targetObj.get(0)) { nodeDom.remove(); } if (target_ulObj.get(0) && moveType == consts.move.TYPE_INNER) { target_ulObj.append(nodeDom); } else if (targetObj.get(0) && moveType == consts.move.TYPE_PREV) { targetObj.before(nodeDom); } else if (targetObj.get(0) && moveType == consts.move.TYPE_NEXT) { targetObj.after(nodeDom); } //repair the data after move var i,l, tmpSrcIndex = -1, tmpTargetIndex = 0, oldNeighbor = null, newNeighbor = null, oldLevel = node.level; if (node.isFirstNode) { tmpSrcIndex = 0; if (oldParentNode[childKey].length > 1 ) { oldNeighbor = oldParentNode[childKey][1]; oldNeighbor.isFirstNode = true; } } else if (node.isLastNode) { tmpSrcIndex = oldParentNode[childKey].length -1; oldNeighbor = oldParentNode[childKey][tmpSrcIndex - 1]; oldNeighbor.isLastNode = true; } else { for (i = 0, l = oldParentNode[childKey].length; i < l; i++) { if (oldParentNode[childKey][i].tId == node.tId) { tmpSrcIndex = i; break; } } } if (tmpSrcIndex >= 0) { oldParentNode[childKey].splice(tmpSrcIndex, 1); } if (moveType != consts.move.TYPE_INNER) { for (i = 0, l = targetParentNode[childKey].length; i < l; i++) { if (targetParentNode[childKey][i].tId == targetNode.tId) tmpTargetIndex = i; } } if (moveType == consts.move.TYPE_INNER) { if (!targetNode[childKey]) targetNode[childKey] = new Array(); if (targetNode[childKey].length > 0) { newNeighbor = targetNode[childKey][targetNode[childKey].length - 1]; newNeighbor.isLastNode = false; } targetNode[childKey].splice(targetNode[childKey].length, 0, node); node.isLastNode = true; node.isFirstNode = (targetNode[childKey].length == 1); } else if (targetNode.isFirstNode && moveType == consts.move.TYPE_PREV) { targetParentNode[childKey].splice(tmpTargetIndex, 0, node); newNeighbor = targetNode; newNeighbor.isFirstNode = false; node.parentTId = targetNode.parentTId; node.isFirstNode = true; node.isLastNode = false; } else if (targetNode.isLastNode && moveType == consts.move.TYPE_NEXT) { targetParentNode[childKey].splice(tmpTargetIndex + 1, 0, node); newNeighbor = targetNode; newNeighbor.isLastNode = false; node.parentTId = targetNode.parentTId; node.isFirstNode = false; node.isLastNode = true; } else { if (moveType == consts.move.TYPE_PREV) { targetParentNode[childKey].splice(tmpTargetIndex, 0, node); } else { targetParentNode[childKey].splice(tmpTargetIndex + 1, 0, node); } node.parentTId = targetNode.parentTId; node.isFirstNode = false; node.isLastNode = false; } data.fixPIdKeyValue(setting, node); data.setSonNodeLevel(setting, node.getParentNode(), node); //repair node what been moved view.setNodeLineIcos(setting, node); view.repairNodeLevelClass(setting, node, oldLevel) //repair node's old parentNode dom if (!setting.data.keep.parent && oldParentNode[childKey].length < 1) { //old parentNode has no child nodes oldParentNode.isParent = false; oldParentNode.open = false; var tmp_ulObj = $$(oldParentNode, consts.id.UL, setting), tmp_switchObj = $$(oldParentNode, consts.id.SWITCH, setting), tmp_icoObj = $$(oldParentNode, consts.id.ICON, setting); view.replaceSwitchClass(oldParentNode, tmp_switchObj, consts.folder.DOCU); view.replaceIcoClass(oldParentNode, tmp_icoObj, consts.folder.DOCU); tmp_ulObj.css("display", "none"); } else if (oldNeighbor) { //old neigbor node view.setNodeLineIcos(setting, oldNeighbor); } //new neigbor node if (newNeighbor) { view.setNodeLineIcos(setting, newNeighbor); } //repair checkbox / radio if (!!setting.check && setting.check.enable && view.repairChkClass) { view.repairChkClass(setting, oldParentNode); view.repairParentChkClassWithSelf(setting, oldParentNode); if (oldParentNode != node.parent) view.repairParentChkClassWithSelf(setting, node); } //expand parents after move if (!isSilent) { view.expandCollapseParentNode(setting, node.getParentNode(), true, animateFlag); } }, removeEditBtn: function(setting, node) { $$(node, consts.id.EDIT, setting).unbind().remove(); }, removeRemoveBtn: function(setting, node) { $$(node, consts.id.REMOVE, setting).unbind().remove(); }, removeTreeDom: function(setting, node) { node.isHover = false; view.removeEditBtn(setting, node); view.removeRemoveBtn(setting, node); tools.apply(setting.view.removeHoverDom, [setting.treeId, node]); }, repairNodeLevelClass: function(setting, node, oldLevel) { if (oldLevel === node.level) return; var liObj = $$(node, setting), aObj = $$(node, consts.id.A, setting), ulObj = $$(node, consts.id.UL, setting), oldClass = consts.className.LEVEL + oldLevel, newClass = consts.className.LEVEL + node.level; liObj.removeClass(oldClass); liObj.addClass(newClass); aObj.removeClass(oldClass); aObj.addClass(newClass); ulObj.removeClass(oldClass); ulObj.addClass(newClass); }, selectNodes : function(setting, nodes) { for (var i=0, l=nodes.length; i<l; i++) { view.selectNode(setting, nodes[i], i>0); } } }, _z = { tools: _tools, view: _view, event: _event, data: _data }; $.extend(true, $.fn.zTree.consts, _consts); $.extend(true, $.fn.zTree._z, _z); var zt = $.fn.zTree, tools = zt._z.tools, consts = zt.consts, view = zt._z.view, data = zt._z.data, event = zt._z.event, $$ = tools.$; data.exSetting(_setting); data.addInitBind(_bindEvent); data.addInitUnBind(_unbindEvent); data.addInitCache(_initCache); data.addInitNode(_initNode); data.addInitProxy(_eventProxy); data.addInitRoot(_initRoot); data.addZTreeTools(_zTreeTools); var _cancelPreSelectedNode = view.cancelPreSelectedNode; view.cancelPreSelectedNode = function (setting, node) { var list = data.getRoot(setting).curSelectedList; for (var i=0, j=list.length; i<j; i++) { if (!node || node === list[i]) { view.removeTreeDom(setting, list[i]); if (node) break; } } if (_cancelPreSelectedNode) _cancelPreSelectedNode.apply(view, arguments); } var _createNodes = view.createNodes; view.createNodes = function(setting, level, nodes, parentNode) { if (_createNodes) { _createNodes.apply(view, arguments); } if (!nodes) return; if (view.repairParentChkClassWithSelf) { view.repairParentChkClassWithSelf(setting, parentNode); } } var _makeNodeUrl = view.makeNodeUrl; view.makeNodeUrl = function(setting, node) { return setting.edit.enable ? null : (_makeNodeUrl.apply(view, arguments)); } var _removeNode = view.removeNode; view.removeNode = function(setting, node) { var root = data.getRoot(setting); if (root.curEditNode === node) root.curEditNode = null; if (_removeNode) { _removeNode.apply(view, arguments); } } var _selectNode = view.selectNode; view.selectNode = function(setting, node, addFlag) { $('#'+setting.treeId+' a').removeClass('focusNode'); $('#'+node.tId+'_a').addClass('focusNode'); var root = data.getRoot(setting); if (data.isSelectedNode(setting, node) && root.curEditNode == node && node.editNameFlag) { return false; } if (_selectNode) _selectNode.apply(view, arguments); view.addHoverDom(setting, node); return true; } var _uCanDo = tools.uCanDo; tools.uCanDo = function(setting, e) { var root = data.getRoot(setting); if (e && (tools.eqs(e.type, "mouseover") || tools.eqs(e.type, "mouseout") || tools.eqs(e.type, "mousedown") || tools.eqs(e.type, "mouseup"))) { return true; } if (root.curEditNode) { view.editNodeBlur = false; root.curEditInput.focus(); } return (!root.curEditNode) && (_uCanDo ? _uCanDo.apply(view, arguments) : true); } })(jQuery);
{ "content_hash": "bcb26061534abb951c3b1dd4d0a3f05f", "timestamp": "", "source": "github", "line_count": 3576, "max_line_length": 270, "avg_line_length": 34.22175615212528, "alnum_prop": 0.6399241687572012, "repo_name": "iuap-design/iuap-design.github.io", "id": "3f7a2d698ffb2b9e11079ee11f19f7d031531f9f", "size": "122457", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/vendor/uui/js/u-tree.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19509" }, { "name": "HTML", "bytes": "91209" }, { "name": "JavaScript", "bytes": "99264" }, { "name": "Shell", "bytes": "1720" } ], "symlink_target": "" }
layout: page title: About permalink: about/ --- ## About
{ "content_hash": "d9b358afadbbad9f5b1d1d21cf180bdc", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 17, "avg_line_length": 11.4, "alnum_prop": 0.6842105263157895, "repo_name": "shakna-israel/shaknaisrael_2015", "id": "5edb23074ffa5354ca39326c7300c21222ccc26e", "size": "61", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25936" }, { "name": "HTML", "bytes": "26303" }, { "name": "JavaScript", "bytes": "2445" } ], "symlink_target": "" }
namespace blink { // EditingState represents current editing command running state for propagating // DOM tree mutation operation failure to callers. // // Example usage: // EditingState editingState; // ... // functionMutatesDOMTree(..., &editingState); // if (editingState.isAborted()) // return; // class EditingState final { STACK_ALLOCATED(); WTF_MAKE_NONCOPYABLE(EditingState); public: EditingState(); ~EditingState(); void abort(); bool isAborted() const { return m_isAborted; } private: bool m_isAborted = false; }; // TODO(yosin): Once all commands aware |EditingState|, we get rid of // |IgnorableEditingAbortState | class class IgnorableEditingAbortState final { STACK_ALLOCATED(); WTF_MAKE_NONCOPYABLE(IgnorableEditingAbortState); public: IgnorableEditingAbortState(); ~IgnorableEditingAbortState(); EditingState* editingState() { return &m_editingState; } private: EditingState m_editingState; }; // Abort the editing command if the specified expression is true. #define ABORT_EDITING_COMMAND_IF(expr) \ do { \ if (expr) { \ editingState->abort(); \ return; \ } \ } while (false) #if DCHECK_IS_ON() // This class is inspired by |NoExceptionStateAssertionChecker|. class NoEditingAbortChecker final { STACK_ALLOCATED(); WTF_MAKE_NONCOPYABLE(NoEditingAbortChecker); public: NoEditingAbortChecker(const char* file, int line); ~NoEditingAbortChecker(); EditingState* editingState() { return &m_editingState; } private: EditingState m_editingState; const char* const m_file; int const m_line; }; // If a function with EditingState* argument should not be aborted, // ASSERT_NO_EDITING_ABORT should be specified. // fooFunc(...., ASSERT_NO_EDITING_ABORT); // It causes an assertion failure If DCHECK_IS_ON() and the function was aborted // unexpectedly. #define ASSERT_NO_EDITING_ABORT \ (NoEditingAbortChecker(__FILE__, __LINE__).editingState()) #else #define ASSERT_NO_EDITING_ABORT (IgnorableEditingAbortState().editingState()) #endif } // namespace blink #endif // EditingState_h
{ "content_hash": "3076907a32a3ee003122a9f078e80b5a", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 80, "avg_line_length": 26.404761904761905, "alnum_prop": 0.6794409377817854, "repo_name": "ssaroha/node-webrtc", "id": "608408df5ad0895e0118257ce50bb614bf3d242f", "size": "2516", "binary": false, "copies": "5", "ref": "refs/heads/develop", "path": "third_party/webrtc/include/chromium/src/third_party/WebKit/Source/core/editing/commands/EditingState.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "6179" }, { "name": "C", "bytes": "2679" }, { "name": "C++", "bytes": "54327" }, { "name": "HTML", "bytes": "434" }, { "name": "JavaScript", "bytes": "42707" }, { "name": "Python", "bytes": "3835" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <doc> <assembly> <name>SharpGit</name> </assembly> <members> <member name="M:SharpGit.GitTools.PathCombine(System.String,System.String)"> <summary>Long path capable version of <see cref="M:System.IO.Path.Combine(System.String,System.String)" /></summary> </member> <member name="M:SharpGit.GitTools.GetNormalizedDirectoryName(System.String)"> <summary>Gets the normalized directory name of path (Long path enabled version of <see cref="M:System.IO.Path.GetDirectoryName(System.String)" />, always returning full paths)</summary> <returns>Directory information for path, or null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information.</returns> </member> <member name="M:SharpGit.GitTools.IsAbsolutePath(System.String)"> <summary> Checks whether the specified path is an absolute path that doesn't end in an unneeded '\' </summary> </member> <member name="M:SharpGit.GitTools.IsNormalizedFullPath(System.String)"> <summary> Checks whether normalization is required </summary> <remarks>This method does not verify the casing of invariant parts</remarks> </member> <member name="M:SharpGit.GitTools.GetNormalizedFullPath(System.String)"> <summary> Normalizes the path to a full path </summary> <summary>This normalizes drive letters to upper case and hostnames to lowercase to match Subversion 1.6 behavior</summary> </member> <member name="M:SharpGit.GitTools.IsBelowManagedPath(System.String)"> <summary>Gets a boolean indicating whether at least one of the parent paths or the path (file/directory) itself is a working copy. </summary> </member> <member name="M:SharpGit.GitTools.IsManagedPath(System.String)"> <summary>Gets a boolean indicating whether the path could contain a Subversion Working Copy</summary> <remarks>Assumes path is a directory</remarks> </member> <member name="M:SharpGit.GitTools.GetTruePath(System.String,System.Boolean)"> <summary>Gets the absolute pathname exactly like it is on disk (fixing casing). For not existing paths, if bestEffort is TRUE, returns a path based on existing parents. Otherwise return NULL for not existing paths</summary> </member> <member name="M:SharpGit.GitTools.GetTruePath(System.String)"> <summary>Gets the absolute pathname exactly like it is on disk (fixing casing); returns NULL for non existing paths</summary> </member> <member name="P:SharpGit.GitMergeAnalysis.IsUnborn"> <summary> The HEAD of the current repository is "unborn" and does not point to a valid commit. No merge can be performed, but the caller may wish to simply set HEAD to the target commit(s). </summary> </member> <member name="P:SharpGit.GitMergeAnalysis.CanFastForward"> <summary> The given merge input is a fast-forward from HEAD and no merge needs to be performed. Instead, the client can check out the given merge input. </summary> </member> <member name="P:SharpGit.GitMergeAnalysis.IsUpToDate"> <summary> All given merge inputs are reachable from HEAD, meaning the repository is up-to-date and no merge needs to be performed. </summary> </member> <member name="P:SharpGit.GitMergeAnalysis.CanMergeNormal"> <summary> A "normal" merge; both HEAD and the given merge input have diverged from their common ancestor. The divergent commits must be merged. </summary> </member> <member name="T:SharpGit.GitCheckOutConflictStrategy"> <summary> Enum specifying what content checkout should write to disk for conflicts. </summary> <threadsafety static="true" instance="false" /> </member> <member name="F:SharpGit.GitCheckOutConflictStrategy.Diff3"> <summary> Write diff3 formated files for conflicts. </summary> </member> <member name="F:SharpGit.GitCheckOutConflictStrategy.Merge"> <summary> Write normal merge files for conflicts. </summary> </member> <member name="F:SharpGit.GitCheckOutConflictStrategy.UseTheirs"> <summary> For conflicting files, checkout the "theirs" (stage 3) version of the file from the index. </summary> </member> <member name="F:SharpGit.GitCheckOutConflictStrategy.UseOurs"> <summary> For conflicting files, checkout the "ours" (stage 2) version of the file from the index. </summary> </member> <member name="F:SharpGit.GitCheckOutConflictStrategy.Default"> <summary> Use the default behavior for handling file conflicts. This is controlled by the merge.conflictstyle config option, and is "Merge" if no option is explicitly set. </summary> </member> <member name="M:SharpGit.Plumbing.GitBranch.RecordAsHeadBranch(SharpGit.GitClientArgs)"> <summary>Marks this branch as the currently checked out HEAD branch</summary> </member> <member name="P:SharpGit.Plumbing.GitCommit.AncestorsAndSelf"> <summary>Get an enumerator over this nodes ancestors, starting by this node itself</summary> </member> <member name="P:SharpGit.Plumbing.GitCommit.Ancestors"> <summary>Get an enumerator over this nodes ancestors, starting by the parent of this commit</summary> </member> <member name="P:SharpGit.Plumbing.GitCommit.Ancestor"> <summary>Get the first ancestor/first parent of this commit</summary> </member> <member name="P:SharpGit.GitException.Error"> <summary>Gets the raw subversion error code</summary> </member> <member name="F:SharpGit.Plumbing.GitObjectKind.DeltaOffset"> <summary>GIT_OBJ_OFS_DELTA</summary> </member> <member name="F:SharpGit.Plumbing.GitObjectKind.Ext5"> <summary>Reserved</summary> </member> <member name="F:SharpGit.Plumbing.GitObjectKind.Ext0"> <summary>Reserved</summary> </member> <member name="F:SharpGit.Plumbing.GitObjectKind.Bad"> <summary>Object is invalid</summary> </member> <member name="F:SharpGit.Plumbing.GitObjectKind.Any"> <summary>Object can be any of the following</summary> </member> <member name="P:SharpGit.Plumbing.GitIndexEntry.Id"> <summary>Id of blob</summary> </member> <member name="T:SharpGit.Plumbing.GitIndexStage"> <summary>Disambiguates the different versions of an index entry during a merge.</summary> <threadsafety static="true" instance="false" /> </member> <member name="F:SharpGit.Plumbing.GitIndexStage.Theirs"> <summary>Version of the entry as it is in the commit being merged.</summary> </member> <member name="F:SharpGit.Plumbing.GitIndexStage.Ours"> <summary>Version of the entry as it is in the commit of the Head.</summary> </member> <member name="F:SharpGit.Plumbing.GitIndexStage.Ancestor"> <summary>Version of the entry as it was in the common base merge commit.</summary> </member> <member name="F:SharpGit.Plumbing.GitIndexStage.Normal"> <summary>The standard fully merged state for an index entry.</summary> </member> <member name="P:SharpGit.GitStatusArgs.GenerateVersionedDirs"> <summary>Generates reports for versioned directories</summary> </member> <member name="P:SharpGit.Plumbing.GitRemote.DefaultBranch"> <summary>When connected: Provides the default branch</summary> </member> <member name="M:SharpGit.Plumbing.GitRepository.CleanupState(SharpGit.GitArgs)"> <summary>Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc.</summary> </member> <member name="M:SharpGit.Plumbing.GitRepository.CleanupState"> <summary>Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc.</summary> </member> <member name="M:SharpGit.Plumbing.GitRepository.Open(System.String)"> <summary>Opens the repository at REPOSITORYPATH</summary> </member> <member name="M:SharpGit.Plumbing.GitRepository.Locate(System.String)"> <summary>Opens the repository containing PATH</summary> </member> <member name="M:SharpGit.Plumbing.GitRepository.#ctor(System.String)"> <summary>Creates an unopened repository and then calls Open(REPOSITORYPATH)</summary> </member> <member name="M:SharpGit.Plumbing.GitRepository.#ctor"> <summary>Creates an unopened repository</summary> </member> <member name="P:SharpGit.GitClient.SharpGitVersion"> <summary>Gets the SharpGit version</summary> </member> <member name="P:SharpGit.GitClient.Version"> <summary>Gets the libgit2 version</summary> </member> <member name="M:SharpGit.GitClient.Add(System.String,SharpGit.GitStageArgs)"> <summary>Alias for .Stage()</summary> </member> <member name="M:SharpGit.GitClient.Add(System.String)"> <summary>Alias for .Stage()</summary> </member> <member name="T:SharpGit.GitClient"> <summary>Git client instance; main entrance to the SharpGit Client api</summary> <threadsafety static="true" instance="false" /> </member> <member name="P:SharpGit.GitSignature.EmailAddress"> <summary>The email address. When using for commit preparation NULL represents the configured value</summary> </member> <member name="P:SharpGit.GitSignature.Name"> <summary>The user name. When using for commit preparation NULL represents the configured value</summary> </member> <member name="P:SharpGit.GitSignature.When"> <summary>When the signature was added (as/auto-converted as GMT DateTime)</summary> </member> </members> </doc>
{ "content_hash": "c64353c27b0cc1148d35a1d9d8fe538a", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 191, "avg_line_length": 46.34134615384615, "alnum_prop": 0.7205104263927793, "repo_name": "balkrishnajha/angular-phonecat", "id": "dafab4550f72b6e479fd104a13d9f39cc1509e43", "size": "9639", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Bin/SharpGit.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "362" }, { "name": "CSS", "bytes": "2907" }, { "name": "HTML", "bytes": "4622" }, { "name": "JavaScript", "bytes": "14692" }, { "name": "Shell", "bytes": "5093" } ], "symlink_target": "" }
package cn.gridx.scala.slick.mysql import scala.slick.jdbc.GetResult import scala.slick.session.Database import scala.slick.session.Database.threadLocalSession import scala.slick.jdbc.StaticQuery._ /** * Created by tao on 4/8/16. */ object SqlQuery { def db: Database = { val url = "jdbc:mysql://gridxmysql.cywgostu0so4.us-west-1.rds.amazonaws.com/pge_prod?user=demo&password=RE3u6pc8ZYx1c&connectTimeout=60000&socketTimeout=60000" Database.forURL(url, driver = "com.mysql.jdbc.Driver") } def main(args: Array[String]): Unit = { implicit val getCustomerResult = GetResult(r => Customer(r.<<, r.<<, r.<<, r.<<)) val id = "0000021395" val list: List[Customer] = db withSession { val q = sql"""select __pk_customerattribute, contract_id,attribute_id, attribute_value from customerattribute where contract_id = $id""" val ret = q.as[Customer] // 需要一个implicit session -> import scala.slick.session.Database.threadLocalSession ret.list } println(list.mkString("[", ",", "]")) } } case class Customer(__pk_customerattribute: Int, contract_id: String, attribute_id: Int, attribute_value: String)
{ "content_hash": "158c61897861b3847ce6bb52744842a9", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 163, "avg_line_length": 31.435897435897434, "alnum_prop": 0.664763458401305, "repo_name": "TaoXiao/Scala", "id": "a3b9a218c0d3136065f4caf15ecd7bb2668efe4f", "size": "1234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "slick/src/main/scala/cn/gridx/scala/slick/mysql/SqlQuery.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "25891" }, { "name": "Scala", "bytes": "230759" }, { "name": "Shell", "bytes": "607" } ], "symlink_target": "" }
package com.microsoft.azure.management.network.v2019_11_01; import com.microsoft.azure.arm.collection.SupportsCreating; import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup; import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion; import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup; import rx.Observable; import com.microsoft.azure.arm.resources.collection.SupportsListingByResourceGroup; import com.microsoft.azure.arm.collection.SupportsListing; import com.microsoft.azure.management.network.v2019_11_01.implementation.VpnGatewaysInner; import com.microsoft.azure.arm.model.HasInner; /** * Type representing VpnGateways. */ public interface VpnGateways extends SupportsCreating<VpnGateway.DefinitionStages.Blank>, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup<VpnGateway>, SupportsListingByResourceGroup<VpnGateway>, SupportsListing<VpnGateway>, HasInner<VpnGatewaysInner> { /** * Resets the primary of the vpn gateway in the specified resource group. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<VpnGateway> resetAsync(String resourceGroupName, String gatewayName); }
{ "content_hash": "8834fed4689906a4a97651464d95d41c", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 291, "avg_line_length": 49.89655172413793, "alnum_prop": 0.8196268140981341, "repo_name": "selvasingh/azure-sdk-for-java", "id": "dd7a3e594bfc0e94091952c1063d8283cf0db858", "size": "1677", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/VpnGateways.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
import logging from django.core.management.base import BaseCommand from contentcuration.utils.import_tools import import_channel logging.basicConfig() logger = logging.getLogger('command') class Command(BaseCommand): def add_arguments(self, parser): # ID of channel to read data from parser.add_argument('source_id', type=str) # ID of channel to write data to (can be same as source channel) parser.add_argument('--target', help='restore channel db to TARGET CHANNEL ID') parser.add_argument('--download-url', help='where to download db from') parser.add_argument('--editor', help='add user as editor to channel') def handle(self, *args, **options): # Set up variables for restoration process logger.info("\n\n********** STARTING CHANNEL RESTORATION **********") source_id = options['source_id'] target_id = options.get('target') or source_id download_url = options.get('download_url') editor = options.get('editor') import_channel(source_id, target_id, download_url, editor, logger=logger)
{ "content_hash": "2d6fde6be6b7d2aede749a30447080f0", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 87, "avg_line_length": 37.06666666666667, "alnum_prop": 0.6672661870503597, "repo_name": "DXCanas/content-curation", "id": "4088232c4b91f8dc6ed28f2202c11c2fd680dd98", "size": "1112", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "contentcuration/contentcuration/management/commands/restore_channel.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "173955" }, { "name": "Dockerfile", "bytes": "2215" }, { "name": "HTML", "bytes": "503467" }, { "name": "JavaScript", "bytes": "601189" }, { "name": "Makefile", "bytes": "3409" }, { "name": "Python", "bytes": "813881" }, { "name": "Shell", "bytes": "6970" }, { "name": "Smarty", "bytes": "6584" }, { "name": "Vue", "bytes": "21539" } ], "symlink_target": "" }
package openpgp import ( "code.google.com/p/go.crypto/openpgp/armor" "code.google.com/p/go.crypto/openpgp/errors" "code.google.com/p/go.crypto/openpgp/packet" "crypto" _ "crypto/sha256" "hash" "io" "strconv" ) // SignatureType is the armor type for a PGP signature. var SignatureType = "PGP SIGNATURE" // readArmored reads an armored block with the given type. func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { block, err := armor.Decode(r) if err != nil { return } if block.Type != expectedType { return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) } return block.Body, nil } // MessageDetails contains the result of parsing an OpenPGP encrypted and/or // signed message. type MessageDetails struct { IsEncrypted bool // true if the message was encrypted. EncryptedToKeyIds []uint64 // the list of recipient key ids. IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message. DecryptedWith Key // the private key used to decrypt the message, if any. IsSigned bool // true if the message is signed. SignedByKeyId uint64 // the key id of the signer, if any. SignedBy *Key // the key of the signer, if available. LiteralData *packet.LiteralData // the metadata of the contents UnverifiedBody io.Reader // the contents of the message. // If IsSigned is true and SignedBy is non-zero then the signature will // be verified as UnverifiedBody is read. The signature cannot be // checked until the whole of UnverifiedBody is read so UnverifiedBody // must be consumed until EOF before the data can trusted. Even if a // message isn't signed (or the signer is unknown) the data may contain // an authentication code that is only checked once UnverifiedBody has // been consumed. Once EOF has been seen, the following fields are // valid. (An authentication code failure is reported as a // SignatureError error when reading from UnverifiedBody.) SignatureError error // nil if the signature is good. Signature *packet.Signature // the signature packet itself. decrypted io.ReadCloser } // A PromptFunction is used as a callback by functions that may need to decrypt // a private key, or prompt for a passphrase. It is called with a list of // acceptable, encrypted private keys and a boolean that indicates whether a // passphrase is usable. It should either decrypt a private key or return a // passphrase to try. If the decrypted private key or given passphrase isn't // correct, the function will be called again, forever. Any error returned will // be passed up. type PromptFunction func(keys []Key, symmetric bool) ([]byte, error) // A keyEnvelopePair is used to store a private key with the envelope that // contains a symmetric key, encrypted with that key. type keyEnvelopePair struct { key Key encryptedKey *packet.EncryptedKey } // ReadMessage parses an OpenPGP message that may be signed and/or encrypted. // The given KeyRing should contain both public keys (for signature // verification) and, possibly encrypted, private keys for decrypting. // If config is nil, sensible defaults will be used. func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) { var p packet.Packet var symKeys []*packet.SymmetricKeyEncrypted var pubKeys []keyEnvelopePair var se *packet.SymmetricallyEncrypted packets := packet.NewReader(r) md = new(MessageDetails) md.IsEncrypted = true // The message, if encrypted, starts with a number of packets // containing an encrypted decryption key. The decryption key is either // encrypted to a public key, or with a passphrase. This loop // collects these packets. ParsePackets: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.SymmetricKeyEncrypted: // This packet contains the decryption key encrypted with a passphrase. md.IsSymmetricallyEncrypted = true symKeys = append(symKeys, p) case *packet.EncryptedKey: // This packet contains the decryption key encrypted to a public key. md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId) switch p.Algo { case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal: break default: continue } var keys []Key if p.KeyId == 0 { keys = keyring.DecryptionKeys() } else { keys = keyring.KeysById(p.KeyId) } for _, k := range keys { pubKeys = append(pubKeys, keyEnvelopePair{k, p}) } case *packet.SymmetricallyEncrypted: se = p break ParsePackets case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: // This message isn't encrypted. if len(symKeys) != 0 || len(pubKeys) != 0 { return nil, errors.StructuralError("key material not followed by encrypted message") } packets.Unread(p) return readSignedMessage(packets, nil, keyring) } } var candidates []Key var decrypted io.ReadCloser // Now that we have the list of encrypted keys we need to decrypt at // least one of them or, if we cannot, we need to call the prompt // function so that it can decrypt a key or give us a passphrase. FindKey: for { // See if any of the keys already have a private key available candidates = candidates[:0] candidateFingerprints := make(map[string]bool) for _, pk := range pubKeys { if pk.key.PrivateKey == nil { continue } if !pk.key.PrivateKey.Encrypted { if len(pk.encryptedKey.Key) == 0 { pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) } if len(pk.encryptedKey.Key) == 0 { continue } decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key) if err != nil && err != errors.ErrKeyIncorrect { return nil, err } if decrypted != nil { md.DecryptedWith = pk.key break FindKey } } else { fpr := string(pk.key.PublicKey.Fingerprint[:]) if v := candidateFingerprints[fpr]; v { continue } candidates = append(candidates, pk.key) candidateFingerprints[fpr] = true } } if len(candidates) == 0 && len(symKeys) == 0 { return nil, errors.ErrKeyIncorrect } if prompt == nil { return nil, errors.ErrKeyIncorrect } passphrase, err := prompt(candidates, len(symKeys) != 0) if err != nil { return nil, err } // Try the symmetric passphrase first if len(symKeys) != 0 && passphrase != nil { for _, s := range symKeys { err = s.Decrypt(passphrase) if err == nil && !s.Encrypted { decrypted, err = se.Decrypt(s.CipherFunc, s.Key) if err != nil && err != errors.ErrKeyIncorrect { return nil, err } if decrypted != nil { break FindKey } } } } } md.decrypted = decrypted packets.Push(decrypted) return readSignedMessage(packets, md, keyring) } // readSignedMessage reads a possibly signed message if mdin is non-zero then // that structure is updated and returned. Otherwise a fresh MessageDetails is // used. func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) { if mdin == nil { mdin = new(MessageDetails) } md = mdin var p packet.Packet var h hash.Hash var wrappedHash hash.Hash FindLiteralData: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.Compressed: packets.Push(p.Body) case *packet.OnePassSignature: if !p.IsLast { return nil, errors.UnsupportedError("nested signatures") } h, wrappedHash, err = hashForSignature(p.Hash, p.SigType) if err != nil { md = nil return } md.IsSigned = true md.SignedByKeyId = p.KeyId keys := keyring.KeysById(p.KeyId) for i, key := range keys { if key.SelfSignature.FlagsValid && !key.SelfSignature.FlagSign { continue } md.SignedBy = &keys[i] break } case *packet.LiteralData: md.LiteralData = p break FindLiteralData } } if md.SignedBy != nil { md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md} } else if md.decrypted != nil { md.UnverifiedBody = checkReader{md} } else { md.UnverifiedBody = md.LiteralData.Body } return md, nil } // hashForSignature returns a pair of hashes that can be used to verify a // signature. The signature may specify that the contents of the signed message // should be preprocessed (i.e. to normalize line endings). Thus this function // returns two hashes. The second should be used to hash the message itself and // performs any needed preprocessing. func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { h := hashId.New() if h == nil { return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId))) } switch sigType { case packet.SigTypeBinary: return h, h, nil case packet.SigTypeText: return h, NewCanonicalTextHash(h), nil } return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) } // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF // it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger // MDC checks. type checkReader struct { md *MessageDetails } func (cr checkReader) Read(buf []byte) (n int, err error) { n, err = cr.md.LiteralData.Body.Read(buf) if err == io.EOF { mdcErr := cr.md.decrypted.Close() if mdcErr != nil { err = mdcErr } } return } // signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes // the data as it is read. When it sees an EOF from the underlying io.Reader // it parses and checks a trailing Signature packet and triggers any MDC checks. type signatureCheckReader struct { packets *packet.Reader h, wrappedHash hash.Hash md *MessageDetails } func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { n, err = scr.md.LiteralData.Body.Read(buf) scr.wrappedHash.Write(buf[:n]) if err == io.EOF { var p packet.Packet p, scr.md.SignatureError = scr.packets.Next() if scr.md.SignatureError != nil { return } var ok bool if scr.md.Signature, ok = p.(*packet.Signature); !ok { scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature") return } scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) // The SymmetricallyEncrypted packet, if any, might have an // unsigned hash of its own. In order to check this we need to // close that Reader. if scr.md.decrypted != nil { mdcErr := scr.md.decrypted.Close() if mdcErr != nil { err = mdcErr } } } return } // CheckDetachedSignature takes a signed file and a detached signature and // returns the signer if the signature is valid. If the signer isn't known, // ErrUnknownIssuer is returned. func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { p, err := packet.Read(signature) if err != nil { return } sig, ok := p.(*packet.Signature) if !ok { return nil, errors.StructuralError("non signature packet found") } if sig.IssuerKeyId == nil { return nil, errors.StructuralError("signature doesn't have an issuer") } keys := keyring.KeysById(*sig.IssuerKeyId) if len(keys) == 0 { return nil, errors.ErrUnknownIssuer } h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType) if err != nil { return } _, err = io.Copy(wrappedHash, signed) if err != nil && err != io.EOF { return } for _, key := range keys { if key.SelfSignature.FlagsValid && !key.SelfSignature.FlagSign { continue } err = key.PublicKey.VerifySignature(h, sig) if err == nil { return key.Entity, nil } } if err != nil { return } return nil, errors.ErrUnknownIssuer } // CheckArmoredDetachedSignature performs the same actions as // CheckDetachedSignature but expects the signature to be armored. func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { body, err := readArmored(signature, SignatureType) if err != nil { return } return CheckDetachedSignature(keyring, signed, body) }
{ "content_hash": "e8d533b3a9f314123d536167f05ddeae", "timestamp": "", "source": "github", "line_count": 410, "max_line_length": 126, "avg_line_length": 30.426829268292682, "alnum_prop": 0.694749498997996, "repo_name": "dizzyd/go.crypto", "id": "de0920c354e3f01afe0809f98400a2760e6aa685", "size": "12708", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "openpgp/read.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "53267" }, { "name": "C", "bytes": "5538" }, { "name": "Go", "bytes": "947377" } ], "symlink_target": "" }
<?php /* SonataAdminBundle:CRUD:batch_confirmation.html.twig */ class __TwigTemplate_59218342f0eb258e7107cc0b26183150d05b3d917d6fb76c06a95f2f19320f90 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->blocks = array( 'actions' => array($this, 'block_actions'), 'side_menu' => array($this, 'block_side_menu'), 'content' => array($this, 'block_content'), ); } protected function doGetParent(array $context) { return $this->env->resolveTemplate((isset($context["base_template"]) ? $context["base_template"] : $this->getContext($context, "base_template"))); } protected function doDisplay(array $context, array $blocks = array()) { $this->getParent($context)->display($context, array_merge($this->blocks, $blocks)); } // line 14 public function block_actions($context, array $blocks = array()) { // line 15 echo " <div class=\"sonata-actions btn-group\"> "; // line 16 $this->env->loadTemplate("SonataAdminBundle:Button:list_button.html.twig")->display($context); // line 17 echo " "; $this->env->loadTemplate("SonataAdminBundle:Button:create_button.html.twig")->display($context); // line 18 echo " </div> "; } // line 21 public function block_side_menu($context, array $blocks = array()) { echo $this->env->getExtension('knp_menu')->render($this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "sidemenu", array(0 => (isset($context["action"]) ? $context["action"] : $this->getContext($context, "action"))), "method"), array("currentClass" => "active"), "list"); } // line 23 public function block_content($context, array $blocks = array()) { // line 24 echo " <div class=\"sonata-ba-delete\"> <h1>"; // line 25 echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("title_batch_confirmation", array(), "SonataAdminBundle"), "html", null, true); echo "</h1> "; // line 27 if ($this->getAttribute((isset($context["data"]) ? $context["data"] : $this->getContext($context, "data")), "all_elements")) { // line 28 echo " "; echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("message_batch_all_confirmation", array(), "SonataAdminBundle"), "html", null, true); echo " "; } else { // line 30 echo " "; echo $this->env->getExtension('translator')->getTranslator()->transChoice("message_batch_confirmation", twig_length_filter($this->env, $this->getAttribute((isset($context["data"]) ? $context["data"] : $this->getContext($context, "data")), "idx")), array("%count%" => twig_length_filter($this->env, $this->getAttribute((isset($context["data"]) ? $context["data"] : $this->getContext($context, "data")), "idx"))), "SonataAdminBundle"); // line 31 echo " "; } // line 32 echo " <div class=\"well form-actions\"> <form action=\""; // line 34 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "generateUrl", array(0 => "batch", 1 => array("filter" => $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "filterParameters"))), "method"), "html", null, true); echo "\" method=\"POST\" > <input type=\"hidden\" name=\"confirmation\" value=\"ok\" /> <input type=\"hidden\" name=\"data\" value=\""; // line 36 echo twig_escape_filter($this->env, twig_jsonencode_filter((isset($context["data"]) ? $context["data"] : $this->getContext($context, "data"))), "html", null, true); echo "\" /> <input type=\"hidden\" name=\"_sonata_csrf_token\" value=\""; // line 37 echo twig_escape_filter($this->env, (isset($context["csrf_token"]) ? $context["csrf_token"] : $this->getContext($context, "csrf_token")), "html", null, true); echo "\" /> <div style=\"display: none\"> "; // line 40 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'rest'); echo " </div> <input type=\"submit\" class=\"btn btn-danger\" value=\""; // line 43 echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("btn_execute_batch_action", array(), "SonataAdminBundle"), "html", null, true); echo "\" /> "; // line 45 if (($this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "hasRoute", array(0 => "list"), "method") && $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "isGranted", array(0 => "LIST"), "method"))) { // line 46 echo " "; echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("delete_or", array(), "SonataAdminBundle"), "html", null, true); echo " <a class=\"btn btn-success\" href=\""; // line 48 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "generateUrl", array(0 => "list"), "method"), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("link_action_list", array(), "SonataAdminBundle"), "html", null, true); echo "</a> "; } // line 50 echo " </form> </div> </div> "; } public function getTemplateName() { return "SonataAdminBundle:CRUD:batch_confirmation.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 120 => 50, 113 => 48, 107 => 46, 105 => 45, 100 => 43, 94 => 40, 88 => 37, 84 => 36, 79 => 34, 75 => 32, 72 => 31, 69 => 30, 63 => 28, 61 => 27, 56 => 25, 53 => 24, 50 => 23, 44 => 21, 39 => 18, 36 => 17, 34 => 16, 31 => 15, 28 => 14,); } }
{ "content_hash": "87cf23187ed524a75f38c7263211aef7", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 445, "avg_line_length": 48.1, "alnum_prop": 0.5476685476685477, "repo_name": "jdelcastro/jobeet_tutorial", "id": "8636fe1f6d4faef41ca32ca14612ce727e95455c", "size": "6734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/cache/dev/twig/59/21/8342f0eb258e7107cc0b26183150d05b3d917d6fb76c06a95f2f19320f90.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21610" }, { "name": "JavaScript", "bytes": "501" }, { "name": "PHP", "bytes": "137235" } ], "symlink_target": "" }
import base64 import os from tempfile import NamedTemporaryFile from time import time from unittest.mock import patch import pytest from esteid.mobileid import MobileIdSigner from esteid.mobileid import signer as signer_module from ...exceptions import InvalidIdCode, InvalidParameter, InvalidParameters, SigningSessionDoesNotExist @pytest.fixture() def mobileidsigner(): signer = MobileIdSigner({}, initial=True) with patch.object(signer, "open_container"), patch.object(signer, "save_session_data"): yield signer @pytest.fixture() def mobileid_session_data(): with NamedTemporaryFile("wb", delete=False) as f: f.write(b"xml signature data") yield { "digest_b64": "MTIz", "temp_signature_file": f.name, "temp_container_file": "...", "session_id": "...", "timestamp": int(time()), } os.remove(f.name) @pytest.fixture() def mobileidservice(): with patch.object(signer_module, "TranslatedMobileIDService") as service_cls: yield service_cls @pytest.mark.parametrize( "data,error", [ pytest.param( None, InvalidParameters, id="No data", ), pytest.param( {}, InvalidParameters, id="Empty data", ), pytest.param( {"id_code": "asdf", "phone_number": "asdf"}, InvalidParameter, id="Invalid Phone", ), pytest.param( {"id_code": "asdf", "phone_number": "+37200000766"}, InvalidIdCode, id="Invalid ID Code", ), pytest.param( {"id_code": "60001019906", "phone_number": "+37200000766"}, None, id="ID Code and Phone OK", ), pytest.param( {"id_code": "60001019906", "phone_number": "+37200000766", "language": "EST"}, None, id="ID Code and Phone OK", ), ], ) def test_mobileidsigner_setup(data, error): signer = MobileIdSigner({}, initial=True) if error: with pytest.raises(error): signer.setup(data) else: signer.setup(data) assert signer.id_code == data["id_code"] assert signer.phone_number == data["phone_number"] assert signer.language == data.get("language", "ENG") @pytest.mark.parametrize( "data,error", [ pytest.param(None, SigningSessionDoesNotExist, id="No session data"), pytest.param({}, SigningSessionDoesNotExist, id="Empty session data"), pytest.param({"digest_b64": "asd"}, SigningSessionDoesNotExist, id="Broken session data"), pytest.param( { "digest_b64": "MTIz", "temp_signature_file": "a", "temp_container_file": "b", "session_id": "c", "timestamp": int(time()), }, None, id="Good session data", ), ], ) def test_mobileidsigner_load_session(data, error): if error: with pytest.raises(error): MobileIdSigner({MobileIdSigner._SESSION_KEY: data}) else: signer = MobileIdSigner({MobileIdSigner._SESSION_KEY: data}) assert signer.session_data.digest == b"123" assert signer.session_data.session_id == "c" def test_mobileidsigner_prepare(mobileidsigner, MID_DEMO_PHONE_EE_OK, MID_DEMO_PIN_EE_OK, mobileidservice): mobileidsigner.setup({"id_code": MID_DEMO_PIN_EE_OK, "phone_number": MID_DEMO_PHONE_EE_OK}) result = mobileidsigner.prepare(None, []) mobileidsigner.open_container.assert_called_once_with(None, []) container = mobileidsigner.open_container(...) mobileidservice.get_instance.assert_called_once() service = mobileidservice.get_instance() service.get_certificate.assert_called_once_with(MID_DEMO_PIN_EE_OK, MID_DEMO_PHONE_EE_OK) cert = service.get_certificate(...) container.prepare_signature.assert_called_once_with(cert) xml_sig = mobileidsigner.open_container().prepare_signature(...) xml_sig.signed_data.assert_called_once() service.sign.assert_called_once_with( MID_DEMO_PIN_EE_OK, MID_DEMO_PHONE_EE_OK, xml_sig.signed_data(), language=mobileidsigner.language ) sign_session = service.sign(...) mobileidsigner.save_session_data.assert_called_once_with( digest=sign_session.digest, container=container, xml_sig=xml_sig, session_id=sign_session.session_id, ) assert result["verification_code"] == sign_session.verification_code @patch.object(signer_module, "Container") @patch.object(signer_module, "XmlSignature") def test_mobileidsigner_finalize( XmlSignatureMock, ContainerMock, MID_DEMO_PHONE_EE_OK, MID_DEMO_PIN_EE_OK, mobileidservice, mobileid_session_data ): mobileidsigner = MobileIdSigner({MobileIdSigner._SESSION_KEY: mobileid_session_data}) with patch.object(mobileidsigner, "finalize_xml_signature"): result = mobileidsigner.finalize() XmlSignatureMock.assert_called_once_with(b"xml signature data") mobileidsigner.finalize_xml_signature.assert_called_once_with(XmlSignatureMock()) xml_sig = XmlSignatureMock(...) service = mobileidservice.get_instance() service.sign_status.assert_called_once_with( mobileid_session_data["session_id"], xml_sig.get_certificate_value(), base64.b64decode(mobileid_session_data["digest_b64"]), ) sign_status = service.sign_status(...) xml_sig.set_signature_value.assert_called_once_with(sign_status.signature) ContainerMock.open.assert_called_once_with(mobileid_session_data["temp_container_file"]) container = ContainerMock.open(...) assert result == container
{ "content_hash": "1f5a58f5882f1dcfac02915450231cb0", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 117, "avg_line_length": 31.87845303867403, "alnum_prop": 0.6322357019064124, "repo_name": "thorgate/django-esteid", "id": "1291f3066376407af3ee1fe20a8cd4ad96421b3e", "size": "5770", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "esteid/mobileid/tests/test_mobileidsigner.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "53642" }, { "name": "JavaScript", "bytes": "62010" }, { "name": "Makefile", "bytes": "1533" }, { "name": "Python", "bytes": "268714" } ], "symlink_target": "" }
package com.ysu.zyw.tc.openapi.fk.shiro.filter; import com.ysu.zyw.tc.components.servlet.support.TcServletUtils; import com.ysu.zyw.tc.components.servlet.support.TcXsrfTokenFilter; import com.ysu.zyw.tc.model.mw.Rc; import com.ysu.zyw.tc.model.mw.TcR; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.apache.shiro.web.util.WebUtils; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; @Slf4j public class TcFormAuthenticationFilter extends FormAuthenticationFilter { @Override protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException { if (TcServletUtils.isXmlHttpRequest(WebUtils.toHttp(request))) { TcR<?> tcR = TcR.code(Rc.UNAUTHORIZED, Rc.UNAUTHORIZED_DESCRIPTION); TcServletUtils.writeApplicationJsonResponse(WebUtils.toHttp(response), tcR); log.warn("path [{}] authc failed, redirect to login", WebUtils.toHttp(request).getRequestURI()); } else { TcXsrfTokenFilter.removeXsrfCookie(WebUtils.toHttp(response)); super.redirectToLogin(request, response); } } }
{ "content_hash": "05dcb06030f6b49e76effa8b84d7cf79", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 108, "avg_line_length": 40.733333333333334, "alnum_prop": 0.7528641571194763, "repo_name": "srarcbrsent/tc", "id": "775cba6aada1e991996b5862c1de4bed7b0f75cf", "size": "1222", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tc-openapi/src/main/java/com/ysu/zyw/tc/openapi/fk/shiro/filter/TcFormAuthenticationFilter.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2729" }, { "name": "FreeMarker", "bytes": "25024" }, { "name": "HTML", "bytes": "6565" }, { "name": "Java", "bytes": "781549" }, { "name": "JavaScript", "bytes": "24653" }, { "name": "Shell", "bytes": "47" } ], "symlink_target": "" }
const _ = require('lodash'); const fs = require("fs"); const path = require('path'); const util = require('util'); const exec = require('child_process').execFile; const PROJECTS_ROOT = "test/fixtures/sample_apps"; const shell = require('shelljs'); function getDirectories(folder){ return fs.readdirSync(folder).filter(function(file){ return fs.statSync(path.join(folder,file)).isDirectory(); } ) } function puts(error, stdout, stderr) { util.print(stdout); util.error(stderr); if (error !== null) { console.log('exec error: ' + error); } } var directories = getDirectories(path.resolve(PROJECTS_ROOT)); var exitCode = 0; _.forEach(directories, function(version) { var testExitCode = shell.exec('SAILS_VERSION='+version+' mocha test/specs').code; if (testExitCode !== 0) exitCode = testExitCode; }); shell.exit(exitCode);
{ "content_hash": "08b310dd839b48031e2524a2719b7e1f", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 85, "avg_line_length": 26.09090909090909, "alnum_prop": 0.6875725900116144, "repo_name": "sotadev/sails-migrations", "id": "9bfed8112b46044d9e5e5cd4e602479737c9f817", "size": "882", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bin/run_tests.js", "mode": "33261", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "7590" }, { "name": "JavaScript", "bytes": "17677" } ], "symlink_target": "" }
import React from "react" import { Link } from "gatsby" export default props => ( <article className={`post-card ${ props.postClass } ${props.node.frontmatter.thumbnail ? `with-image` : `no-image`}`} style={ props.node.frontmatter.thumbnail && { backgroundImage: `url(${ props.node.frontmatter.thumbnail.childImageSharp.fluid.src })`, } } > <Link to={props.node.fields.slug} className="post-card-link"> <div className="post-card-content"> <h2 className="post-card-title"> {props.node.frontmatter.title || props.node.fields.slug} </h2> </div> </Link> </article> )
{ "content_hash": "c7305c136feaa3de75dc71cdc00651da", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 71, "avg_line_length": 27.04, "alnum_prop": 0.5946745562130178, "repo_name": "formap/formap.github.io", "id": "c7e5eeee0ef36dba6e3dc5e588b3f9ab0a0c896a", "size": "676", "binary": false, "copies": "1", "ref": "refs/heads/code", "path": "src/components/postCard.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "481780" } ], "symlink_target": "" }
// // StickyHeaderFlowLayout.m // UXMaterial // // Created by Anton Bukov on 05.10.15. // Copyright © 2015 @k06a. All rights reserved. // #import "StickyHeaderFlowLayout.h" @implementation StickyHeaderFlowLayout - (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect { NSMutableArray *answer = [[super layoutAttributesForElementsInRect:rect] mutableCopy]; NSMutableIndexSet *missingSections = [NSMutableIndexSet indexSet]; for (NSUInteger idx=0; idx<[answer count]; idx++) { UXCollectionViewLayoutAttributes *layoutAttributes = answer[idx]; if (layoutAttributes.representedElementCategory == NSCollectionElementCategoryItem) { [missingSections addIndex:layoutAttributes.indexPath.section]; // remember that we need to layout header for this section } if ([layoutAttributes.representedElementKind isEqualToString:@"UXCollectionViewElementKindSectionHeader"]) { [answer removeObjectAtIndex:idx]; // remove layout of header done by our super, we will do it right later idx--; } } // layout all headers needed for the rect using self code [missingSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) { NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:idx]; UXCollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForSupplementaryViewOfKind:@"UXCollectionViewElementKindSectionHeader" atIndexPath:indexPath]; [answer addObject:layoutAttributes]; }]; return answer; } - (UXCollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UXCollectionViewLayoutAttributes *attributes = [super layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath]; if ([kind isEqualToString:@"UXCollectionViewElementKindSectionHeader"]) { UXCollectionView * const cv = self.collectionView; CGPoint const contentOffset = cv.contentOffset; CGPoint nextHeaderOrigin = CGPointMake(INFINITY, INFINITY); if (indexPath.section+1 < [cv numberOfSections]) { UXCollectionViewLayoutAttributes *nextHeaderAttributes = [super layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.section+1]]; nextHeaderOrigin = nextHeaderAttributes.frame.origin; } CGRect frame = attributes.frame; if (self.scrollDirection == /*UXCollectionViewScrollDirectionVertical*/0) { frame.origin.y = MIN(MAX(contentOffset.y, frame.origin.y), nextHeaderOrigin.y - CGRectGetHeight(frame)); } else { // UICollectionViewScrollDirectionHorizontal frame.origin.x = MIN(MAX(contentOffset.x, frame.origin.x), nextHeaderOrigin.x - CGRectGetWidth(frame)); } attributes.zIndex = 1024; attributes.frame = frame; } return attributes; } - (UXCollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UXCollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath]; return attributes; } - (UXCollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UXCollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath]; return attributes; } - (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBound { return YES; } @end
{ "content_hash": "b0a990889ec037f081987d049fa75cd7", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 200, "avg_line_length": 44.78313253012048, "alnum_prop": 0.744955609362389, "repo_name": "k06a/Mattericon", "id": "74f8e6604e438250ee9ddd0e4f1282e66dd57c7b", "size": "3718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UXMaterial/StickyHeaderFlowLayout.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "255030" }, { "name": "Ruby", "bytes": "146" } ], "symlink_target": "" }
using System; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; namespace LetThereBeLight { class LightMachine : IState { public LightMachine(ShellApp.Settings settings) { this.settings = settings; this.settings.Button.OnInterrupt += new NativeEventHandler(button_OnInterrupt); } public void Initialize() { if (State == null) { State = new NeedSystemTimeState(this); } } public void ButtonPressed() { if (State != null) { State.ButtonPressed(); } } public void Dispose() { this.settings.Button.OnInterrupt -= this.button_OnInterrupt; State = null; } public IState State { get { return currentState; } set { Debug.Print("Changing state from " + ((currentState == null) ? "null" : currentState.GetType().ToString()) + " to " + ((value == null) ? "null" : value.GetType().ToString())); if (this.currentState != null) { IState oldState = currentState; currentState = null; oldState.Dispose(); } currentState = value; if (currentState != null) { currentState.Initialize(); } } } public ShellApp.Settings Settings { get { return settings; } } private IState currentState; private ShellApp.Settings settings; private void button_OnInterrupt(uint pin, uint edge, DateTime time) { bool up = (edge == 0); if (up) { ButtonPressed(); } } } }
{ "content_hash": "4fa5dff3a1d124235e98b7cd6002ca43", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 191, "avg_line_length": 25.048780487804876, "alnum_prop": 0.43476144109055503, "repo_name": "danielrivera/NetduinoProjects", "id": "cf54886dcff0210df6f28e15a399708f084bc8a0", "size": "2685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/LetThereBeLight/StateMachine/LightMachine.cs", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "40971" } ], "symlink_target": "" }
package com.aventstack.extentreports.model.service; public interface EntityService { }
{ "content_hash": "9c2635f5ccd40f9d0550f074f80779ee", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 51, "avg_line_length": 22, "alnum_prop": 0.8295454545454546, "repo_name": "extent-framework/extentreports-java", "id": "a908c0009b9ee279d627a84b765db70f6855f62b", "size": "88", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/aventstack/extentreports/model/service/EntityService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "54712" }, { "name": "Java", "bytes": "372681" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:12 EEST 2014 --> <title>DataAdapterParameterContributorExtensionsRegistryFactory (JasperReports 5.6.0 API)</title> <meta name="date" content="2014-05-27"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DataAdapterParameterContributorExtensionsRegistryFactory (JasperReports 5.6.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DataAdapterParameterContributorExtensionsRegistryFactory.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/data/DataAdapter.html" title="interface in net.sf.jasperreports.data"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/data/DataAdapterParameterContributorFactory.html" title="class in net.sf.jasperreports.data"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/data/DataAdapterParameterContributorExtensionsRegistryFactory.html" target="_top">Frames</a></li> <li><a href="DataAdapterParameterContributorExtensionsRegistryFactory.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">net.sf.jasperreports.data</div> <h2 title="Class DataAdapterParameterContributorExtensionsRegistryFactory" class="title">Class DataAdapterParameterContributorExtensionsRegistryFactory</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>net.sf.jasperreports.data.DataAdapterParameterContributorExtensionsRegistryFactory</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../net/sf/jasperreports/extensions/ExtensionsRegistryFactory.html" title="interface in net.sf.jasperreports.extensions">ExtensionsRegistryFactory</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">DataAdapterParameterContributorExtensionsRegistryFactory</span> extends java.lang.Object implements <a href="../../../../net/sf/jasperreports/extensions/ExtensionsRegistryFactory.html" title="interface in net.sf.jasperreports.extensions">ExtensionsRegistryFactory</a></pre> <dl><dt><span class="strong">Version:</span></dt> <dd>$Id: DataAdapterParameterContributorExtensionsRegistryFactory.java 5878 2013-01-07 20:23:13Z teodord $</dd> <dt><span class="strong">Author:</span></dt> <dd>Teodor Danciu (teodord@users.sourceforge.net)</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../net/sf/jasperreports/data/DataAdapterParameterContributorExtensionsRegistryFactory.html#DataAdapterParameterContributorExtensionsRegistryFactory()">DataAdapterParameterContributorExtensionsRegistryFactory</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../net/sf/jasperreports/extensions/ExtensionsRegistry.html" title="interface in net.sf.jasperreports.extensions">ExtensionsRegistry</a></code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/data/DataAdapterParameterContributorExtensionsRegistryFactory.html#createRegistry(java.lang.String, net.sf.jasperreports.engine.JRPropertiesMap)">createRegistry</a></strong>(java.lang.String&nbsp;registryId, <a href="../../../../net/sf/jasperreports/engine/JRPropertiesMap.html" title="class in net.sf.jasperreports.engine">JRPropertiesMap</a>&nbsp;properties)</code> <div class="block">Instantiates an extensions registry.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DataAdapterParameterContributorExtensionsRegistryFactory()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DataAdapterParameterContributorExtensionsRegistryFactory</h4> <pre>public&nbsp;DataAdapterParameterContributorExtensionsRegistryFactory()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="createRegistry(java.lang.String, net.sf.jasperreports.engine.JRPropertiesMap)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>createRegistry</h4> <pre>public&nbsp;<a href="../../../../net/sf/jasperreports/extensions/ExtensionsRegistry.html" title="interface in net.sf.jasperreports.extensions">ExtensionsRegistry</a>&nbsp;createRegistry(java.lang.String&nbsp;registryId, <a href="../../../../net/sf/jasperreports/engine/JRPropertiesMap.html" title="class in net.sf.jasperreports.engine">JRPropertiesMap</a>&nbsp;properties)</pre> <div class="block"><strong>Description copied from interface:&nbsp;<code><a href="../../../../net/sf/jasperreports/extensions/ExtensionsRegistryFactory.html#createRegistry(java.lang.String, net.sf.jasperreports.engine.JRPropertiesMap)">ExtensionsRegistryFactory</a></code></strong></div> <div class="block">Instantiates an extensions registry.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../net/sf/jasperreports/extensions/ExtensionsRegistryFactory.html#createRegistry(java.lang.String, net.sf.jasperreports.engine.JRPropertiesMap)">createRegistry</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../net/sf/jasperreports/extensions/ExtensionsRegistryFactory.html" title="interface in net.sf.jasperreports.extensions">ExtensionsRegistryFactory</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>registryId</code> - the ID of the registry to instantiate. The ID can be used to identify a set of properties to be used when instantiating the registry.</dd><dd><code>properties</code> - the map of properties that can be used to configure the registry instantiation process</dd> <dt><span class="strong">Returns:</span></dt><dd>an extensions registry</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../net/sf/jasperreports/extensions/DefaultExtensionsRegistry.html#PROPERTY_REGISTRY_PREFIX"><code>DefaultExtensionsRegistry.PROPERTY_REGISTRY_PREFIX</code></a></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DataAdapterParameterContributorExtensionsRegistryFactory.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/data/DataAdapter.html" title="interface in net.sf.jasperreports.data"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/data/DataAdapterParameterContributorFactory.html" title="class in net.sf.jasperreports.data"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/data/DataAdapterParameterContributorExtensionsRegistryFactory.html" target="_top">Frames</a></li> <li><a href="DataAdapterParameterContributorExtensionsRegistryFactory.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
{ "content_hash": "c0ca4957979d5b457d9fcb8a17771519", "timestamp": "", "source": "github", "line_count": 284, "max_line_length": 407, "avg_line_length": 44.11971830985915, "alnum_prop": 0.6865921787709497, "repo_name": "phurtado1112/cnaemvc", "id": "d436d160a288aeffbf496a7894523ee8315dbe9a", "size": "12530", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/JasperReport__5.6/docs/api/net/sf/jasperreports/data/DataAdapterParameterContributorExtensionsRegistryFactory.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "112926414" }, { "name": "Java", "bytes": "532942" } ], "symlink_target": "" }
echo -n "Removing data ... " curl -s -o /dev/null -i -H "Accept: application/json; charset=UTF-8" -H "Content-Type: application/json" -X POST -d '{"statements": [{"statement": "MATCH (n) DETACH DELETE n"}]}' http://localhost:7474/db/data/transaction/commit echo "done" echo -n "Populating data ... " declare -a STATEMENTS while IFS= read -r; do STATEMENTS+=("$REPLY"); done <./data/demo.cypher CYPHER=$(echo "$(IFS=,; echo "${STATEMENTS[*]}")" | sed 's/["]/\\&/g') curl -i -H "Accept: application/json; charset=UTF-8" -H "Content-Type: application/json" -X POST -d "{\"statements\": [{\"statement\": \"CREATE ${CYPHER}\"}]}" http://localhost:7474/db/data/transaction/commit echo "done"
{ "content_hash": "712408dbd885a8bd21f00c297f61bf1f", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 227, "avg_line_length": 68.7, "alnum_prop": 0.6550218340611353, "repo_name": "glevine/spin", "id": "2d7337c7c4babea9c93a26253a82b6e6ec1f61e1", "size": "700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/demo.sh", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "2788" }, { "name": "JavaScript", "bytes": "8952" }, { "name": "Shell", "bytes": "985" } ], "symlink_target": "" }
<?php /** Index controller for the statistics module */ class RSNABranding_IndexController extends RSNABranding_AppController { public function indexAction() { } /** Login action */ public function loginAction() { $request = $this->getRequest(); $this->Form->User->uri = $request->getRequestUri(); $form = $this->Form->User->createLoginForm(); $this->view->form = $this->getFormAsArray($form); $this->disableLayout(); if ($this->_request->isPost()) { $this->disableView(); $previousUri = $this->getParam('previousuri'); if ($form->isValid($request->getPost())) { try { $notifications = array(); // initialize first in case of exception $notifications = Zend_Registry::get('notifier')->callback( 'CALLBACK_CORE_AUTHENTICATION', array('email' => $form->getValue('email'), 'password' => $form->getValue('password')) ); } catch (Zend_Exception $exc) { $this->getLogger()->crit($exc->getMessage()); } $authModule = false; foreach ($notifications as $user) { if ($user) { $userDao = $user; $authModule = true; break; } } if (!$authModule) { $userDao = $this->User->getByEmail($form->getValue('email')); if ($userDao === false) { echo JsonComponent::encode(array('status' => false, 'message' => 'Invalid email or password')); return; } } $instanceSalt = Zend_Registry::get('configGlobal')->get('password_prefix', false); // Necessary for upgrades to 3.4.1. if ($instanceSalt === false) { $instanceSalt = Zend_Registry::get('configGlobal')->password->prefix; } $currentVersion = UtilityComponent::getCurrentModuleVersion('core'); if ($currentVersion === false) { throw new Zend_Exception('Core version is undefined.'); } // We have to have this so that an admin can log in to upgrade from version < 3.2.12 to >= 3.2.12. // Version 3.2.12 introduced the new password hashing and storage system. if (!$authModule && version_compare($currentVersion, '3.2.12', '>=') ) { $passwordHash = hash( $userDao->getHashAlg(), $instanceSalt . $userDao->getSalt() . $form->getValue('password') ); $coreAuth = $this->User->hashExists($passwordHash); } elseif (!$authModule) { $passwordHash = md5($instanceSalt . $form->getValue('password')); $coreAuth = $this->User->legacyAuthenticate($userDao, $instanceSalt, $form->getValue('password')); } if ($authModule || $coreAuth) { $notifications = Zend_Registry::get('notifier')->callback( 'CALLBACK_CORE_AUTH_INTERCEPT', array('user' => $userDao) ); foreach ($notifications as $value) { if ($value['override'] && $value['response']) { echo $value['response']; return; } } if (!$authModule && version_compare($currentVersion, '3.2.12', '>=') && $userDao->getSalt() == '' ) { $passwordHash = $this->User->convertLegacyPasswordHash($userDao, $form->getValue('password')); } $remember = $form->getValue('remerberMe'); if (!$this->isTestingEnv()) { $date = new DateTime(); $interval = new DateInterval('P1M'); if (!$authModule && isset($remember) && $remember == 1) { setcookie( MIDAS_USER_COOKIE_NAME, $userDao->getKey() . '-' . $passwordHash, $date->add($interval)->getTimestamp(), '/', $request->getHttpHost(), (int)Zend_Registry::get('configGlobal')->get('cookie_secure', 1) === 1, true ); } else { setcookie( MIDAS_USER_COOKIE_NAME, null, $date->sub($interval)->getTimestamp(), '/', $request->getHttpHost(), (int)Zend_Registry::get('configGlobal')->get('cookie_secure', 1) === 1, true ); Zend_Session::start(); $user = new Zend_Session_Namespace('Auth_User'); $user->setExpirationSeconds(60 * (int)Zend_Registry::get('configGlobal')->get('session_lifetime', 20)); $user->Dao = $userDao; $user->lock(); } } $this->getLogger()->debug(__METHOD__ . ' Log in : ' . $userDao->getFullName()); if (isset($previousUri) && !empty($previousUri) && (!empty($this->view->webroot)) && strpos( $previousUri, 'logout' ) === false ) { $redirect = $previousUri; } else { $redirect = $this->view->webroot . '/feed?first=true'; } echo JsonComponent::encode(array('status' => true, 'redirect' => $redirect)); } else { echo JsonComponent::encode(array('status' => false, 'message' => 'Invalid email or password')); } } else { echo JsonComponent::encode(array('status' => false, 'message' => 'Invalid email or password')); } } $this->view->allowPasswordReset = (int)$this->Setting->getValueByNameWithDefault('allow_password_reset', 0) === 1; $this->view->closeRegistration = (int)$this->Setting->getValueByNameWithDefault('close_registration', 1) === 1; } }
{ "content_hash": "61a1ba049118d3d96e911d8ce1f636b5", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 131, "avg_line_length": 47.45205479452055, "alnum_prop": 0.4282621247113164, "repo_name": "midasplatform/rsnabranding", "id": "3a08f37b087bb5ec1cf6e0e91ce43a6a77b3aeaf", "size": "6928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "controllers/IndexController.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2864" }, { "name": "HTML", "bytes": "6916" }, { "name": "JavaScript", "bytes": "8795" }, { "name": "PHP", "bytes": "22939" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.kusto.generated; import com.azure.core.util.Context; /** Samples for Clusters ListOutboundNetworkDependenciesEndpoints. */ public final class ClustersListOutboundNetworkDependenciesEndpointsSamples { /* * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2022-07-07/examples/KustoOutboundNetworkDependenciesList.json */ /** * Sample code: Get Kusto cluster outbound network dependencies. * * @param manager Entry point to KustoManager. */ public static void getKustoClusterOutboundNetworkDependencies( com.azure.resourcemanager.kusto.KustoManager manager) { manager.clusters().listOutboundNetworkDependenciesEndpoints("kustorptest", "kustoCluster", Context.NONE); } }
{ "content_hash": "7cfd9f4e2cace16fe3ea3b4d80bb0c69", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 154, "avg_line_length": 41.69565217391305, "alnum_prop": 0.7632950990615224, "repo_name": "Azure/azure-sdk-for-java", "id": "bf13824cb068739ea68ef40cf82541e2c9451368", "size": "959", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsSamples.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <Document> <Header> <SchemaName>Location</SchemaName> <Identifier>location_geonames_2745452</Identifier> <DocumentState>public</DocumentState> <TimeStamp>1390753461724</TimeStamp> <SummaryFields> <Title>NL &gt; North Brabant &gt; Vlas</Title> </SummaryFields> </Header> <Body> <Location> <GeopoliticalHierarchy>NL,North Brabant,Vlas</GeopoliticalHierarchy> <LocationName> <Appelation>Vlas</Appelation> <LocationNameType>populated place</LocationNameType> <Comments></Comments> </LocationName> <Coordinates> <Longitude>5.71528</Longitude> <Latitude>51.369170000000004</Latitude> </Coordinates> <GeonamesURI>http://www.geonames.org/2745452</GeonamesURI> <WikipediaLink/> <DbpediaLink/> </Location> </Body> </Document>
{ "content_hash": "9ccdd33ecf038cbd5bc66fc3214d8643", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 74, "avg_line_length": 30.655172413793103, "alnum_prop": 0.6614173228346457, "repo_name": "delving/oscr-data", "id": "b01af07304b33c0d4803a664e11b60b1bdca879e", "size": "889", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shared/Location/location_geonames_2745452.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>MVVM</title> <meta charset="utf-8"> <link href="../content/shared/styles/examples-offline.css" rel="stylesheet"> <link href="../../styles/kendo.common.min.css" rel="stylesheet"> <link href="../../styles/kendo.rtl.min.css" rel="stylesheet"> <link href="../../styles/kendo.default.min.css" rel="stylesheet"> <link href="../../styles/kendo.dataviz.min.css" rel="stylesheet"> <link href="../../styles/kendo.dataviz.default.min.css" rel="stylesheet"> <script src="../../js/jquery.min.js"></script> <script src="../../js/kendo.all.min.js"></script> <script src="../content/shared/js/console.js"></script> <script> </script> </head> <body> <a class="offline-button" href="../index.html">Back</a> <div id="example"> <div class="demo-section"> <div class="box-col" style="width: 500px;"> <h4>Hover some series</h4> <div data-role="chart" data-legend="{ position: 'top' }" data-series-defaults="{ type: 'donut', startAngle: 270 }" data-series="[{ field: 'share', categoryField: 'resolution', visibleInLegendField: 'visibleInLegend', padding: 10 }]" data-bind="visible: isVisible, source: screenResolution, events: { seriesHover: onSeriesHover }"></div> </div> <div class="box-col"> <h4>Console</h4> <div class="console"></div> </div> </div> <div class="box"> <div class="box-col" style="width: 500px;"> <h4>Configuration</h4> <div> <label><input type="checkbox" data-bind="checked: isVisible">Visible</label> </div> </div> <div class="box-col"> <h4>Information</h4> Kendo UI Chart supports the <a href="http://docs.telerik.com/kendo-ui/getting-started/framework/mvvm/bindings/events">events</a>, <a href="http://docs.telerik.com/kendo-ui/getting-started/framework/mvvm/bindings/source">source</a> and <a href="http://docs.telerik.com/kendo-ui/getting-started/framework/mvvm/bindings/visible">visible</a> bindings. </div> </div> <script> function createChart() { var viewModel = kendo.observable({ isVisible: true, onSeriesHover: function(e) { kendoConsole.log(kendo.format("event :: seriesHover ({0} : {1})", e.series.name, e.value)); }, screenResolution: new kendo.data.DataSource({ transport: { read: { url: "../content/dataviz/js/screen_resolution.json", dataType: "json" } }, sort: { field: "order", dir: "asc" }, group: { field: "year" } }) }); kendo.bind($("#example"), viewModel); } $(document).ready(createChart).bind("kendo:skinChange", createChart); </script> </div> <div class='demo-section'> <h3>Note:</h3> <p> Security restrictions prevent this example from working in all browsers when the page is loaded from the file system (via file:// protocol). If the demo is not working as expected, please host the Kendo folder on a web server. </p> </div> </body> </html>
{ "content_hash": "3df3a8ab45d076d553d25abd189ff19e", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 156, "avg_line_length": 36, "alnum_prop": 0.4978835978835979, "repo_name": "hhuynhlam/Ulysses", "id": "8ea40c373341a3485aebc3f2cb28eca1a053b250", "size": "3780", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/client/vendor/kendo/examples/donut-charts/mvvm.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "192778" }, { "name": "HTML", "bytes": "74176" }, { "name": "JavaScript", "bytes": "29078" }, { "name": "Shell", "bytes": "1104" } ], "symlink_target": "" }
package push; import io.waterworx.pushover.PushoverService; import io.waterworx.pushover.PushoverUtils; import com.google.inject.AbstractModule; public class AppInjector extends AbstractModule { @Override protected void configure() { bind(PushoverService.class).to(PushoverUtils.class); } }
{ "content_hash": "b7cb3298430f21c4db79da92b7c529d0", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 54, "avg_line_length": 20.066666666666666, "alnum_prop": 0.8006644518272426, "repo_name": "GrahamA2/PushoverTWPlugin", "id": "0dcc351a4c5a06239f22df30c4cac7da44b1c6f1", "size": "301", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CommonCode/src/main/java/push/AppInjector.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "19958" } ], "symlink_target": "" }