prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use env_logger::{fmt::Formatter, Builder}; use log::{LevelFilter, Record}; use std::{ env, io::{self, Write}, }; pub fn init(without_time: bool, debug_level: u64, bin_name: &str) { let mut log_builder = Builder::new(); log_builder.filter(None, LevelFilter::Info); match debug_level { 0 => { // Default filter log_builder.format(move |fmt, r| log_time(fmt, without_time, r)); } 1 => { let log_builder = log_builder.format(move |fmt, r| log_time_module(fmt, without_time, r));<|fim▁hole|> } 2 => { let log_builder = log_builder.format(move |fmt, r| log_time_module(fmt, without_time, r)); log_builder .filter(Some(bin_name), LevelFilter::Debug) .filter(Some("shadowsocks"), LevelFilter::Debug); } 3 => { let log_builder = log_builder.format(move |fmt, r| log_time_module(fmt, without_time, r)); log_builder .filter(Some(bin_name), LevelFilter::Trace) .filter(Some("shadowsocks"), LevelFilter::Trace); } _ => { let log_builder = log_builder.format(move |fmt, r| log_time_module(fmt, without_time, r)); log_builder.filter(None, LevelFilter::Trace); } } if let Ok(env_conf) = env::var("RUST_LOG") { log_builder.parse(&env_conf); } log_builder.init(); } fn log_time(fmt: &mut Formatter, without_time: bool, record: &Record) -> io::Result<()> { if without_time { writeln!(fmt, "[{}] {}", record.level(), record.args()) } else { writeln!( fmt, "[{}][{}] {}", time::now().strftime("%Y-%m-%d][%H:%M:%S.%f").unwrap(), record.level(), record.args() ) } } fn log_time_module(fmt: &mut Formatter, without_time: bool, record: &Record) -> io::Result<()> { if without_time { writeln!( fmt, "[{}] [{}] {}", record.level(), record.module_path().unwrap_or("*"), record.args() ) } else { writeln!( fmt, "[{}][{}] [{}] {}", time::now().strftime("%Y-%m-%d][%H:%M:%S.%f").unwrap(), record.level(), record.module_path().unwrap_or("*"), record.args() ) } }<|fim▁end|>
log_builder.filter(Some(bin_name), LevelFilter::Debug);
<|file_name|>04_coffee.js<|end_file_name|><|fim▁begin|><|fim▁hole|> // Inserts seed entries return knex('coffee').insert([ { id: 1, name: 'Three Africas', producer_id: 1, flavor_profile: 'Fruity, radiant, creamy', varieties: 'Heirloom', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 2, name: 'Ethiopia Bulga', producer_id: 2, flavor_profile: 'Cotton Candy, Strawberry, Sugar, Tangerine', varieties: 'Heirloom', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 3, name: 'Columbia Andino', producer_id: 2, flavor_profile: 'Butterscotch Citrus', varieties: 'Bourbon, Caturra, Typica', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 4, name: 'Colombia Popayán Fall Harvest', producer_id: 1, flavor_profile: 'Baking spice, red apple, nougat', varieties: '', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }]) .then(() => { return knex.raw("SELECT setval('coffee_id_seq', (SELECT MAX(id) FROM coffee));"); }); }); };<|fim▁end|>
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('coffee').del() .then(function () {
<|file_name|>AbstractJsonQueryBuilderFactory.java<|end_file_name|><|fim▁begin|>package com.senseidb.search.node.impl; import org.json.JSONObject; import com.senseidb.search.node.SenseiQueryBuilder; import com.senseidb.search.node.SenseiQueryBuilderFactory; import com.senseidb.search.req.SenseiQuery; import com.senseidb.util.JSONUtil.FastJSONObject; public abstract class AbstractJsonQueryBuilderFactory implements SenseiQueryBuilderFactory { @Override<|fim▁hole|> public SenseiQueryBuilder getQueryBuilder(SenseiQuery query) throws Exception { JSONObject jsonQuery = null; if (query != null) { byte[] bytes = query.toBytes(); jsonQuery = new FastJSONObject(new String(bytes, SenseiQuery.utf8Charset)); } return buildQueryBuilder(jsonQuery); } public abstract SenseiQueryBuilder buildQueryBuilder(JSONObject jsonQuery); }<|fim▁end|>
<|file_name|>local.py<|end_file_name|><|fim▁begin|><|fim▁hole|>DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': Path.join(BASE_DIR, 'db.sqlite3'), } } STATIC_URL = '/static/'<|fim▁end|>
__author__ = 'soporte' from .base import *
<|file_name|>TestAtom.cpp<|end_file_name|><|fim▁begin|>#include <pulsar/testing/CppTester.hpp> #include <pulsar/system/Atom.hpp> using namespace pulsar; TEST_SIMPLE(TestAtom){ CppTester tester("Testing the Atom class"); Atom H=create_atom({0.0,0.0,0.0},1); Atom H2=create_atom({0.0,0.0,0.0},1,1); tester.test_equal("create_atom works",H,H2); tester.test_equal("correct Z",1,H.Z); tester.test_equal("correct isotope",1,H.isotope); tester.test_equal("correct mass",1.007975,H.mass); tester.test_equal("correct isotope mass",1.0078250322,H.isotope_mass); tester.test_equal("correct charge",0,H.charge); tester.test_equal("correct multiplicity",2,H.multiplicity); tester.test_equal("correct nelectrons",1,H.nelectrons); tester.test_equal("correct covalent radius",0.5858150988919267,H.cov_radius); tester.test_equal("correct vDW radius",2.267671350549394,H.vdw_radius); Atom H3(H2); tester.test_equal("copy constructor works",H,H3); Atom H4(std::move(H3)); tester.test_equal("move constructor works",H,H4); Atom D=create_atom({0.0,0.0,0.0},1,2); tester.test_equal("Isotopes work",2,D.isotope); tester.test_equal("Isotopes are different",true,D!=H); <|fim▁hole|> Atom U=create_atom({0.0,0.0,0.0},92); U=std::move(H4); tester.test_equal("move assignment works",U,H); tester.test_equal("hash works",H.my_hash(),U.my_hash()); tester.test_equal("hash works 1",H.my_hash(),H2.my_hash()); tester.test_equal("hash works 2",H.my_hash(),D.my_hash()); Atom GH=make_ghost_atom(H2); tester.test_equal("ghost works",true,is_ghost_atom(GH)); Atom q=make_point_charge(H2,3.3),q2=make_point_charge(H2.get_coords(),3.3); tester.test_equal("point charges work",true,is_point_charge(q)); tester.test_equal("point charges work 2",true,is_point_charge(q2)); tester.test_equal("is same point charge",q,q2); Atom Dm=make_dummy_atom(H),Dm2=make_dummy_atom(H.get_coords()); tester.test_equal("is dummy atom",true,is_dummy_atom(Dm)); tester.test_equal("is dummy atom 2",true,is_dummy_atom(Dm2)); tester.test_equal("is same dummy atom",Dm,Dm2); tester.print_results(); return tester.nfailed(); }<|fim▁end|>
D=H4; tester.test_equal("assignment works",D,H);
<|file_name|>find.d.ts<|end_file_name|><|fim▁begin|>import { find } from "lodash";<|fim▁hole|><|fim▁end|>
export default find;
<|file_name|>Pattern_White_Space-regex.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
// Regular expression that matches all symbols with the `Pattern_White_Space` property as per Unicode v6.3.0: /[\x09-\x0D\x20\x85\u200E\u200F\u2028\u2029]/;
<|file_name|>usodiz.py<|end_file_name|><|fim▁begin|># uso dizionario come cache per evitare di calcolare sempre PEOPLE = [] def main(): """ devo far inserire name, city, salary come input e salvarli nel dizionario # 1.finche utente non smette.<|fim▁hole|> usa raw_input per chiedere le info all'utente # 3.l'utente inserisce la città # 4.l'utente inserisce lo stipendio # 5.inserisci il dizionario con chiavi 'name','city','salary' nella lista PEOPLE = [] PEOPLE.append(person_d) # 6.STAMPA A VIDEO PEOPLE nel modo che ti piace # 7.ri-inizia da Step 1 # FINE #----BONUS----- #STEP 8.QUANDO L'UTENTE SMETTE --> SCRIVI I DATI IN UN FILE # SE VUOI STEP 8.1 IN FOMRATO JSON # SE VUOI STEP 8.2 IN FORMATO CSV # SE VUOI STEP 8.3 IN FORMATO XML # STEP 9. FALLO ANCHE SE L 'UTENTE PREME CTRL+C O CTRL+Z """ cont = True while cont: cont = insert_person() stampa_lista() scrivi_file() def insert_person(): ret_val = False nome = get_input("Come ti chiami ? ") if nome : cit = get_input("Dove vivi ? ") if cit : salario = get_input("Quanto guadagni mensilmente ? ") try: salario = int(salario) except ValueError: print("Salario non valido") return False if salario : persona = {"name":nome , "city" : cit, "salary" : salario } PEOPLE.append(persona) ret_val = True #print(ret_val) return ret_val def stampa_lista(): print("Stampo la mia lista... ") for x in PEOPLE: print("Sig: {name} di {city} guadagna {salary}".format(**x) ) def get_input(msg): try: ret = raw_input(msg) except KeyboardInterrupt: ret ='' return ret def scrivi_file(): print("Scrivo file... ") if __name__ == "__main__": main()<|fim▁end|>
# 2.l'utente inserisce il nome
<|file_name|>helpers.js<|end_file_name|><|fim▁begin|>const constants = require('./constants.js'); const AWS = constants.AWS; const DYNAMODB_TABLE = constants.DYNAMODB_TABLE; const model = require('./model.json'); // a static copy of your model, used to suggest custom slot values module.exports = { 'randomArrayElement': function(myArray) { return(myArray[Math.floor(Math.random() * myArray.length)]); }, 'capitalize': function(myString) { return myString.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); }, 'supportsDisplay': function(handlerInput) // returns true if the skill is running on a device with a display (Echo Show, Echo Spot, etc.) { // Enable your skill for display as shown here: https://alexa.design/enabledisplay const hasDisplay = handlerInput.requestEnvelope.context && handlerInput.requestEnvelope.context.System && handlerInput.requestEnvelope.context.System.device && handlerInput.requestEnvelope.context.System.device.supportedInterfaces && handlerInput.requestEnvelope.context.System.device.supportedInterfaces.Display; return hasDisplay; }, 'timeDelta': function(t1, t2) { const dt1 = new Date(t1); const dt2 = new Date(t2); const timeSpanMS = dt2.getTime() - dt1.getTime(); const span = { "timeSpanMIN": Math.floor(timeSpanMS / (1000 * 60 )), "timeSpanHR": Math.floor(timeSpanMS / (1000 * 60 * 60)), "timeSpanDAY": Math.floor(timeSpanMS / (1000 * 60 * 60 * 24)), "timeSpanDesc" : "" }; if (span.timeSpanHR < 2) { span.timeSpanDesc = span.timeSpanMIN + " minutes"; } else if (span.timeSpanDAY < 2) { span.timeSpanDesc = span.timeSpanHR + " hours"; } else { span.timeSpanDesc = span.timeSpanDAY + " days"; } return span; }, 'sayArray': function(myData, penultimateWord = 'and') { // the first argument is an array [] of items // the second argument is the list penultimate word; and/or/nor etc. Default to 'and' let result = ''; myData.forEach(function(element, index, arr) { if (index === 0) { result = element; } else if (index === myData.length - 1) { result += ` ${penultimateWord} ${element}`; } else { result += `, ${element}`; } }); return result; }, 'stripTags': function(str) { return str.replace(/<\/?[^>]+(>|$)/g, ""); }, 'getSampleUtterance': function(intent) { return randomElement(intent.samples); }, 'getSlotValues': function(filledSlots) { const slotValues = {}; Object.keys(filledSlots).forEach((item) => { const name = filledSlots[item].name; if (filledSlots[item] && filledSlots[item].resolutions && filledSlots[item].resolutions.resolutionsPerAuthority[0] && filledSlots[item].resolutions.resolutionsPerAuthority[0].status && filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code) { switch (filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code) { case 'ER_SUCCESS_MATCH': let resolutions = []; let vals = filledSlots[item].resolutions.resolutionsPerAuthority[0].values; for (let i = 0; i < vals.length; i++) { resolutions.push(vals[i].value.name); } slotValues[name] = { heardAs: filledSlots[item].value, resolved: filledSlots[item].resolutions.resolutionsPerAuthority[0].values[0].value.name, resolutions: resolutions, ERstatus: 'ER_SUCCESS_MATCH' }; break; case 'ER_SUCCESS_NO_MATCH': slotValues[name] = { heardAs: filledSlots[item].value, resolved: '', ERstatus: 'ER_SUCCESS_NO_MATCH' }; break; default: break; } } else { slotValues[name] = { heardAs: filledSlots[item].value, resolved: '', ERstatus: '' }; } }, this); return slotValues; }, 'getExampleSlotValues': function(intentName, slotName) { let examples = []; let slotType = ''; let slotValuesFull = []; let intents = model.interactionModel.languageModel.intents; for (let i = 0; i < intents.length; i++) { if (intents[i].name == intentName) { let slots = intents[i].slots; for (let j = 0; j < slots.length; j++) { if (slots[j].name === slotName) { slotType = slots[j].type; } } } } let types = model.interactionModel.languageModel.types; for (let i = 0; i < types.length; i++) { if (types[i].name === slotType) { slotValuesFull = types[i].values; } } slotValuesFull = module.exports.shuffleArray(slotValuesFull); examples.push(slotValuesFull[0].name.value); examples.push(slotValuesFull[1].name.value); if (slotValuesFull.length > 2) { examples.push(slotValuesFull[2].name.value); } return examples; }, 'getRecordCount': function(callback) { const params = { TableName: DYNAMODB_TABLE }; let docClient = new AWS.DynamoDB.DocumentClient(); docClient.scan(params, (err, data) => { if (err) { console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); } else { const skillUserCount = data.Items.length; callback(skillUserCount); } }); }, 'changeProsody' : function(attribute, current, change) { let newValue = ''; if (attribute === 'rate') { switch(current + '.' + change) { case 'x-slow.slower': case 'slow.slower': newValue = 'x-slow'; break; case 'medium.slower': case 'x-slow.faster': newValue = 'slow'; break; case 'fast.slower': case 'slow.faster': newValue = 'medium'; break;<|fim▁hole|> case 'medium.faster': newValue = 'fast'; break; case 'x-fast.faster': case 'fast.faster': newValue = 'x-fast'; break; default: newValue = 'medium'; } } return newValue; }, 'sendTxtMessage': function(params, locale, callback) { let mobileNumber = params.PhoneNumber.toString(); if (locale === 'en-US') { if (mobileNumber.length < 10 ){ const errMsg = 'mobileNumber provided is too short: ' + mobileNumber + '. '; callback(errMsg); } if (mobileNumber.length == 10 ) { mobileNumber = '1' + mobileNumber; } } else { if (locale === 'other locales tbd') { // add validation and format code } } if (mobileNumber.substring(0,1) !== '+') { mobileNumber = '+' + mobileNumber; } let snsParams = params; snsParams.PhoneNumber = mobileNumber; const SNS = new AWS.SNS(); SNS.publish(snsParams, function(err, data){ // console.log('sending message to ' + mobileNumber ); if (err) console.log(err, err.stack); callback('I sent you a text message. '); }); }, 'generatePassPhrase': function() { // 'correct', 'horse', 'battery', 'staple' const word1 = ['nice', 'good', 'clear', 'kind', 'red', 'green', 'orange', 'yellow', 'brown', 'careful', 'powerful', 'vast', 'happy', 'deep', 'warm', 'cold', 'heavy', 'dry', 'quiet', 'sweet', 'short', 'long', 'late', 'early', 'quick', 'fast', 'slow', 'other','public','clean','proud', 'flat','round', 'loud', 'funny', 'free', 'tall', 'short', 'big', 'small']; const word2 = ['person', 'day', 'car', 'tree', 'fish', 'wheel', 'chair', 'sun', 'moon', 'star', 'story', 'voice', 'job', 'fact', 'record', 'computer', 'ocean', 'building', 'cat', 'dog', 'rabbit', 'carrot', 'orange', 'bread', 'soup', 'spoon', 'fork', 'straw', 'napkin', 'fold', 'pillow', 'radio', 'towel', 'pencil', 'table', 'mark', 'teacher', 'student', 'developer', 'raisin', 'pizza', 'movie', 'book', 'cup', 'plate', 'wall', 'door', 'window', 'shoes', 'hat', 'shirt', 'bag', 'page', 'clock', 'glass', 'button', 'bump', 'paint', 'song', 'story', 'memory', 'school', 'corner', 'wire', 'cable' ]; const numLimit = 999; const phraseObject = { 'word1': randomArrayElement(word1), 'word2': randomArrayElement(word2), 'number': Math.floor(Math.random() * numLimit) }; return phraseObject; }, 'shuffleArray': function(array) { // Fisher Yates shuffle! let currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }, 'incrementArray': function(arr, element) { for(let i = 0; i < arr.length; i++) { if (arr[i].name === element) { arr[i].value += 1; return arr; } } // no match, create new element arr.push({'name':element, 'value': 1}); return arr; }, 'sortArray': function(arr) { return arr.sort(function(a,b) {return (a.value > b.value) ? -1 : ((b.value > a.value) ? 1 : 0);} ); }, 'rankArray': function(arr) { // assumes sorted array let rank = 0; let previousValue = 0; let tiesAll = {}; let ties = []; for(let i = 0; i < arr.length; i++) { if (arr[i].value !== previousValue) { rank += 1; ties = []; } ties.push(arr[i].name); arr[i].rank = rank; arr[i].ties = ties; previousValue = arr[i].value; } // list other elements tied at the same rank for(let i = 0; i < arr.length; i++) { let tiesCleaned = []; for (let j = 0; j < arr[i].ties.length; j++) { if (arr[i].ties[j] !== arr[i].name) { tiesCleaned.push(arr[i].ties[j]); } } arr[i].ties = tiesCleaned; } return arr; } }; // another way to define helpers: extend a native type with a new function Array.prototype.diff = function(a) { return this.filter(function(i) {return a.indexOf(i) < 0;}); };<|fim▁end|>
case 'x-fast.slower':
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import jsonify, session from marshmallow import INCLUDE, fields from marshmallow_enum import EnumField from indico.modules.categories.controllers.base import RHDisplayCategoryBase from indico.modules.events.controllers.base import RHDisplayEventBase from indico.modules.search.base import SearchOptions, SearchTarget, get_search_provider from indico.modules.search.internal import InternalSearch from indico.modules.search.result_schemas import ResultSchema from indico.modules.search.views import WPCategorySearch, WPEventSearch, WPSearch from indico.util.marshmallow import validate_with_message from indico.web.args import use_kwargs from indico.web.rh import RH class RHSearchDisplay(RH): def _process(self): return WPSearch.render_template('search.html') class RHCategorySearchDisplay(RHDisplayCategoryBase): def _process(self): return WPCategorySearch.render_template('category_search.html', self.category) class RHEventSearchDisplay(RHDisplayEventBase):<|fim▁hole|> return WPEventSearch.render_template('event_search.html', self.event) class RHAPISearch(RH): """API for searching across all records with the current search provider. Besides pagination, filters or placeholders may be passed as query parameters. Since `type` may be a list, the results from the search provider are not mixed with the InternalSearch. """ @use_kwargs({ 'page': fields.Int(missing=None), 'q': fields.String(required=True), 'type': fields.List(EnumField(SearchTarget), missing=None), 'admin_override_enabled': fields.Bool( missing=False, validate=validate_with_message(lambda value: session.user and session.user.is_admin, 'Restricted to admins') ), }, location='query', unknown=INCLUDE) def _process(self, page, q, type, **params): search_provider = get_search_provider() if type == [SearchTarget.category]: search_provider = InternalSearch result = search_provider().search(q, session.user, page, type, **params) return ResultSchema().dump(result) class RHAPISearchOptions(RH): def _process(self): search_provider = get_search_provider()() placeholders = search_provider.get_placeholders() sort_options = search_provider.get_sort_options() return jsonify(SearchOptions(placeholders, sort_options).dump())<|fim▁end|>
def _process(self):
<|file_name|>ManagedCamelContextTest.java<|end_file_name|><|fim▁begin|>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.management; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.openmbean.TabularData; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.util.StringHelper; import org.junit.Ignore; /** * @version */ public class ManagedCamelContextTest extends ManagementTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); // to force a different management name than the camel id context.getManagementNameStrategy().setNamePattern("19-#name#"); return context; } public void testManagedCamelContext() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\""); assertTrue("Should be registered", mbeanServer.isRegistered(on)); String name = (String) mbeanServer.getAttribute(on, "CamelId"); assertEquals("camel-1", name); String managementName = (String) mbeanServer.getAttribute(on, "ManagementName"); assertEquals("19-camel-1", managementName); String uptime = (String) mbeanServer.getAttribute(on, "Uptime"); assertNotNull(uptime); String status = (String) mbeanServer.getAttribute(on, "State"); assertEquals("Started", status); Boolean messageHistory = (Boolean) mbeanServer.getAttribute(on, "MessageHistory"); assertEquals(Boolean.TRUE, messageHistory); Integer total = (Integer) mbeanServer.getAttribute(on, "TotalRoutes"); assertEquals(2, total.intValue()); Integer started = (Integer) mbeanServer.getAttribute(on, "StartedRoutes"); assertEquals(2, started.intValue()); // invoke operations MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); mbeanServer.invoke(on, "sendBody", new Object[]{"direct:start", "Hello World"}, new String[]{"java.lang.String", "java.lang.Object"}); assertMockEndpointsSatisfied(); resetMocks(); mock.expectedBodiesReceived("Hello World"); mbeanServer.invoke(on, "sendStringBody", new Object[]{"direct:start", "Hello World"}, new String[]{"java.lang.String", "java.lang.String"}); assertMockEndpointsSatisfied(); Object reply = mbeanServer.invoke(on, "requestBody", new Object[]{"direct:foo", "Hello World"}, new String[]{"java.lang.String", "java.lang.Object"}); assertEquals("Bye World", reply); reply = mbeanServer.invoke(on, "requestStringBody", new Object[]{"direct:foo", "Hello World"}, new String[]{"java.lang.String", "java.lang.String"}); assertEquals("Bye World", reply); resetMocks();<|fim▁hole|> mock.expectedBodiesReceived("Hello World"); mock.expectedHeaderReceived("foo", 123); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("foo", 123); mbeanServer.invoke(on, "sendBodyAndHeaders", new Object[]{"direct:start", "Hello World", headers}, new String[]{"java.lang.String", "java.lang.Object", "java.util.Map"}); assertMockEndpointsSatisfied(); resetMocks(); mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); mock.expectedHeaderReceived("foo", 123); reply = mbeanServer.invoke(on, "requestBodyAndHeaders", new Object[]{"direct:start", "Hello World", headers}, new String[]{"java.lang.String", "java.lang.Object", "java.util.Map"}); assertEquals("Hello World", reply); assertMockEndpointsSatisfied(); // test can send Boolean can = (Boolean) mbeanServer.invoke(on, "canSendToEndpoint", new Object[]{"direct:start"}, new String[]{"java.lang.String"}); assertEquals(true, can.booleanValue()); can = (Boolean) mbeanServer.invoke(on, "canSendToEndpoint", new Object[]{"timer:foo"}, new String[]{"java.lang.String"}); assertEquals(false, can.booleanValue()); // stop Camel mbeanServer.invoke(on, "stop", null, null); } public void testManagedCamelContextCreateEndpoint() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\""); assertNull(context.hasEndpoint("seda:bar")); // create a new endpoint Object reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"}); assertEquals(Boolean.TRUE, reply); assertNotNull(context.hasEndpoint("seda:bar")); ObjectName seda = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=endpoints,name=\"seda://bar\""); boolean registered = mbeanServer.isRegistered(seda); assertTrue("Should be registered " + seda, registered); // create it again reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"}); assertEquals(Boolean.FALSE, reply); registered = mbeanServer.isRegistered(seda); assertTrue("Should be registered " + seda, registered); } public void testManagedCamelContextRemoveEndpoint() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\""); assertNull(context.hasEndpoint("seda:bar")); // create a new endpoint Object reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"}); assertEquals(Boolean.TRUE, reply); assertNotNull(context.hasEndpoint("seda:bar")); ObjectName seda = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=endpoints,name=\"seda://bar\""); boolean registered = mbeanServer.isRegistered(seda); assertTrue("Should be registered " + seda, registered); // remove it Object num = mbeanServer.invoke(on, "removeEndpoints", new Object[]{"seda:*"}, new String[]{"java.lang.String"}); assertEquals(1, num); assertNull(context.hasEndpoint("seda:bar")); registered = mbeanServer.isRegistered(seda); assertFalse("Should not be registered " + seda, registered); // remove it again num = mbeanServer.invoke(on, "removeEndpoints", new Object[]{"seda:*"}, new String[]{"java.lang.String"}); assertEquals(0, num); assertNull(context.hasEndpoint("seda:bar")); registered = mbeanServer.isRegistered(seda); assertFalse("Should not be registered " + seda, registered); } public void testFindComponentsInClasspath() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\""); assertTrue("Should be registered", mbeanServer.isRegistered(on)); @SuppressWarnings("unchecked") Map<String, Properties> info = (Map<String, Properties>) mbeanServer.invoke(on, "findComponents", null, null); assertNotNull(info); assertTrue(info.size() > 20); Properties prop = info.get("seda"); assertNotNull(prop); assertEquals("seda", prop.get("name")); assertEquals("org.apache.camel", prop.get("groupId")); assertEquals("camel-core", prop.get("artifactId")); } public void testManagedCamelContextCreateRouteStaticEndpointJson() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\""); // get the json String json = (String) mbeanServer.invoke(on, "createRouteStaticEndpointJson", null, null); assertNotNull(json); assertEquals(7, StringHelper.countChar(json, '{')); assertEquals(7, StringHelper.countChar(json, '}')); assertTrue(json.contains("{ \"uri\": \"direct://start\" }")); assertTrue(json.contains("{ \"uri\": \"direct://foo\" }")); } public void testManagedCamelContextExplainEndpointUri() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\""); // get the json String json = (String) mbeanServer.invoke(on, "explainEndpointJson", new Object[]{"log:foo?groupDelay=2000&groupSize=5", false}, new String[]{"java.lang.String", "boolean"}); assertNotNull(json); assertEquals(5, StringHelper.countChar(json, '{')); assertEquals(5, StringHelper.countChar(json, '}')); assertTrue(json.contains("\"groupDelay\": { \"kind\": \"parameter\", \"type\": \"integer\", \"javaType\": \"java.lang.Long\", \"deprecated\": \"false\", \"value\": \"2000\"," + " \"description\": \"Set the initial delay for stats (in millis)\" },")); assertTrue(json.contains("\"groupSize\": { \"kind\": \"parameter\", \"type\": \"integer\", \"javaType\": \"java.lang.Integer\", \"deprecated\": \"false\", \"value\": \"5\"," + " \"description\": \"An integer that specifies a group size for throughput logging.\" }")); assertTrue(json.contains("\"loggerName\": { \"kind\": \"path\", \"type\": \"string\", \"javaType\": \"java.lang.String\", \"deprecated\": \"false\"," + " \"value\": \"foo\", \"description\": \"The logger name to use\" }")); } public void testManagedCamelContextExplainEip() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\""); // get the json String json = (String) mbeanServer.invoke(on, "explainEipJson", new Object[]{"transform", false}, new String[]{"java.lang.String", "boolean"}); assertNotNull(json); assertTrue(json.contains("\"label\": \"transformation\"")); assertTrue(json.contains("\"expression\": { \"kind\": \"element\", \"required\": \"true\", \"type\": \"object\"")); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("mock:result"); from("direct:foo").transform(constant("Bye World")); } }; } }<|fim▁end|>
mock = getMockEndpoint("mock:result");
<|file_name|>IfcSlabTypeImpl.java<|end_file_name|><|fim▁begin|>/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 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<|fim▁hole|> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc4.impl; import org.eclipse.emf.ecore.EClass; import cn.dlb.bim.models.ifc4.Ifc4Package; import cn.dlb.bim.models.ifc4.IfcSlabType; import cn.dlb.bim.models.ifc4.IfcSlabTypeEnum; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Slab Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc4.impl.IfcSlabTypeImpl#getPredefinedType <em>Predefined Type</em>}</li> * </ul> * * @generated */ public class IfcSlabTypeImpl extends IfcBuildingElementTypeImpl implements IfcSlabType { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcSlabTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc4Package.Literals.IFC_SLAB_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IfcSlabTypeEnum getPredefinedType() { return (IfcSlabTypeEnum) eGet(Ifc4Package.Literals.IFC_SLAB_TYPE__PREDEFINED_TYPE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPredefinedType(IfcSlabTypeEnum newPredefinedType) { eSet(Ifc4Package.Literals.IFC_SLAB_TYPE__PREDEFINED_TYPE, newPredefinedType); } } //IfcSlabTypeImpl<|fim▁end|>
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from rest_framework.decorators import list_route from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets from .models import User from .serializers import UserSerializer <|fim▁hole|> class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer http_method_names = ['get', 'patch']<|fim▁end|>
<|file_name|>yaml_generator.py<|end_file_name|><|fim▁begin|>from ll1_symbols import * YAML_OUTPUT = """terminals: %s non-terminals: %s eof-marker: %s error-marker: %s start-symbol: %s productions: %s table: %s""" YAML_OUTPUT_NO_TABLE = """terminals: %s non-terminals: %s eof-marker: %s error-marker: %s start-symbol: %s productions: %s""" class YamlGenerator(object): """docstring for yaml_generator""" def __init__(self, grammar): self.grammar = grammar def print_yaml(self, ll1_table = None): def convert_list_str(a_list): return "[%s]" % (", ".join(a_list)) def convert_dict_str(a_dict): return "{%s}" % ", ".join(["%s: %s" % (key, value) for key, value in a_dict.items()]) def convert_dict_dict_str(a_dict): return "\n %s" % ("\n ".join(["%s: %s" % (key, convert_dict_str(value)) for key, value in a_dict.items()])) def convert_dict_list_str(a_dict): return "{%s}" % (", \n ".join(["%s: %s" % (key, convert_list_str(value)) for key, value in a_dict.items()])) def convert_dict_dict_list_str(a_dict): return "\n %s" % ("\n ".join(["%s: %s" % (key, convert_dict_list_str(value)) <|fim▁hole|> convert_list_str(list(self.grammar.non_term)), EOF, ERROR_MARKER, self.grammar.goal, convert_dict_dict_list_str(self.convert_production()), convert_dict_dict_str(ll1_table)) else: return YAML_OUTPUT_NO_TABLE % (convert_list_str(list(self.grammar.term)), convert_list_str(list(self.grammar.non_term)), EOF, ERROR_MARKER, self.grammar.goal, convert_dict_dict_list_str(self.convert_production())) def convert_production(self): return {idx : {production.left_hand.lexeme : [item.lexeme for item in production.right_hand if item.lexeme is not EPSILON]} for idx, production in enumerate(self.grammar.production)}<|fim▁end|>
for key, value in a_dict.items()])) if ll1_table: return YAML_OUTPUT % (convert_list_str(list(self.grammar.term)),
<|file_name|>AggregationStateSortedImpl.java<|end_file_name|><|fim▁begin|>/************************************************************************************** * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * **************************************************************************************/ package com.espertech.esper.epl.agg.access; import com.espertech.esper.client.EventBean; import com.espertech.esper.collection.MultiKeyUntyped; import com.espertech.esper.epl.expression.ExprEvaluator; import com.espertech.esper.epl.expression.ExprEvaluatorContext; import java.util.*; /** * Implementation of access function for single-stream (not joins). */ public class AggregationStateSortedImpl implements AggregationStateWithSize, AggregationStateSorted { protected final AggregationStateSortedSpec spec; protected final TreeMap<Object, Object> sorted; protected int size; /** * Ctor. * @param spec aggregation spec */ public AggregationStateSortedImpl(AggregationStateSortedSpec spec) { this.spec = spec; sorted = new TreeMap<Object, Object>(spec.getComparator());<|fim▁hole|> size = 0; } public void applyEnter(EventBean[] eventsPerStream, ExprEvaluatorContext exprEvaluatorContext) { EventBean theEvent = eventsPerStream[spec.getStreamId()]; if (theEvent == null) { return; } if (referenceEvent(theEvent)) { Object comparable = getComparable(spec.getCriteria(), eventsPerStream, true, exprEvaluatorContext); Object existing = sorted.get(comparable); if (existing == null) { sorted.put(comparable, theEvent); } else if (existing instanceof EventBean) { ArrayDeque coll = new ArrayDeque(2); coll.add(existing); coll.add(theEvent); sorted.put(comparable, coll); } else { ArrayDeque q = (ArrayDeque) existing; q.add(theEvent); } size++; } } protected boolean referenceEvent(EventBean theEvent) { // no action return true; } protected boolean dereferenceEvent(EventBean theEvent) { // no action return true; } public void applyLeave(EventBean[] eventsPerStream, ExprEvaluatorContext exprEvaluatorContext) { EventBean theEvent = eventsPerStream[spec.getStreamId()]; if (theEvent == null) { return; } if (dereferenceEvent(theEvent)) { Object comparable = getComparable(spec.getCriteria(), eventsPerStream, false, exprEvaluatorContext); Object existing = sorted.get(comparable); if (existing != null) { if (existing.equals(theEvent)) { sorted.remove(comparable); size--; } else if (existing instanceof ArrayDeque) { ArrayDeque q = (ArrayDeque) existing; q.remove(theEvent); if (q.isEmpty()) { sorted.remove(comparable); } size--; } } } } public EventBean getFirstValue() { if (sorted.isEmpty()) { return null; } Map.Entry<Object, Object> max = sorted.firstEntry(); return checkedPayload(max.getValue()); } public EventBean getLastValue() { if (sorted.isEmpty()) { return null; } Map.Entry<Object, Object> min = sorted.lastEntry(); return checkedPayload(min.getValue()); } public Iterator<EventBean> iterator() { return new AggregationStateSortedIterator(sorted, false); } public Iterator<EventBean> getReverseIterator() { return new AggregationStateSortedIterator(sorted, true); } public Collection<EventBean> collectionReadOnly() { return new AggregationStateSortedWrappingCollection(sorted, size); } public int size() { return size; } protected static Object getComparable(ExprEvaluator[] criteria, EventBean[] eventsPerStream, boolean istream, ExprEvaluatorContext exprEvaluatorContext) { if (criteria.length == 1) { return criteria[0].evaluate(eventsPerStream, istream, exprEvaluatorContext); } else { Object[] result = new Object[criteria.length]; int count = 0; for(ExprEvaluator expr : criteria) { result[count++] = expr.evaluate(eventsPerStream, true, exprEvaluatorContext); } return new MultiKeyUntyped(result); } } private EventBean checkedPayload(Object value) { if (value instanceof EventBean) { return (EventBean) value; } ArrayDeque<EventBean> q = (ArrayDeque<EventBean>) value; return q.getFirst(); } }<|fim▁end|>
} public void clear() { sorted.clear();
<|file_name|>serialization.py<|end_file_name|><|fim▁begin|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function def load_pem_traditional_openssl_private_key(data, password, backend):<|fim▁hole|> def load_pem_pkcs8_private_key(data, password, backend): return backend.load_pkcs8_pem_private_key( data, password )<|fim▁end|>
return backend.load_traditional_openssl_pem_private_key( data, password )
<|file_name|>Solution.java<|end_file_name|><|fim▁begin|>package MultiplyStrings; /** * Created by gzhou on 6/1/15. */ public class Solution {<|fim▁hole|> public static String multiply(String num1, String num2) { String n1 = new StringBuilder(num1).reverse().toString(); String n2 = new StringBuilder(num2).reverse().toString(); int[] tmp = new int[n1.length() + n2.length()]; for (int i = 0; i < n1.length(); i++) { int a = n1.charAt(i) - '0'; for (int j = 0; j < n2.length(); j++) { int b = n2.charAt(j) - '0'; tmp[i + j] += b * a; } } StringBuilder sb = new StringBuilder(); for (int k = 0; k < tmp.length; k++) { int d = tmp[k] % 10; int carry = tmp[k] / 10; // will insert digit from left most sb.insert(0, d); if (k < tmp.length - 1) { tmp[k + 1] += carry; } } // remove zeros which are created by initialization of 'tmp' while(sb.length()>0 && sb.charAt(0)=='0'){ sb.deleteCharAt(0); } return sb.length()==0? "0" : sb.toString(); } }<|fim▁end|>
public static void main(String[] args) { System.out.println(multiply("123", "20")); }
<|file_name|>comp_delib_player.rs<|end_file_name|><|fim▁begin|>extern crate time; use {Player, MoveResult}; use game_manager::{Game, State}; use gdl::{Move, Score}; /// A bounded compulsive deliberation player. This should only be used for single player games pub struct CompDelibPlayer { depth_limit: u32, best_move: Option<Move>, } impl CompDelibPlayer { /// Returns a CompDelibPlayer that does not recurse past the given depth pub fn new(depth: u32) -> CompDelibPlayer { CompDelibPlayer { depth_limit: depth, best_move: None } } fn best_move(&mut self, game: &Game) -> MoveResult<Move> { let cur_state = game.current_state(); let mut moves = game.legal_moves(cur_state, game.role()); assert!(moves.len() >= 1, "No legal moves"); if moves.len() == 1 { return Ok(moves.swap_remove(0)); } let mut max = 0; let mut res = moves[0].clone(); self.best_move = Some(res.clone()); for m in moves { let score = match self.max_score(game, &cur_state, &vec![m.clone()], 0) { Ok(score) => score, Err(m) => return Err(m) }; if score == 100 { return Ok(m); } if score > max { max = score; self.best_move = Some(m.clone()); res = m; } check_time_result!(self, game); } Ok(res) } fn max_score(&mut self, game: &Game, state: &State, moves: &[Move], depth: u32) -> MoveResult<Score> { if depth > self.depth_limit { return Ok(game.goal(state, game.role())); } let cur_state = game.next_state(state, moves); if game.is_terminal(&cur_state) { return Ok(game.goal(&cur_state, game.role())); } let moves = game.legal_moves(&cur_state, game.role()); assert!(moves.len() >= 1, "No legal moves"); let mut max = 0; for m in moves { let score = match self.max_score(game, &cur_state, &vec![m], depth + 1) { Ok(score) => score, e @ Err(_) => return e }; if score > max { max = score } check_time_result!(self, game); } Ok(max) } } impl Player for CompDelibPlayer { fn name(&self) -> String { "CompDelibPlayer".to_string()<|fim▁hole|> } fn select_move(&mut self, game: &Game) -> Move { assert!(game.roles().len() == 1, "CompDelibPlayer only works with single player games"); let m = match self.best_move(&game) { Ok(m) => m, Err(m) => { warn!("Out of time"); m } }; info!("Selecting move {}", m.to_string()); m } fn out_of_time(&mut self, _: &Game) -> Move { self.best_move.take().unwrap() } }<|fim▁end|>
<|file_name|>crop.py<|end_file_name|><|fim▁begin|># crop.py # Derek Groenendyk # 2/15/2017 # reads input data from Excel workbook from collections import OrderedDict import logging import numpy as np import os import sys from cons2.cu import CONSUMPTIVE_USE # from utils import excel logger = logging.getLogger('crop') logger.setLevel(logging.DEBUG) class CROP(object): """docstring for CROP""" def __init__(self, shrtname, longname, crop_type, mmnum, directory, sp): self.sname = shrtname self.lname = longname self.crop_type = crop_type self.directory = directory if self.crop_type == 'ANNUAL': self.mmnum = mmnum if sp.et_method == 'fao': self.stages = {} self.kc = {} # self.read_cropdev() self.read_stages() self.read_kc() elif sp.et_method == 'scs': self.get_nckc() self.get_ckc() # methods = { # 'ANNUAL': ANNUAL, # 'PERENNIAL': PERENNIAL # } # self.cu = methods[crop_type](sp, self) self.cu = CONSUMPTIVE_USE(sp, self) def read_cropdev(self): try: infile = open(os.path.join(self.directory,'data','crop_dev_coef.csv'),'r') except TypeError: logger_fn.critical('crop_dev_coef.csv file not found.') raise lines = infile.readlines() infile.close() # sline = lines[1].split(',') # cname = sline[0].replace(' ','') # temp_cname = cname stage_flag = False kc_flag = False switch = False i = 1 # while i < len(lines): while i < len(lines): sline = lines[i].split(',') cname = sline[0].replace(' ','') # print(cname,self.sname) if cname != '': if cname == self.sname: # print(i) if not switch: stage = sline[1].lower() self.stages[stage] = np.array([float(item) for item in sline[2:6]]) # print(1.0-np.sum(self.stages[stage])) stage_flag = True else: num = int(sline[1].replace(' ','')) self.kc[num] = np.array([float(item) for item in sline[2:5]]) kc_flag = True else: if switch: break i += 1 switch = True i += 1 if stage_flag == False or kc_flag == False: logger.critical('Crop, ' + self.sname + ', not found in crop_dev_coef.csv.') # include site?? raise def read_stages(self): try: infile = open(os.path.join(self.directory,'data','fao_crop_stages.csv'),'r') except TypeError: logger_fn.critical('fao_crop_stages.csv file not found.') raise lines = infile.readlines() infile.close() flag = False i = 1 while i < len(lines): sline = lines[i].split(',') cname = sline[0].replace(' ','') if cname != '': if cname == self.sname: stage = sline[1].lower() self.stages[stage] = np.array([float(item) for item in sline[2:6]]) flag = True else: if flag: break flag = False i += 1 if not flag: logger.critical('Crop, ' + self.sname + ', not found in fao_crop_stages.csv.') # include site?? raise def read_kc(self): try: infile = open(os.path.join(self.directory,'data','fao_crop_coef.csv'),'r') except TypeError: logger_fn.critical('fao_crop_coef.csv file not found.') raise lines = infile.readlines() infile.close() flag = False i = 1 while i < len(lines): sline = lines[i].split(',') cname = sline[0].replace(' ','') if cname != '': if cname == self.sname: num = int(sline[1].replace(' ','')) self.kc[num] = np.array([float(item) for item in sline[2:5]]) flag = True else: if flag: break flag = False i += 1 if not flag: logger.critical('Crop, ' + self.sname + ', not found in fao_crop_coef.csv.') # include site?? raise def get_nckc(self): """ Reads in crop coefficients. Parameters ---------- name: string Name of the crop Returns ------- nckc: list List of crop coefficients """ try: infile = open(os.path.join(self.directory,'data','scs_crop_stages.csv'),'r') except TypeError: logger.critical('scs_crop_stages.csv file not found.') raise lines = infile.readlines() infile.close() nckca = [float(item) for item in lines[0].split(',')[1:]] nckcp = [float(item) for item in lines[1].split(',')[1:]] if self.crop_type == 'PERENNIAL': self.nckc= nckcp else: self.nckc = nckca def get_ckc(self): """ Reads in crop coefficients. Parameters ---------- name: string Name of the crop Returns ------- ckc: list List of crop coefficients """ try: infile = open(os.path.join(self.directory,'data','scs_crop_coef.csv'),'r') except TypeError: logger_fn.critical('scs_crop_coef.csv file not found.')<|fim▁hole|> if self.crop_type == 'PERENNIAL': end = 26 else: end = 22 for line in lines: sline = line.split(',') sline[-1] = sline[-1][:-1] # print(sline[0],self.sname) if sline[0] == self.sname: vals = [float(item) for item in sline[1:end]] self.ckc = vals break<|fim▁end|>
raise else: lines = infile.readlines() infile.close()
<|file_name|>script-jumping.js<|end_file_name|><|fim▁begin|>(function () { window.onload = function () { var stage, layer, layerBG, ball, constants, onJump, isOver; stage = new Kinetic.Stage({ container: 'kinetic-container', width: document.body.clientWidth, height: document.body.clientHeight }); layer = new Kinetic.Layer(); layerBG = new Kinetic.Layer(); constants = { BALL_X: 25, BALL_Y: stage.getHeight() * 0.75 - 25, BALL_RADIUS: 25, BALL_X_ACCELERATION: 0.1, BALL_X_DECELERATION: 0.15, BALL_Y_ACCELERATION: 0.2, BALL_Y_DECELERATION: 0.25, FUNDAMENTALS_WIDTH: 175, FUNDAMENTALS_HEIGHT: 50, GAME_OVER_IMG: 'https://lh3.googleusercontent.com/-hk3-q7XFs1w/U5105G5F8SI/AAAAAAAAAfQ/OMHmsK6-Dco/zoom_games_18.normal.color_000000.png', IMAGES_SOURCES: ['http://3.bp.blogspot.com/-zt_wXhDvv_Q/VI0u3M65zFI/AAAAAAAAAM0/eQHiw5EuhFI/s1600/apple-logo-black.png', 'http://4.bp.blogspot.com/-kp9dUl08xCA/UODmryuwAYI/AAAAAAAApn4/-nFoS6F0cFE/s1600/AxFoCM-CMAEH868.jpg', 'http://hdw.datawallpaper.com/nature/the-beauty-of-nature-wide-wallpaper-499995.jpg', 'http://cs304304.vk.me/v304304772/59cc/DStHQW-F20A.jpg'] }; window.onkeydown = function(ev){ switch (ev.keyCode) { case 32: if (!onJump) { onJump = true; ball.deltaY = -1; ball.speedY = constants.BALL_Y_ACCELERATION * 50; } break; case 37: if (onJump) { ball.deltaX = -1; ball.speedX += constants.BALL_X_ACCELERATION * 5; } else { ball.deltaX = -1; ball.speedX += constants.BALL_X_ACCELERATION * 10; } break; case 39: if (onJump) { ball.deltaX = 1; ball.speedX += constants.BALL_X_ACCELERATION * 5; } else { ball.deltaX = 1; ball.speedX += constants.BALL_X_ACCELERATION * 10; } break; default: break; } }; function start() { onJump = false; isOver = false; ball = getBall(); for (var i = 0; i < 6; i += 1) { getFundamental(i * 200, stage.getHeight() * 0.75 - i * 100); } getTrophy((i - 1) * 200, stage.getHeight() * 0.75 - (i - 1) * 100 - constants.FUNDAMENTALS_HEIGHT * 2); layer.add(ball); stage.add(layerBG); stage.add(layer); step(); } function step() { // y if (ball.deltaY === 1) { if (checkFundamentals()) { onJump = false; ball.deltaY = 0; ball.speedY = 0; } else if (ball.getY() >= stage.getHeight() - ball.getRadius()) { gameOverText(); gameOverImage(); } } else if (ball.deltaY === -1) { if (ball.getY() <= 0 + ball.getRadius()) { happyEnd(); ball.deltaY = 1; } else if (ball.speedY <= 0) { ball.deltaY = 1; ball.speedY = 0; } } else { if (!checkFundamentals()) { ball.deltaY = 1; } } // x if (ball.deltaX === 1) { if (ball.getX() >= stage.getWidth() - ball.getRadius()) { ball.deltaX = 0; } else if (ball.speedX <= 0) { ball.deltaX = 0; ball.speedX = 0; } } else if (ball.deltaX === -1) { if (ball.getX() <= 0 + ball.getRadius()) { ball.deltaX = 0; } else if (ball.speedX <= 0) { ball.deltaX = 0; ball.speedX = 0; } } moveBall(); layer.draw(); if (!isOver) { requestAnimationFrame(step); } else { window.onkeydown = null; } } function checkFundamentals() { return layerBG.find('Rect').some(function (fundamental) { if (ball.getX() > fundamental.getX() && ball.getX() < fundamental.getX() + fundamental.getWidth() && ball.getY() > fundamental.getY() - ball.getRadius() && ball.getY() <= fundamental.getY() + fundamental.getHeight() - ball.getRadius()) { ball.setY(fundamental.getY() - ball.getRadius()); return true } return false; }); } <|fim▁hole|> } else if (ball.deltaX === -1) { ball.speedX -= ball.decelerationX; } else { ball.speedX = 0; } if (ball.deltaY === 1) { ball.speedY += ball.accelerationY; } else if (ball.deltaY === -1) { ball.speedY -= ball.decelerationY; } else { ball.speedY = 0; } ball.setX(ball.getX() + ball.deltaX * ball.speedX); ball.setY(ball.getY() + ball.deltaY * ball.speedY); } function getBall() { var ball = new Kinetic.Circle({ x: constants.BALL_X, y: constants.BALL_Y, radius: constants.BALL_RADIUS, fill: getRandomColor() }); ball.deltaX = 0; ball.deltaY = 0; ball.speedX = 0; ball.speedY = 0; ball.accelerationX = constants.BALL_X_ACCELERATION; ball.decelerationX = constants.BALL_X_DECELERATION; ball.accelerationY = constants.BALL_Y_ACCELERATION; ball.decelerationY = constants.BALL_Y_DECELERATION; return ball; } function getFundamental(x, y) { layerBG.add(new Kinetic.Rect({ x: x, y: y, width: constants.FUNDAMENTALS_WIDTH, height: constants.FUNDAMENTALS_HEIGHT, fill: 'purple' })); layerBG.draw(); } function getTrophy(x, y) { var canvasImage, kineticImage; canvasImage = new Image(); canvasImage.src = constants.IMAGES_SOURCES[0]; canvasImage.onload = function () { kineticImage = new Kinetic.Image({ x: x, y: y, width: 150, height: 100, image: canvasImage, draggable: true }); layerBG.add(kineticImage); layerBG.draw(); }; } function happyEnd() { var canvasImage, kineticImage; canvasImage = new Image(); canvasImage.src = constants.IMAGES_SOURCES[3]; canvasImage.onload = function () { kineticImage = new Kinetic.Image({ x: 0, y: 0, width: stage.getWidth(), height: stage.getHeight(), image: canvasImage, draggable: true }); layerBG.add(kineticImage); layerBG.draw(); }; isOver = true; } function gameOverText() { var gameOver = 'GAME OVER'; var text = new Kinetic.Text({ x: (stage.getWidth() - gameOver.length * 36) / 2, y: stage.getHeight() / 2, text: gameOver, fontSize: 72, fontFamily: 'Calibri', align: 'center', fill: 'blue' }); layerBG.add(text); layerBG.draw(); isOver = true; } function gameOverImage() { var canvasImage, kineticImage; canvasImage = new Image(); canvasImage.src = constants.GAME_OVER_IMG; canvasImage.onload = function () { kineticImage = new Kinetic.Image({ x: 0, y: 0, width: stage.getWidth(), height: stage.getHeight(), image: canvasImage, draggable: true }); layerBG.add(kineticImage); layerBG.draw(); }; isOver = true; } function getRandomColor() { const COLOR_STRING_LENGTH = 6; const HEXADECIMAL_BASE = 16; const HEXADECIMAL_SIGNS = '0123456789ABCDEF'; var letters = HEXADECIMAL_SIGNS.split(''); var color = '#'; for (var i = 0; i < COLOR_STRING_LENGTH; i += 1) { color += letters[Math.floor(Math.random() * HEXADECIMAL_BASE)]; } return color; } return start(); }; }());<|fim▁end|>
function moveBall() { if (ball.deltaX === 1) { ball.speedX -= ball.decelerationX;
<|file_name|>hashcode_tests.py<|end_file_name|><|fim▁begin|>import unittest from rdflib import URIRef from owlapy import model from owlapy.util.hashcode import HashCode from owlapy.vocab.owlfacet import OWLFacet class TestHashCode(unittest.TestCase): def test_hash_ontology(self): ont_id = model.OWLOntologyID() data_factory = model.OWLDataFactory() man = model.OWLOntologyManager(data_factory) ont = model.OWLOntology(man, ont_id) ont_id_hash = hash(ont_id) self.assertEqual(ont_id_hash, HashCode.hash_code(ont)) def test_asym_obj_prop_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} asym_obj_prop = model.OWLAsymmetricObjectPropertyAxiom(prop, anns) asym_obj_prop_hash = (((3 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(asym_obj_prop_hash, HashCode.hash_code(asym_obj_prop)) def test_cls_assertion_axiom(self): indiv = model.OWLNamedIndividual(model.IRI('http://ex.org/indivXYZ')) ce = model.OWLClass(model.IRI('http://ex.org/SomeCls')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp'))<|fim▁hole|> ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} cls_ass_ax = model.OWLClassAssertionAxiom(indiv, ce, anns) cls_ass_ax_hash = (((((7 * HashCode.MULT) + hash(indiv)) * HashCode.MULT) + hash(ce)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(cls_ass_ax_hash, HashCode.hash_code(cls_ass_ax)) def test_data_prop_assertion_axiom(self): subj = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC')) prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) val = model.OWLLiteral('abcd') ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDataPropertyAssertionAxiom(subj, prop, val, anns) axiom_hash = (((((((11 * HashCode.MULT) + hash(subj)) * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(val)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_data_prop_dom_axiom(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) dom = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDataPropertyDomainAxiom(prop, dom, anns) axiom_hash = (((((13 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(dom)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_data_prop_range_axiom(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) rnge = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDataPropertyRangeAxiom(prop, rnge, anns) axiom_hash = (((((17 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(rnge)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_sub_data_prop_of_axiom(self): sub_prop = model.OWLDataProperty('http://ex.org/subProp') super_prop = model.OWLDataProperty('http://ex.org/superProp') ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLSubDataPropertyOfAxiom(sub_prop, super_prop, anns) axiom_hash = (((((19 * HashCode.MULT) + hash(sub_prop)) * HashCode.MULT) + hash(super_prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_declaration_axiom(self): entity = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDeclarationAxiom(entity, anns) axiom_hash = (((23 * HashCode.MULT) + hash(entity)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_diff_indivs_axiom(self): indiv1 = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC')) indiv2 = model.OWLAnonymousIndividual(model.NodeID('_:23')) indivs = {indiv1, indiv2} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDifferentIndividualsAxiom(indivs, anns) axiom_hash = (((29 * HashCode.MULT) + HashCode._hash_list(indivs)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_disjoint_classes_axiom(self): ce1 = model.OWLClass(model.IRI('http://ex.org/SomeClass')) prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) filler = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) ce2 = model.OWLObjectSomeValuesFrom(prop, filler) ces = {ce1, ce2} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDisjointClassesAxiom(ces, anns) axiom_hash = (((31 * HashCode.MULT) + HashCode._hash_list(ces)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_disjoint_data_props_axiom(self): prop1 = model.OWLDataProperty(model.IRI('http://ex.org/prop1')) prop2 = model.OWLDataProperty(model.IRI('http://ex.org/prop2')) properties = {prop1, prop2} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDisjointDataPropertiesAxiom(properties, anns) axiom_hash = (((37 * HashCode.MULT) + HashCode._hash_list(properties)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_disjoint_obj_props_axiom(self): prop1 = model.OWLObjectProperty(model.IRI('http://ex.org/prop1')) prop2 = model.OWLObjectProperty(model.IRI('http://ex.org/prop2')) prop3 = model.OWLObjectInverseOf(model.IRI('http://ex.org/prop3')) properties = {prop1, prop2, prop3} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDisjointObjectPropertiesAxiom(properties, anns) axiom_hash = (((41 * HashCode.MULT) + HashCode._hash_list(properties)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_disjoint_union_axiom(self): cls = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce1 = model.OWLClass(model.IRI('http://ex.org/SomeClass')) prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) filler = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) ce2 = model.OWLObjectAllValuesFrom(prop, filler) ces = {ce1, ce2} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDisjointUnionAxiom(cls, ces, anns) axiom_hash = (((((43 * HashCode.MULT) + hash(axiom.owl_class)) * HashCode.MULT) + HashCode._hash_list(ces)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_annotation_assertion_axiom(self): subj = model.IRI('http://ex.org/sth') prop = model.OWLAnnotationProperty(model.IRI('http://ex.org/prop')) val = model.OWLLiteral('abcabc') ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLAnnotationAssertionAxiom(subj, prop, val, anns) axiom_hash = (((((((47 * HashCode.MULT) + hash(subj)) * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(val)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_equiv_classes_axiom(self): ce1 = model.OWLClass(model.IRI('http://ex.org/SomeClass')) prop1 = model.OWLObjectProperty(model.IRI('http://ex.org/prop1')) filler1 = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) ce2 = model.OWLObjectSomeValuesFrom(prop1, filler1) prop2 = model.OWLObjectProperty(model.IRI('http://ex.org/prop2')) filler2 = model.OWLClass(model.IRI('http://ex.org/YetAnotherClass')) ce3 = model.OWLObjectAllValuesFrom(prop2, filler2) classes = {ce1, ce2, ce3} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLEquivalentClassesAxiom(classes, anns) axiom_hash = (((53 * HashCode.MULT) + HashCode._hash_list(classes)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_equiv_data_prop_axiom(self): prop1 = model.OWLDataProperty(model.IRI('http://ex.org/prop1')) prop2 = model.OWLDataProperty(model.IRI('http://ex.org/prop2')) properties = {prop1, prop2} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLEquivalentDataPropertiesAxiom(properties, anns) axiom_hash = (((59 * HashCode.MULT) + HashCode._hash_list(properties)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_equiv_obj_prop_axiom(self): prop1 = model.OWLObjectProperty(model.IRI('http://ex.org/prop1')) prop2 = model.OWLObjectProperty(model.IRI('http://ex.org/prop2')) properties = {prop1, prop2} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLEquivalentObjectPropertiesAxiom(properties, anns) axiom_hash = (((61 * HashCode.MULT) + HashCode._hash_list(properties)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_functional_data_prop_axiom(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) rnge = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLFunctionalDataPropertyAxiom(prop, rnge, anns) axiom_hash = (((67 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_functional_obj_prop_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLFunctionalObjectPropertyAxiom(prop, anns) axiom_hash = (((71 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_inv_functional_obj_prop_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLInverseFunctionalObjectPropertyAxiom(prop, anns) axiom_hash = (((79 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_inv_obj_props_axiom(self): prop1 = model.OWLObjectProperty(model.IRI('http://ex.org/prop1')) prop2 = model.OWLObjectProperty(model.IRI('http://ex.org/prop2')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLInverseObjectPropertiesAxiom(prop1, prop2, anns) axiom_hash = (((83 * HashCode.MULT) + hash(prop1) + hash(prop2)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_irrefl_obj_prop_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLIrreflexiveObjectPropertyAxiom(prop, anns) axiom_hash = (((89 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_negative_data_prop_assertion_axiom(self): subj = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC')) prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) obj = model.OWLLiteral('acab') ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLNegativeDataPropertyAssertionAxiom( subj, prop, obj, anns) axiom_hash = (((((((97 * HashCode.MULT) + hash(subj)) * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(obj)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_negative_obj_prop_assertion_axiom(self): subj = model.OWLNamedIndividual(model.IRI('http://ex.org/indivXYZ')) prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) obj = model.OWLAnonymousIndividual(model.NodeID('_:23')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLNegativeObjectPropertyAssertionAxiom( subj, prop, obj, anns) axiom_hash = (((((((101 * HashCode.MULT) + hash(subj)) * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(obj)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_obj_prop_assertion_axiom(self): subj = model.OWLAnonymousIndividual(model.NodeID('_:23')) prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) obj = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLObjectPropertyAssertionAxiom(subj, prop, obj, anns) axiom_hash = (((((((103 * HashCode.MULT) + hash(subj)) * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(obj)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_sub_prop_chain_of_axiom(self): prop1 = model.OWLObjectProperty(model.IRI('http://ex.org/prop1')) prop2 = model.OWLObjectProperty(model.IRI('http://ex.org/prop2')) prop3 = model.OWLObjectProperty(model.IRI('http://ex.org/prop3')) prop_chain = [prop1, prop2, prop3] super_prop = model.OWLObjectProperty(model.IRI('http://ex.org/sProp')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLSubPropertyChainOfAxiom(prop_chain, super_prop, anns) axiom_hash = (((((107 * HashCode.MULT) + HashCode._hash_list(prop_chain)) * HashCode.MULT) + hash(super_prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_obj_prop_dom_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) cls1 = model.OWLClass(model.IRI('http://ex.org/SomeCls')) cls2 = model.OWLClass(model.IRI('http://ex.org/AnotherCls')) operands = {cls1, cls2} dom = model.OWLObjectUnionOf(operands) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLObjectPropertyDomainAxiom(prop, dom, anns) axiom_hash = (((((109 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(dom)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_obj_prop_range_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) rnge = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLObjectPropertyRangeAxiom(prop, rnge, anns) axiom_hash = (((((113 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + hash(rnge)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_sub_obj_prop_of_axiom(self): sub_prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop1')) super_prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop2')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLSubObjectPropertyOfAxiom(sub_prop, super_prop, anns) axiom_hash = (((((127 * HashCode.MULT) + hash(sub_prop)) * HashCode.MULT) + hash(super_prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_refl_obj_prop_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLReflexiveObjectPropertyAxiom(prop, anns) axiom_hash = (((131 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_same_indiv_axiom(self): indiv1 = model.OWLAnonymousIndividual(model.NodeID('_:23')) indiv2 = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC')) indivs = {indiv1, indiv2} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLSameIndividualAxiom(indivs, anns) axiom_hash = (((137 * HashCode.MULT) + HashCode._hash_list(indivs)) * HashCode.MULT) + HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_sub_cls_of_axiom(self): sub_cls = model.OWLClass(model.IRI('http://ex.org/SomeClass')) cls1 = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) cls2 = model.OWLClass(model.IRI('http://ex.org/YetAnotherClass')) operands = {cls1, cls2} super_cls = model.OWLObjectIntersectionOf(operands) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLSubClassOfAxiom(sub_cls, super_cls, anns) axiom_hash = (((((139 * HashCode.MULT) + hash(sub_cls)) * HashCode.MULT) + hash(super_cls)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_symm_obj_prop_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/property')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLSymmetricObjectPropertyAxiom(prop, anns) axiom_hash = (((149 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_trans_obj_prop_axiom(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLTransitiveObjectPropertyAxiom(prop, anns) axiom_hash = (((151 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ HashCode._hash_list(anns) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_cls(self): iri = model.IRI('http://ex.org/SomeCls') cls = model.OWLClass(iri) cls_hash = (157 * HashCode.MULT) + hash(iri) self.assertEqual(cls_hash, HashCode.hash_code(cls)) def test_data_all_vals_from(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) filler = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) ce = model.OWLDataAllValuesFrom(prop, filler) ce_hash = (((163 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_data_exact_cardinality(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) card = 5 filler = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) ce = model.OWLDataExactCardinality(prop, card, filler) ce_hash = (((((167 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + card) * HashCode.MULT) + hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_data_max_cardinality(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) card = 23 filler = model.OWLDatatype(model.IRI('http://ex.org/dtype/str')) ce = model.OWLDataMaxCardinality(prop, card, filler) ce_hash = (((((173 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + card) * HashCode.MULT) + hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_data_min_cardinality(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) card = 5 filler = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) ce = model.OWLDataMinCardinality(prop, card, filler) ce_hash = (((((179 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + card) * HashCode.MULT) + hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_data_some_vals_from(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) filler = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) ce = model.OWLDataSomeValuesFrom(prop, filler) ce_hash = (((181 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_data_has_val(self): prop = model.OWLDataProperty(model.IRI('http://ex.org/prop')) val = model.OWLLiteral('abc') ce = model.OWLDataHasValue(prop, val) ce_hash = (((191 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(val) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_all_vals_from(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/property')) ce1 = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce2 = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) operands = {ce1, ce2} filler = model.OWLObjectUnionOf(operands) ce = model.OWLObjectAllValuesFrom(prop, filler) ce_hash = (((193 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_complement_of(self): operand = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce = model.OWLObjectComplementOf(operand) ce_hash = (197 * HashCode.MULT) + hash(operand) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_exact_cardinality(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) card = 5 cls1 = model.OWLClass(model.IRI('http://ex.org/SomeClass')) cls2 = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) operands = {cls1, cls2} filler = model.OWLObjectUnionOf(operands) ce = model.OWLObjectExactCardinality(prop, card, filler) ce_hash = (((((199 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + card) * HashCode.MULT) + hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_intersect_of(self): ce1 = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce2 = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) ce3 = model.OWLClass(model.IRI('http://ex.org/YetAnotherClass')) operands = {ce1, ce2, ce3} ce = model.OWLObjectIntersectionOf(operands) ce_hash = (211 * HashCode.MULT) + HashCode._hash_list(operands) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_max_cardinality(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) card = 5 filler = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce = model.OWLObjectMaxCardinality(prop, card, filler) ce_hash = (((((223 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + card) * HashCode.MULT) + hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_min_cardinality(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) card = 25 filler = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce = model.OWLObjectMinCardinality(prop, card, filler) ce_hash = (((((227 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + card) * HashCode.MULT) + hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_one_of(self): indiv1 = model.OWLNamedIndividual(model.IRI('http://ex.org/indivXYZ')) indiv2 = model.OWLAnonymousIndividual(model.NodeID('_:23')) values = {indiv1, indiv2} ce = model.OWLObjectOneOf(values) ce_hash = (229 * HashCode.MULT) + HashCode._hash_list(values) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_has_self(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) ce = model.OWLObjectHasSelf(prop) ce_hash = (233 * HashCode.MULT) + hash(prop) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_some_val_from(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) filler = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce = model.OWLObjectSomeValuesFrom(prop, filler) ce_hash = (((239 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(filler) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_union_of(self): ce1 = model.OWLClass(model.IRI('http://ex.org/SomeClass')) ce2 = model.OWLClass(model.IRI('http://ex.org/AnotherClass')) ce3 = model.OWLClass(model.IRI('http://ex.org/YetAnotherClass')) operands = {ce1, ce2, ce3} ce = model.OWLObjectUnionOf(operands) ce_hash = (241 * HashCode.MULT) + HashCode._hash_list(operands) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_obj_has_val(self): prop = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) val = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC')) ce = model.OWLObjectHasValue(prop, val) ce_hash = (((251 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(val) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_data_complement_of(self): rnge = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) ce = model.OWLDataComplementOf(rnge) ce_hash = (257 * HashCode.MULT) + hash(rnge) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_data_one_of(self): val1 = model.OWLLiteral('abc') val2 = model.OWLLiteral('def') val3 = model.OWLLiteral('ghi') values = {val1, val2, val3} ce = model.OWLDataOneOf(values) ce_hash = (263 * HashCode.MULT) + HashCode._hash_list(values) self.assertEqual(ce_hash, HashCode.hash_code(ce)) def test_datatype(self): iri = model.IRI('http://ex.org/dtype/int') dtype = model.OWLDatatype(iri) dtype_hash = (269 * HashCode.MULT) + hash(iri) self.assertEqual(dtype_hash, HashCode.hash_code(dtype)) def test_datatype_restr(self): dtype = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) facet1 = OWLFacet.LENGTH facet_val1 = model.OWLLiteral('23') fr1 = model.OWLFacetRestriction(facet1, facet_val1) facet2 = OWLFacet.MAX_EXCLUSIVE facet_value2 = model.OWLLiteral('5') fr2 = model.OWLFacetRestriction(facet2, facet_value2) facet_restrictions = {fr1, fr2} node = model.OWLDatatypeRestriction(dtype, facet_restrictions) node_hash = (((271 * HashCode.MULT) + hash(dtype)) * HashCode.MULT) + \ HashCode._hash_list(facet_restrictions) self.assertEqual(node_hash, HashCode.hash_code(node)) def test_facet_restr(self): facet = OWLFacet.LENGTH facet_val = model.OWLLiteral('23') node = model.OWLFacetRestriction(facet, facet_val) node_hash = (((563 * HashCode.MULT) + hash(facet)) * HashCode.MULT) + \ hash(facet_val) self.assertEqual(node_hash, HashCode.hash_code(node)) def test_literal(self): literal = model.OWLLiteral('abc') self.assertEqual(hash(literal), HashCode.hash_code(literal)) def test_data_prop(self): iri = model.IRI('http://ex.org/dprop') prop = model.OWLDataProperty(iri) prop_hash = (283 * HashCode.MULT) + hash(iri) self.assertEqual(prop_hash, HashCode.hash_code(prop)) def test_object_prop(self): iri = model.IRI('http://ex.org/prop') prop = model.OWLObjectProperty(iri) prop_hash = (293 * HashCode.MULT) + hash(iri) self.assertEqual(prop_hash, HashCode.hash_code(prop)) def test_obj_inv_of(self): inv_prop = model.OWLObjectProperty(model.IRI('http://ex.org/iProp')) prop = model.OWLObjectInverseOf(inv_prop) prop_hash = (307 * HashCode.MULT) + hash(inv_prop) self.assertEqual(prop_hash, HashCode.hash_code(prop)) def test_named_indiv(self): iri = model.IRI('http://ex.org/indivABC') indiv = model.OWLNamedIndividual(iri) indiv_hash = (311 * HashCode.MULT) + hash(iri) self.assertEqual(indiv_hash, HashCode.hash_code(indiv)) def test_swrl_rule(self): pred1 = model.OWLDataProperty(model.IRI('http://ex.org/prop1')) b_arg0 = model.SWRLLiteralArgument(model.OWLLiteral('abc')) b_arg1 = model.SWRLLiteralArgument(model.OWLLiteral('def')) body = model.SWRLDataPropertyAtom(pred1, b_arg0, b_arg1) pred2 = model.OWLDataProperty(model.IRI('http://ex.org/prop2')) h_arg0 = model.SWRLLiteralArgument(model.OWLLiteral('23')) h_arg1 = model.SWRLLiteralArgument(model.OWLLiteral('42')) head = model.SWRLDataPropertyAtom(pred2, h_arg0, h_arg1) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} rule = model.SWRLRule(body, head, anns) rule_hash = (((631 * HashCode.MULT) + hash(body)) * HashCode.MULT) +\ hash(head) self.assertEqual(rule_hash, HashCode.hash_code(rule)) def test_swrl_cls_atom(self): pred = model.OWLClass(model.IRI('http://ex.org/SomeClass')) indiv = model.OWLNamedIndividual(model.IRI('http://ex.org/indivXYZ')) arg = model.SWRLIndividualArgument(indiv) atom = model.SWRLClassAtom(pred, arg) atom_hash = (((641 * HashCode.MULT) + hash(arg)) * HashCode.MULT) + \ hash(pred) self.assertEqual(atom_hash, HashCode.hash_code(atom)) def test_srwl_data_range_atom(self): pred = model.OWLDatatype(model.IRI('http://ex.org/SomeClass')) literal = model.OWLLiteral('foo') arg = model.SWRLLiteralArgument(literal) atom = model.SWRLDataRangeAtom(pred, arg) atom_hash = (((643 * HashCode.MULT) + hash(arg)) * HashCode.MULT) + \ hash(pred) self.assertEqual(atom_hash, HashCode.hash_code(atom)) def test_swrl_obj_prop_atom(self): pred = model.OWLObjectProperty(model.IRI('http://ex.org/prop')) indiv0 = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC')) arg0 = model.SWRLIndividualArgument(indiv0) indiv1 = model.OWLAnonymousIndividual(model.NodeID('_:23')) arg1 = model.SWRLIndividualArgument(indiv1) atom = model.SWRLObjectPropertyAtom(pred, arg0, arg1) atom_hash = (((((647 * HashCode.MULT) + hash(arg0)) * HashCode.MULT) + hash(arg1)) * HashCode.MULT) + hash(pred) self.assertEqual(atom_hash, HashCode.hash_code(atom)) def test_swrl_data_prop_atom(self): pred = model.OWLDataProperty(model.IRI('http://ex.org/prop')) arg0 = model.SWRLLiteralArgument(model.OWLLiteral('abc')) arg1 = model.SWRLLiteralArgument(model.OWLLiteral('def')) atom = model.SWRLDataPropertyAtom(pred, arg0, arg1) atom_hash = (((((653 * HashCode.MULT) + hash(arg0)) * HashCode.MULT) + hash(arg1)) * HashCode.MULT) + hash(pred) self.assertEqual(atom_hash, HashCode.hash_code(atom)) def test_swrl_built_in_atom(self): pred = model.IRI('http://ex.org/sth') arg1 = model.SWRLLiteralArgument(model.OWLLiteral('abc')) arg2 = model.SWRLLiteralArgument(model.OWLLiteral('def')) arg3 = model.SWRLLiteralArgument(model.OWLLiteral('ghi')) args = [arg1, arg2, arg3] atom = model.SWRLBuiltInAtom(pred, args) atom_hash = (((659 * HashCode.MULT) + HashCode._hash_list(args)) * HashCode.MULT) + hash(pred) self.assertEqual(atom_hash, HashCode.hash_code(atom)) def test_swrl_variable(self): iri = model.IRI('http://ex.org/sth') var = model.SWRLVariable(iri) var_hash = (661 * HashCode.MULT) + hash(iri) self.assertEqual(var_hash, HashCode.hash_code(var)) def test_swrl_indiv_arg(self): indiv = model.OWLNamedIndividual(model.IRI('http://ex.org/indivXYZ')) arg = model.SWRLIndividualArgument(indiv) arg_hash = (677 * HashCode.MULT) + hash(indiv) self.assertEqual(arg_hash, HashCode.hash_code(arg)) def test_swrl_literal_arg(self): literal = model.OWLLiteral('abc') arg = model.SWRLLiteralArgument(literal) arg_hash = (683 * HashCode.MULT) + hash(literal) self.assertEqual(arg_hash, HashCode.hash_code(arg)) def test_swrl_diff_indivs_atom(self): data_factory = model.OWLDataFactory() indiv0 = model.OWLNamedIndividual(model.IRI('http://ex.org/indivXYZ')) arg0 = model.SWRLIndividualArgument(indiv0) indiv1 = model.OWLAnonymousIndividual(model.NodeID('_:23')) arg1 = model.SWRLIndividualArgument(indiv1) atom = model.SWRLDifferentIndividualsAtom(data_factory, arg0, arg1) atom_hash = (((797 * HashCode.MULT) + hash(arg0)) * HashCode.MULT) + \ hash(arg1) self.assertEqual(atom_hash, HashCode.hash_code(atom)) def test_swrl_same_indivs_atom(self): data_factory = model.OWLDataFactory() indiv0 = model.OWLNamedIndividual(model.IRI('http://ex.org/indivXYZ')) arg0 = model.SWRLIndividualArgument(indiv0) indiv1 = model.OWLAnonymousIndividual(model.NodeID('_:23')) arg1 = model.SWRLIndividualArgument(indiv1) atom = model.SWRLSameIndividualAtom(data_factory, arg0, arg1) atom_hash = (((811 * HashCode.MULT) + hash(arg0)) * HashCode.MULT) + \ hash(arg1) self.assertEqual(atom_hash, HashCode.hash_code(atom)) def test_has_key_axiom(self): ce = model.OWLClass(model.IRI('http://ex.org/SomeClass')) pe1 = model.OWLObjectProperty(model.IRI('http://ex.org/prop1')) pe2 = model.OWLObjectInverseOf( model.OWLObjectProperty(model.IRI('http://ex.org/prop2'))) pe3 = model.OWLObjectProperty(model.IRI('http://ex.org/prop3')) pes = {pe1, pe2, pe3} ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLHasKeyAxiom(ce, pes, anns) axiom_hash = (((821 * HashCode.MULT) + hash(ce)) * HashCode.MULT) + \ HashCode._hash_list(pes) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_ann_prop_dom_axiom(self): prop = model.OWLAnnotationProperty('http://ex.org/prop') dom = model.IRI('http://ex.org/sth') ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLAnnotationPropertyDomainAxiom(prop, dom, anns) axiom_hash = (((823 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(dom) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test__owl_ann_prop_range_axiom(self): prop = model.OWLAnnotationProperty('http://ex.org/prop') rnge = model.IRI('http://ex.org/sth') ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLAnnotationPropertyRangeAxiom(prop, rnge, anns) axiom_hash = (((827 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(rnge) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_sub_ann_prop_of_axiom(self): sub_prop = model.OWLAnnotationProperty(model.IRI('http://ex.org/prop1')) super_prop = model.OWLAnnotationProperty( model.IRI('http://ex.org/prop2')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLSubAnnotationPropertyOfAxiom( sub_prop, super_prop, anns) axiom_hash = (((829 * HashCode.MULT) + hash(sub_prop)) * HashCode.MULT) + hash(super_prop) self.assertEqual(axiom_hash, HashCode.hash_code(axiom)) def test_data_intersect_of(self): dtype1 = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) dtype2 = model.OWLDatatype(model.IRI('http://ex.org/dtype/float')) operands = {dtype1, dtype2} node = model.OWLDataIntersectionOf(operands) node_hash = (839 * HashCode.MULT) + HashCode._hash_list(operands) self.assertEqual(node_hash, HashCode.hash_code(node)) def test_data_union_of(self): dtype1 = model.OWLDatatype(model.IRI('http://ex.org/dtype/int')) dtype2 = model.OWLDatatype(model.IRI('http://ex.org/dtype/float')) operands = {dtype1, dtype2} node = model.OWLDataUnionOf(operands) node_hash = (853 * HashCode.MULT) + HashCode._hash_list(operands) self.assertEqual(node_hash, HashCode.hash_code(node)) def test_annotation_prop(self): prop = model.OWLAnnotationProperty(model.IRI('http://ex.org/anProp')) prop_hash = (857 * HashCode.MULT) + hash(prop.iri) self.assertEqual(prop_hash, HashCode.hash_code(prop)) def test_anon_indiv(self): node_id = model.NodeID('_:23') indiv = model.OWLAnonymousIndividual(node_id) indiv_hash = (859 * HashCode.MULT) + hash(node_id) self.assertEqual(indiv_hash, HashCode.hash_code(indiv)) def test_iri(self): uri = URIRef('http//ex.org/some/uri') iri = model.IRI(uri) iri_hash = (863 * HashCode.MULT) + hash(uri) self.assertEqual(iri_hash, HashCode.hash_code(iri)) # TOOD: the test below fails... think about this! # self.assertEqual(iri_hash, hash(iri)) def test_annotation(self): prop = model.OWLAnnotationProperty(model.IRI('http://ex.org/anProp')) val = model.OWLLiteral('annotation') ann = model.OWLAnnotation(prop, val, []) ann_hash = (((877 * HashCode.MULT) + hash(prop)) * HashCode.MULT) + \ hash(val) self.assertEqual(ann_hash, HashCode.hash_code(ann)) def test_datatype_definition_axiom(self): dtype = model.OWLDatatype(model.IRI('http://ex.org/dtype/posInt')) drange = model.OWLDataComplementOf( model.IRI('http://ex.org/dtype/negInt')) ann_prop1 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp')) ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, []) ann_prop2 = model.OWLAnnotationProperty( model.IRI('http://ex.org/anProp2')) ann_val2 = model.OWLLiteral('annotation 2') ann2 = model.OWLAnnotation(ann_prop2, ann_val2, []) anns = {ann1, ann2} axiom = model.OWLDatatypeDefinitionAxiom(dtype, drange, anns) axiom_hash = (((897 * HashCode.MULT) + hash(dtype)) * HashCode.MULT) + \ hash(drange) self.assertEqual(axiom_hash, HashCode.hash_code(axiom))<|fim▁end|>
ann_val1 = model.OWLLiteral('annotation 1') ann1 = model.OWLAnnotation(ann_prop1, ann_val1, [])
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events<|fim▁hole|> return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return<|fim▁end|>
def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']]
<|file_name|>schema-validation.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as SchemaValidator from 'z-schema'; import { parseJsonPointer } from '../ref/jsonpath'; import { ReadUri, ResolveUri } from '../ref/uri'; import { QuickDataSource } from '../data-store/data-store'; import { Parse } from '../ref/yaml'; import { CreatePerFilePlugin, PipelinePlugin } from "./common"; import { Channel } from "../message"; import { OperationAbortedException } from '../exception'; export function GetPlugin_SchemaValidator(): PipelinePlugin { const validator = new SchemaValidator({ breakOnFirstError: false }); const extendedSwaggerSchema = require("./swagger-extensions.json"); (validator as any).setRemoteReference("http://json.schemastore.org/swagger-2.0", require("./swagger.json")); (validator as any).setRemoteReference("https://raw.githubusercontent.com/Azure/autorest/master/schema/example-schema.json", require("./example-schema.json")); return CreatePerFilePlugin(async config => async (fileIn, sink) => { const obj = fileIn.ReadObject<any>(); const errors = await new Promise<{ code: string, params: string[], message: string, path: string }[] | null>(res => validator.validate(obj, extendedSwaggerSchema, (err, valid) => res(valid ? null : err))); if (errors !== null) { for (const error of errors) { config.Message({ Channel: Channel.Error, Details: error, Plugin: "schema-validator", Source: [{ document: fileIn.key, Position: { path: parseJsonPointer(error.path) } as any }], Text: `Schema violation: ${error.message}` });<|fim▁hole|> }); }<|fim▁end|>
} throw new OperationAbortedException(); } return await sink.Forward(fileIn.Description, fileIn);
<|file_name|>WavpackContext.java<|end_file_name|><|fim▁begin|>package com.wavpack.decoder; import java.io.RandomAccessFile; /* ** WavpackContext.java ** ** Copyright (c) 2007 - 2008 Peter McQuillan ** ** All Rights Reserved. ** ** Distributed under the BSD Software License (see license.txt) ** */ public class WavpackContext { WavpackConfig config = new WavpackConfig(); WavpackStream stream = new WavpackStream(); byte read_buffer[] = new byte[65536]; // was uchar in C int[] temp_buffer = new int[Defines.SAMPLE_BUFFER_SIZE]; int[] temp_buffer2 = new int[Defines.SAMPLE_BUFFER_SIZE]; String error_message = ""; boolean error; RandomAccessFile infile; long total_samples, crc_errors, first_flags; // was uint32_t in C int open_flags, norm_offset; int reduced_channels = 0; int lossy_blocks; int status = 0; // 0 ok, 1 error <|fim▁hole|> } public String getErrorMessage() { return error_message; } }<|fim▁end|>
public boolean isError() { return error;
<|file_name|>metricsPlugin.ts<|end_file_name|><|fim▁begin|>/// /// Copyright 2015 Red Hat, Inc. and/or its affiliates /// and other contributors as indicated by the @author tags. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// <reference path='../../includes.ts'/> /// <reference path='metricsGlobals.ts'/> module HawkularMetrics { export let _module = angular.module(HawkularMetrics.pluginName, ['ngResource', 'ngAnimate', 'ui.select', 'hawkular.services', 'ui.bootstrap', 'topbar', 'patternfly.select', 'angular-momentjs', 'angular-md5', 'toastr', 'infinite-scroll', 'mgo-angular-wizard', 'truncate', '500tech.smart-truncate', 'hawkular.charts', 'ngClipboard']); _module.config(['$compileProvider', function ($compileProvider) { //disable debug info //NOTE: tools like Batarang and Protractor may not work properly with this debug info off //However, this can be turned back on at runtime in the js console by typing: angular.reloadWithDebugInfo() $compileProvider.debugInfoEnabled(false); }]); _module.config(['$httpProvider', '$locationProvider', '$routeProvider', ($httpProvider, $locationProvider) => { $locationProvider.html5Mode(true); }]); _module.config(['$routeProvider', ($routeProvider) => { $routeProvider. when('/metrics/response-time', { templateUrl: 'plugins/metrics/html/url-response-time.html', resolve: { hkResourceList: ($route, $filter, $location, $rootScope, $q, HawkularInventory) => { let idParts = $route.current.params.resourceId.split('~'); let feedId = idParts[0]; let resPromise = HawkularInventory.ResourceUnderFeed.query({ environmentId: globalEnvironmentId, feedId: feedId }).$promise; resPromise.then((hkResourceList) => { $location.path('/metrics/response-time/' + hkResourceList[0].id); }, () => { $location.url('/error'); }); // Returning a promise which would never be resolved, so that the page would not render. // The page will be redirected before rendering based on the resource list loaded above. return $q.defer().promise; } } }).when('/hawkular-ui/url/url-list', {templateUrl: 'plugins/metrics/html/url-list.html'}). when('/hawkular-ui/url/response-time/:resourceId/:timeOffset?/:endTime?', { templateUrl: 'plugins/metrics/html/url-response-time.html', reloadOnSearch: false, resolve: { resource: ($route, $location, HawkularInventory, NotificationsService:INotificationsService) => { let p = HawkularInventory.Resource.get({ environmentId: globalEnvironmentId, resourcePath: $route.current.params.resourceId }).$promise; p.then((response:any) => { return response.properties.url; }, (error) => { NotificationsService.info('You were redirected to this page because you requested an invalid URL.'); $location.path('/'); }); return p; } } }). when('/hawkular-ui/url/availability/:resourceId/:timeOffset?/:endTime?', { templateUrl: 'plugins/metrics/html/url-availability.html', reloadOnSearch: false, resolve: { resource: ($route, $location, HawkularInventory, NotificationsService:INotificationsService) => { let p = HawkularInventory.Resource.get({ environmentId: globalEnvironmentId, resourcePath: $route.current.params.resourceId }).$promise; p.then((response:any) => { return response.properties.url; }, (error) => { NotificationsService.info('You were redirected to this page because you requested an invalid URL.'); $location.path('/'); }); return p; } } }). when('/hawkular-ui/url/alerts/:resourceId/:timeOffset?/:endTime?', { templateUrl: 'plugins/metrics/html/url-alerts.html', reloadOnSearch: false, resolve: { resource: ($route, $location, HawkularInventory, NotificationsService:INotificationsService) => { let p = HawkularInventory.Resource.get({ environmentId: globalEnvironmentId, resourcePath: $route.current.params.resourceId }).$promise; p.then((response:any) => { return response.properties.url; }, (error) => { NotificationsService.info('You were redirected to this page because you requested an invalid URL.'); $location.path('/'); }); return p; } } }). when('/hawkular-ui/app/app-list', {templateUrl: 'plugins/metrics/html/app-server-list.html'}). when('/hawkular-ui/app/app-details/:resourceId/:tabId/:timeOffset?/:endTime?', { templateUrl: 'plugins/metrics/html/app-details/app-server-details.html', reloadOnSearch: false, resolve: { resource: ($route, $location, HawkularInventory, NotificationsService:INotificationsService) => { let redirectMissingAppServer = () => { NotificationsService.info('You were redirected to this page because you requested an invalid ' + 'Application Server.'); $location.path('/hawkular-ui/app/app-list'); }; let checkAppServerExists = () => { let idParts = $route.current.params.resourceId.split('~'); if (idParts.length !== 2) { redirectMissingAppServer(); return; } let p = HawkularInventory.ResourceUnderFeed.get({ environmentId: globalEnvironmentId, feedId: idParts[0], resourcePath: $route.current.params.resourceId + '~~' }).$promise; p.then((response) => { return response; }, (error) => redirectMissingAppServer() ); return p; }; return checkAppServerExists(); } } }). when('/hawkular-ui/alerts-center/:timeOffset?/:endTime?', { templateUrl: 'plugins/metrics/html/alerts-center-list.html', controller: 'AlertsCenterController', controllerAs: 'ac' }). when('/hawkular-ui/alerts-center-detail/:alertId/:timeOffset?/:endTime?', { templateUrl: 'plugins/metrics/html/alerts-center-detail.html', controller: 'AlertsCenterDetailsController', controllerAs: 'acd' }). when('/hawkular-ui/alerts-center-triggers/:resourceId?', { templateUrl: 'plugins/metrics/html/alerts-center-triggers.html', controller: 'AlertsCenterTriggerController', controllerAs: 'act' }). when('/hawkular-ui/alerts-center-triggers/availability/:triggerId', { templateUrl: 'plugins/metrics/html/triggers/availability.html', controller: 'AvailabilityTriggerSetupController', controllerAs: 'tc' }). when('/hawkular-ui/alerts-center-triggers/range/:triggerId', { templateUrl: 'plugins/metrics/html/triggers/range.html', controller: 'RangeTriggerSetupController', controllerAs: 'tc' }). when('/hawkular-ui/alerts-center-triggers/range-percent/:triggerId', { templateUrl: 'plugins/metrics/html/triggers/range-percent.html', controller: 'RangeByPercentTriggerSetupController', controllerAs: 'tc' }). when('/hawkular-ui/alerts-center-triggers/threshold/:triggerId', {<|fim▁hole|> templateUrl: 'plugins/metrics/html/triggers/threshold.html', controller: 'ThresholdTriggerSetupController', controllerAs: 'tc' }). when('/hawkular-ui/agent-installer/view', {templateUrl: 'plugins/metrics/html/agent-installer.html'}). otherwise({redirectTo: '/hawkular-ui/app/app-list'}); }]); // so the same scroll doesn't trigger multiple times angular.module('infinite-scroll').value('THROTTLE_MILLISECONDS', 250); hawtioPluginLoader.addModule(HawkularMetrics.pluginName); }<|fim▁end|>
<|file_name|>DlgPrefsTechDrawDimensionsImp.cpp<|end_file_name|><|fim▁begin|>/*************************************************************************** * Copyright (c) 2015 FreeCAD Developers * * Author: WandererFan <[email protected]> * * Based on src/Mod/FEM/Gui/DlgSettingsFEMImp.cpp * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #include <App/Application.h> #include <Base/Parameter.h> #include <Base/Console.h> #include "DrawGuiUtil.h" #include "PreferencesGui.h" #include "DlgPrefsTechDrawDimensionsImp.h" #include "ui_DlgPrefsTechDrawDimensions.h" using namespace TechDrawGui; using namespace TechDraw; DlgPrefsTechDrawDimensionsImp::DlgPrefsTechDrawDimensionsImp( QWidget* parent ) : PreferencePage( parent ) , ui(new Ui_DlgPrefsTechDrawDimensionsImp) { ui->setupUi(this); ui->plsb_FontSize->setUnit(Base::Unit::Length); ui->plsb_FontSize->setMinimum(0); ui->plsb_ArrowSize->setUnit(Base::Unit::Length); ui->plsb_ArrowSize->setMinimum(0); } DlgPrefsTechDrawDimensionsImp::~DlgPrefsTechDrawDimensionsImp() { // no need to delete child widgets, Qt does it all for us } void DlgPrefsTechDrawDimensionsImp::saveSettings() { ui->pcbStandardAndStyle->onSave(); ui->cbGlobalDecimals->onSave(); ui->cbShowUnits->onSave(); ui->sbAltDecimals->onSave(); ui->plsb_FontSize->onSave(); ui->pdsbToleranceScale->onSave(); ui->leDiameter->onSave(); ui->pcbArrow->onSave(); ui->plsb_ArrowSize->onSave(); } void DlgPrefsTechDrawDimensionsImp::loadSettings() { //set defaults for Quantity widgets if property not found //Quantity widgets do not use preset value since they are based on //QAbstractSpinBox double fontDefault = Preferences::dimFontSizeMM(); ui->plsb_FontSize->setValue(fontDefault); // double arrowDefault = 5.0; // plsb_ArrowSize->setValue(arrowDefault); ui->plsb_ArrowSize->setValue(fontDefault); ui->pcbStandardAndStyle->onRestore(); ui->cbGlobalDecimals->onRestore(); ui->cbShowUnits->onRestore(); ui->sbAltDecimals->onRestore(); ui->plsb_FontSize->onRestore(); ui->pdsbToleranceScale->onRestore(); ui->leDiameter->onRestore(); ui->pcbArrow->onRestore(); ui->plsb_ArrowSize->onRestore(); DrawGuiUtil::loadArrowBox(ui->pcbArrow);<|fim▁hole|> ui->pcbArrow->setCurrentIndex(prefArrowStyle()); } /** * Sets the strings of the subwidgets using the current language. */ void DlgPrefsTechDrawDimensionsImp::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { saveSettings(); ui->retranslateUi(this); loadSettings(); } else { QWidget::changeEvent(e); } } int DlgPrefsTechDrawDimensionsImp::prefArrowStyle(void) const { return PreferencesGui::dimArrowStyle(); } #include <Mod/TechDraw/Gui/moc_DlgPrefsTechDrawDimensionsImp.cpp><|fim▁end|>
<|file_name|>packet_jsmall_scanner.cpp<|end_file_name|><|fim▁begin|>/*************************************************************************** * Copyright (C) 2007, Sly Technologies, Inc * * Distributed under the Lesser GNU Public License (LGPL) * ***************************************************************************/ /* * Utility file that provides various conversion methods for chaging objects * back and forth between C and Java JNI. */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <pcap.h> #include <jni.h> #ifndef WIN32 #include <errno.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <unistd.h> #endif /*WIN32*/ #include "packet_jscanner.h" #include "packet_protocol.h" #include "jnetpcap_utils.h" #include "nio_jmemory.h" #include "nio_jbuffer.h" #include "org_jnetpcap_protocol_JProtocol.h" #include "org_jnetpcap_nio_JMemoryReference.h" #include "org_jnetpcap_packet_JScanner.h" #include "org_jnetpcap_packet_JScannerReference.h" #include "export.h" #include "util_debug.h" //#define DEBUG /**************************************************************** * ************************************************************** * * NON Java declared native functions. Private scan function * * ************************************************************** ****************************************************************/ char str_buf[1024]; char id_str_buf[256]; /***** * Temporarily backout of C++ Debug class and g++ compiler * Debug scanner_logger("jscanner"); Debug protocol_logger("jprotocol", &scanner_logger); ************/ <|fim▁hole|> "id=%s prefix=%-3d header=%-3d gap=%-3d payload=%-3d post=%-3d", id2str(header->hdr_id), header->hdr_prefix, header->hdr_length, header->hdr_gap, header->hdr_payload, header->hdr_postfix); } void debug_scan(char *msg, scan_t *scan) { debug_trace(msg, "id=%s off=%d prefix=%-3d header=%-3d gap=%-3d payload=%-3d post=%-3d " "nid=%s buf_len=%-3d wire_len=%-3d flags=%0x", id2str(scan->id), scan->offset, scan->hdr_prefix, scan->length, scan->hdr_gap, scan->hdr_payload, scan->hdr_postfix, id2str( scan->next_id), scan->buf_len, scan->wire_len, scan->scanner->sc_flags[scan->id]); } /** * Checks if the data at specified offset is accessible or has it possibly * been truncated. */ int is_accessible(scan_t *scan, int offset) { return (scan->offset + offset) <= scan->buf_len; } /* * Converts our numerical header ID to a string, which is better suited for * debugging. */ const char *id2str(int id) { if (id == END_OF_HEADERS) { return "END_OF_HEADERS"; } else if (native_protocol_names[id] != NULL) { return native_protocol_names[id]; } else { sprintf(id_str_buf, "%d", id); return id_str_buf; } } /** * Scan packet buffer */ int scan(JNIEnv *env, jobject obj, jobject jpacket, scanner_t *scanner, packet_state_t *p_packet, int first_id, char *buf, int buf_len, uint32_t wirelen) { scan_t scan; // Our current in progress scan's state information scan_t *pscan = &scan; scan.env = env; scan.jscanner = obj; scan.jpacket = jpacket; scan.scanner = scanner; scan.packet = p_packet; scan.header = &p_packet->pkt_headers[0]; scan.buf = buf; scan.buf_len = buf_len; // Changing buffer length, reduced by 'postfix' scan.mem_len = buf_len; // Constant in memory buffer length scan.wire_len = wirelen; scan.offset = 0; scan.length = 0; scan.id = first_id; scan.next_id = PAYLOAD_ID; scan.flags = 0; scan.hdr_flags = 0; scan.hdr_prefix = 0; scan.hdr_gap = 0; scan.hdr_payload = 0; scan.hdr_postfix = 0; memset(scan.header, 0, sizeof(header_t)); // Point jscan setJMemoryPhysical(env, scanner->sc_jscan, toLong(&scan)); // Local temp variables register uint64_t mask; #ifdef DEBUG debug_enter("scan"); debug_trace("processing packet", "#%d", p_packet->pkt_frame_num); #endif /* * Main scanner loop, 1st scans for builtin header types then * reverts to calling on JBinding objects to provide the binding chain */ while (scan.id != END_OF_HEADERS) { #ifdef DEBUG debug_trace("", ""); debug_trace("processing header", id2str(scan.id)); debug_scan("loop-top", &scan); #endif /* A flag that keeps track of header recording. Set in record_header()*/ scan.is_recorded = 0; /* * If debugging is compiled in, we can also call on each protocols * debug_* function to print out details about the protocol header * structure. */ #ifdef DEBUG if (native_debug[scan.id]) { native_debug[scan.id](scan.buf + scan.offset); } #endif /* * Scan of each protocol is done through a dispatch function table. * Each protocol that has a protocol header scanner attached, a scanner * designed specifically for that protocol. The protocol id is also the * index into the table. There are 2 types of scanners both have exactly * the same signature and thus both are set in this table. The first is * the native scanner that only performs a direct scan of the header. * The second scanner is a java header scanner. It is based on * JHeaderScanner class. A single dispatch method callJavaHeaderScanner * uses the protocol ID to to dispatch to the appropriate java scanner. * Uses a separate java specific table: sc_java_header_scanners[]. The * java scanner is capable of calling the native scan method from java * but also adds the ability to check all the attached JBinding[] for * any additional registered bindings. Interesting fact is that if the * java scanner doesn't have any bindings nor does it override the * default scan method to perform a scan in java and is also setup to * dispatch to native scanner, it is exactly same thing as if the * native scanner was dispatched directly from here, but round * about way through java land. */ if (scanner->sc_scan_table[scan.id] != NULL) { scanner->sc_scan_table[scan.id](&scan); // Dispatch to scanner } #ifdef DEBUG debug_scan("loop-middle", &scan); #endif if (scan.length == 0) { #ifdef DEBUG debug_scan("loop-length==0", &scan); #endif if (scan.id == PAYLOAD_ID) { scan.next_id = END_OF_HEADERS; } else { scan.next_id = PAYLOAD_ID; } } else { // length != 0 #ifdef DEBUG debug_scan("loop-length > 0", &scan); #endif /****************************************************** * **************************************************** * * If override flag is set, then we reset the * * discovered next protocol. If that is what the user * * wants then that is what he gets. * **************************************************** ******************************************************/ if (scanner->sc_flags[scan.id] & FLAG_OVERRIDE_BINDING) { #ifdef DEBUG debug_scan("TCP OVERRIDE", &scan); #endif scan.next_id = PAYLOAD_ID; } /****************************************************** * **************************************************** * * Now do HEURISTIC discovery scans if the appropriate * * flags are set. Heuristics allow us to provide nxt * * protocol binding, using discovery (an educated * * guess). * **************************************************** ******************************************************/ if (scanner->sc_flags[scan.id] & FLAG_HEURISTIC_BINDING) { /* * Save these critical properties, in case heuristic changes them * for this current header, not the next one its supposed to * check for. */ int saved_offset = scan.offset; int saved_length = scan.length; /* Advance offset to next header, so that heuristics can get a * peek. It will be restored at the end of heuristics block. */ scan.offset += scan.length + scan.hdr_gap; /* * 2 types of heuristic bindings. Pre and post. * Pre - heuristics are run before the direct discovery method * in scanner. Only after the pre-heuristic fail do we * utilize the directly discovered binding. * * Post - heuristics are run after the direct discovery method * didn't produce a binding. * * ------------------------------------------------------------ * * In our case, since we have already ran the direct discovery * in the header scanner, we save scan.next_id value, reset it, * call the heuristic function, check its scan.next_id if it * was set, if it was, then use that instead. Otherwise if it * wasn't restore the original next_id and continue on normally. */ if (scanner->sc_flags[scan.id] & FLAG_HEURISTIC_PRE_BINDING) { #ifdef DEBUG debug_scan("heurists_pre", &scan); #endif int saved_next_id = scan.next_id; scan.next_id = PAYLOAD_ID; for (int i = 0; i < MAX_ID_COUNT; i++) { native_validate_func_t validate_func; validate_func = scanner->sc_heuristics_table[scan.id][i]; if (validate_func == NULL) { break; } if ((scan.next_id = validate_func(&scan)) != INVALID) { break; } } if (scan.next_id == PAYLOAD_ID) { scan.next_id = saved_next_id; } } else if (scan.next_id == PAYLOAD_ID) { #ifdef DEBUG debug_scan("heurists_post", &scan); #endif for (int i = 0; i < MAX_ID_COUNT; i++) { native_validate_func_t validate_func; validate_func = scanner->sc_heuristics_table[scan.id][i]; if (validate_func == NULL) { break; } if ((scan.next_id = validate_func(&scan)) != INVALID) { #ifdef DEBUG debug_scan("heurists_post::found", &scan); #endif break; } } } /* Restore these 2 critical properties */ scan.offset = saved_offset; scan.length = saved_length; } /****************************************************** * **************************************************** * * Now record discovered information in structures * **************************************************** ******************************************************/ record_header(&scan); #ifdef DEBUG debug_header("header_t", scan.header - 1); #endif } // End if len != 0 #ifdef DEBUG debug_scan("loop-bottom", &scan); #endif scan.id = scan.next_id; scan.offset += scan.length + scan.hdr_gap; scan.length = 0; scan.next_id = PAYLOAD_ID; if (scan.offset >= scan.buf_len) { scan.id = END_OF_HEADERS; } } // End for loop /* record number of header entries found */ // scan.packet->pkt_header_count = count; process_flow_key(&scan); #ifdef DEBUG debug_trace("loop-finished", "header_count=%d offset=%d header_map=0x%X", scan.packet->pkt_header_count, scan.offset, scan.packet->pkt_header_map); debug_exit("scan()"); #endif return scan.offset; } // End scan() /** * Record state of the header in the packet state structure. */ void record_header(scan_t *scan) { #ifdef DEBUG debug_enter("record_header"); debug_scan("top", scan); #endif /* * Check if already recorded */ if (scan->is_recorded) { #ifdef DEBUG debug_exit("record_header"); #endif return; } register int offset = scan->offset; register header_t *header = scan->header; register int buf_len = scan->buf_len; packet_state_t *packet = scan->packet; /* * Decrease wire-length by postfix amount so that next header's payload * will be reduced and won't go over this header's postfix */ scan->wire_len -= scan->hdr_postfix; if (buf_len > scan->wire_len) { buf_len = scan->buf_len = scan->wire_len; // Make sure that buf_len and wire_len sync up #ifdef DEBUG debug_scan("adj buf_len", scan); #endif } /* * If payload length hasn't explicitly been set to some length, set it * to the remainder of the packet. */ if (scan->hdr_payload == 0 && scan->id != PAYLOAD_ID) { scan->hdr_payload = scan->buf_len - (offset + scan->hdr_prefix + scan->length + scan->hdr_gap); scan->hdr_payload = (scan->hdr_payload < 0) ? 0 : scan->hdr_payload; #ifdef DEBUG debug_scan("adj payload", scan); #endif } adjustForTruncatedPacket(scan); register int length = scan->length; /* * Initialize the header entry in our packet header array */ packet->pkt_header_map |= (1 << scan->id); header->hdr_id = scan->id; header->hdr_offset = offset + scan->hdr_prefix; header->hdr_analysis = NULL; /* * This is a combination of regular header flags with cumulative flags * which are accumulated by subsequent pass to the next header and pass on * to their encapsulated headers. This is a way to pass flags such as * the remaining header's are fragmented. */ header->hdr_flags = scan->hdr_flags | (scan->flags & CUMULATIVE_FLAG_MASK); header->hdr_prefix = scan->hdr_prefix; header->hdr_gap = scan->hdr_gap; header->hdr_payload = scan->hdr_payload; header->hdr_postfix = scan->hdr_postfix; header->hdr_length = length; scan->hdr_flags = 0; scan->hdr_prefix = 0; scan->hdr_gap = 0; scan->hdr_payload = 0; scan->hdr_postfix = 0; scan->is_recorded = 1; packet->pkt_header_count++; /* number of entries */ // scan->id = -1; // Indicates, that header is already recorded /* Initialize key fields in a new header */ header = ++scan->header; /* point to next header entry *** ptr arithmatic */ memset(header, 0, sizeof(header_t)); #ifdef DEBUG debug_scan("bottom", scan); debug_exit("record_header"); #endif } /** * Adjusts for a packet that has been truncated. Sets appropriate flags in the * header flags field, resets lengths of prefix, header, gap, payload and * postfix appropriately to account for shortened packet. */ void adjustForTruncatedPacket(scan_t *scan) { #ifdef DEBUG debug_enter("adjustForTruncatedPacket"); debug_trace("packet", "%ld", scan->scanner->sc_cur_frame_num); #endif /* * Adjust for truncated packets. We check the end of the header record * against the buf_len. If the end is past the buf_len, that means that we * need to start trucating in the following order: * postfix, payload, gap, header, prefix * * +-------------------------------------------+ * | prefix | header | gap | payload | postfix | * +-------------------------------------------+ * */ register int start = scan->offset + scan->hdr_prefix + scan->length + scan->hdr_gap + scan->hdr_payload; register int end = start + scan->hdr_postfix; register int buf_len = scan->buf_len; #ifdef DEBUG debug_scan((char *)id2str(scan->id), scan); debug_trace(id2str(scan->id), "offset=%d, pre=%d, len=%d, gap=%d, pay=%d, post=%d", scan->offset, scan->hdr_prefix, scan->length, scan->hdr_gap, scan->hdr_payload, scan->hdr_postfix); debug_trace(id2str(scan->id), "start=%d end=%d buf_len=%d", start, end, buf_len); #endif if (end > buf_len) { // Check if postfix extends past the end of packet /* * Because postfix is at the end, whenever the packet is truncated * postfix is always truncated, unless it wasn't set */ if (scan->hdr_postfix > 0) { scan->hdr_flags |= HEADER_FLAG_PREFIX_TRUNCATED; scan->hdr_postfix = (start > scan->mem_len) ? 0 : scan->mem_len - start; scan->hdr_postfix = (scan->hdr_postfix < 0) ? 0 : scan->hdr_postfix; #ifdef DEBUG debug_scan("adjust postfix", scan); #endif } /* Position at payload and process */ start -= scan->hdr_payload; end = start + scan->hdr_payload; if (end > buf_len) { scan->hdr_flags |= HEADER_FLAG_PAYLOAD_TRUNCATED; scan->hdr_payload = (start > buf_len) ? 0 : buf_len - start; scan->hdr_payload = (scan->hdr_payload < 0) ? 0 : scan->hdr_payload; #ifdef DEBUG debug_scan("adjust payload", scan); debug_trace("adjust payload", "start=%d end=%d", start, end); #endif /* Position at gap and process */ start -= scan->hdr_gap; end = start + scan->hdr_gap; if (scan->hdr_gap > 0 && end > buf_len) { scan->hdr_flags |= HEADER_FLAG_GAP_TRUNCATED; scan->hdr_gap = (start > buf_len) ? 0 : buf_len - start; scan->hdr_gap = (scan->hdr_gap < 0) ? 0 : scan->hdr_gap; #ifdef DEBUG debug_scan("adjust gap", scan); #endif } /* Position at header and process */ start -= scan->length; end = start + scan->length; if (end > buf_len) { scan->hdr_flags |= HEADER_FLAG_HEADER_TRUNCATED; scan->length = (start > buf_len) ? 0 : buf_len - start; scan->length = (scan->length < 0) ? 0 : scan->length; #ifdef DEBUG debug_scan("adjust header", scan); #endif /* Position at prefix and process */ start -= scan->hdr_prefix; end = start + scan->hdr_prefix; if (0 && scan->hdr_prefix > 0 && end > buf_len) { scan->hdr_flags |= HEADER_FLAG_PREFIX_TRUNCATED; scan->hdr_prefix = (start > buf_len) ? 0 : buf_len - start; scan->hdr_prefix = (scan->hdr_prefix < 0) ? 0 : scan->hdr_prefix; #ifdef DEBUG debug_scan("adjust prefix", scan); #endif } } } } #ifdef DEBUG debug_exit("adjustForTruncatedPacket"); #endif #undef DEBUG } /** * Scan packet buffer by dispatching to JBinding java objects */ void callJavaHeaderScanner(scan_t *scan) { #ifdef DEBUG debug_enter("callJavaHeaderScanner"); #endif JNIEnv *env = scan->env; jobject jscanner = scan->scanner->sc_java_header_scanners[scan->id]; if (jscanner == NULL) { sprintf(str_buf, "java header scanner not set for ID=%d (%s)", scan->id, id2str(scan->id)); #ifdef DEBUG debug_error("callJavaHeaderScanner()", str_buf); #endif throwException(scan->env, NULL_PTR_EXCEPTION, str_buf); return; } env->CallVoidMethod(jscanner, scanHeaderMID, scan->scanner->sc_jscan); #ifdef DEBUG debug_exit("callJavaHeaderScanner"); #endif } /** * Prepares a scan of packet buffer */ int scanJPacket(JNIEnv *env, jobject obj, jobject jpacket, jobject jstate, scanner_t *scanner, int first_id, char *buf, int buf_length, uint32_t wirelen) { #ifdef DEBUG debug_enter("scanJPacket"); #endif /* Check if we need to wrap our entry buffer around */ if (scanner->sc_offset > scanner->sc_len - sizeof(header_t) * MAX_ENTRY_COUNT) { scanner->sc_offset = 0; } packet_state_t *packet = (packet_state_t *) (((char *) scanner->sc_packet) + scanner->sc_offset); /* * Peer JPacket.state to packet_state_t structure */ // setJMemoryPhysical(env, jstate, toLong(packet)); // env->SetObjectField(jstate, jmemoryKeeperFID, obj); // Set it to JScanner jmemoryPeer(env, jstate, packet, sizeof(packet_state_t), obj); /* * Reset the entire packet_state_t structure */ memset(packet, 0, sizeof(packet_state_t)); /* * Initialize the packet_state_t structure for new packet entry. We need to * initialize everything since we may be wrapping around and writting over * previously stored data. */ packet->pkt_header_map = 0; packet->pkt_header_count = 0; packet->pkt_frame_num = scanner->sc_cur_frame_num++; packet->pkt_wirelen = (uint32_t) wirelen; packet->pkt_flags = 0; if (buf_length != wirelen) { packet->pkt_flags |= PACKET_FLAG_TRUNCATED; } #ifdef DEBUG debug_trace("before scan", "buf_len=%d wire_len=%d", buf_length, wirelen); #endif scan(env, obj, jpacket, scanner, packet, first_id, buf, buf_length, wirelen); #ifdef DEBUG debug_trace("after scan", "buf_len=%d wire_len=%d", buf_length, wirelen); #endif const size_t len = sizeof(packet_state_t) + (sizeof(header_t) * packet->pkt_header_count); scanner->sc_offset += len; jmemoryResize(env, jstate, len); #ifdef DEBUG debug_exit("scanJPacket"); #endif } /**************************************************************** * ************************************************************** * * Java declared native functions * * ************************************************************** ****************************************************************/ jclass jheaderScannerClass = NULL; jmethodID scanHeaderMID = 0; /* * Class: org_jnetpcap_packet_JScanner * Method: initIds * Signature: ()V */ JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_initIds (JNIEnv *env, jclass clazz) { if ( (jheaderScannerClass = findClass( env, "org/jnetpcap/packet/JHeaderScanner")) == NULL) { return; } if ( (scanHeaderMID = env->GetMethodID( jheaderScannerClass, "scanHeader", "(Lorg/jnetpcap/packet/JScan;)V")) == NULL) { return; } /* * Initialize the global native scan function dispatch table. * i.e. scan_ethernet(), scan_ip4(), etc... */ init_native_protocols(); } /* * Class: org_jnetpcap_packet_JScanner * Method: sizeof * Signature: ()I */ JNIEXPORT jint JNICALL Java_org_jnetpcap_packet_JScanner_sizeof(JNIEnv *env, jclass obj) { return (jint) sizeof(scanner_t); } /* * Class: org_jnetpcap_packet_JScannerReference * Method: disposeNative * Signature: (J)V */ JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScannerReference_disposeNative (JNIEnv *env, jobject obj, jlong size) { jlong pt = env->GetLongField(obj, jmemoryRefAddressFID); scanner_t *scanner = (scanner_t *)toPtr(pt); if (scanner == NULL) { return; } env->DeleteGlobalRef(scanner->sc_jscan); scanner->sc_jscan = NULL; if (scanner->sc_subheader != NULL) { free(scanner->sc_subheader); scanner->sc_subheader = NULL; } for (int i = 0; i < MAX_ID_COUNT; i ++) { if (scanner->sc_java_header_scanners[i] != NULL) { env->DeleteGlobalRef(scanner->sc_java_header_scanners[i]); scanner->sc_java_header_scanners[i] = NULL; } } /* * Same as super.dispose(): call from JScannerReference.dispose for * JMemoryReference.super.dispose. */ // Java_org_jnetpcap_nio_JMemoryReference_disposeNative0(env, obj, pt, size); } /* * Class: org_jnetpcap_packet_JScanner * Method: getFrameNumber * Signature: ()J */ JNIEXPORT jlong JNICALL Java_org_jnetpcap_packet_JScanner_getFrameNumber( JNIEnv *env, jobject obj) { scanner_t *scanner = (scanner_t *) getJMemoryPhysical(env, obj); if (scanner == NULL) { return -1; } return (jlong) scanner->sc_cur_frame_num; } /* * Class: org_jnetpcap_packet_JScanner * Method: init * Signature: (Lorg.jnetpcap.packet.JScan;)V */ JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_init (JNIEnv *env, jobject obj, jobject jscan) { #ifdef DEBUG debug_enter("JScanner_init"); #endif if (jscan == NULL) { throwException(env, NULL_PTR_EXCEPTION, "JScan parameter can not be null"); return; } void *block = (char *)getJMemoryPhysical(env, obj); size_t size = (size_t)env->GetIntField(obj, jmemorySizeFID); memset(block, 0, size); scanner_t *scanner = (scanner_t *)block; scanner->sc_jscan = env->NewGlobalRef(jscan); scanner->sc_len = size - sizeof(scanner_t); scanner->sc_offset = 0; scanner->sc_packet = (packet_state_t *)((char *)block + sizeof(scanner_t)); for (int i = 0; i < MAX_ID_COUNT; i++) { scanner->sc_scan_table[i] = native_protocols[i]; } for (int i = 0; i < MAX_ID_COUNT; i++) { for (int j = 0; j < MAX_ID_COUNT; j++) { scanner->sc_heuristics_table[i][j] = native_heuristics[i][j]; } } /* Initialize sub-header area - allocate 1/10th */ scanner->sc_sublen = size / 10; scanner->sc_subindex = 0; scanner->sc_subheader = (header_t *)malloc(scanner->sc_sublen); #ifdef DEBUG debug_exit("JScanner_init"); #endif } /* * Class: org_jnetpcap_packet_JScanner * Method: loadScanners * Signature: (I[Lorg/jnetpcap/packet/JHeaderScanner;)V */ JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_loadScanners (JNIEnv *env, jobject obj, jobjectArray jascanners) { #ifdef DEBUG debug_enter("loadScanners"); #endif scanner_t *scanner = (scanner_t *)getJMemoryPhysical(env, obj); if (scanner == NULL) { return; } jsize size = env->GetArrayLength(jascanners); #ifdef DEBUG debug_trace("load", "loaded %d scanners", (int)size); #endif if (size != MAX_ID_COUNT) { throwException(env, ILLEGAL_ARGUMENT_EXCEPTION, "size of array must be MAX_ID_COUNT size"); #ifdef DEBUG debug_error("IllegalArgumentException", "size of array must be MAX_ID_COUNT size"); #endif return; } for (int i = 0; i < MAX_ID_COUNT; i ++) { jobject loc_ref = env->GetObjectArrayElement(jascanners, (jsize) i); if (loc_ref == NULL) { /* * If we don't have a java header scanner, then setup the native * scanner in its place. Any unused java scanner slot will be filled * with native scanner. */ scanner->sc_scan_table[i] = native_protocols[i]; // printf("loadScanners::native(%s)\n", id2str(i));fflush(stdout); } else { // printf("loadScanners::java(%s)\n", id2str(i));fflush(stdout); if (scanner->sc_java_header_scanners[i] != NULL) { env->DeleteGlobalRef(scanner->sc_java_header_scanners[i]); scanner->sc_java_header_scanners[i] = NULL; } /* * Record the java header scanner and replace the native scanner with * our java scanner in dispatch table. */ scanner->sc_java_header_scanners[i] = env->NewGlobalRef(loc_ref); scanner->sc_scan_table[i] = callJavaHeaderScanner; env->DeleteLocalRef(loc_ref); } } #ifdef DEBUG debug_exit("loadScanners"); #endif } /* * Class: org_jnetpcap_packet_JScanner * Method: loadFlags * Signature: ([I)V */ JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_loadFlags (JNIEnv *env, jobject obj, jintArray jflags) { #ifdef DEBUG debug_enter("loadFlags"); #endif scanner_t *scanner = (scanner_t *)getJMemoryPhysical(env, obj); if (scanner == NULL) { return; } jsize size = env->GetArrayLength(jflags); #ifdef DEBUG debug_trace("load", "loaded %d flags", (int)size); #endif if (size != MAX_ID_COUNT) { throwException(env, ILLEGAL_ARGUMENT_EXCEPTION, "size of array must be MAX_ID_COUNT size"); #ifdef DEBUG debug_error("IllegalArgumentException", "size of array must be MAX_ID_COUNT size"); #endif return; } env->GetIntArrayRegion(jflags, 0, size, (jint *)scanner->sc_flags); #ifdef DEBUG debug_exit("loadFlags"); #endif } /* * Class: org_jnetpcap_packet_JScanner * Method: scan * Signature: (Lorg/jnetpcap/packet/JPacket;Lorg/jnetpcap/packet/JPacket$State;II)I */ JNIEXPORT jint JNICALL Java_org_jnetpcap_packet_JScanner_scan(JNIEnv *env, jobject obj, jobject jpacket, jobject jstate, jint id, jint wirelen) { scanner_t *scanner = (scanner_t *) getJMemoryPhysical(env, obj); if (scanner == NULL) { return -1; } char *buf = (char *) getJMemoryPhysical(env, jpacket); if (buf == NULL) { return -1; } int size = (int) env->GetIntField(jpacket, jmemorySizeFID); if (wirelen < size) { throwException(env, ILLEGAL_ARGUMENT_EXCEPTION, "wirelen < buffer len"); return -1; } return scanJPacket(env, obj, jpacket, jstate, scanner, id, buf, size, (uint32_t) wirelen); } /* * Class: org_jnetpcap_packet_JScanner * Method: setFrameNumber * Signature: (J)V */ JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_setFrameNumber (JNIEnv *env, jobject obj, jlong frame_no) { scanner_t *scanner = (scanner_t *)getJMemoryPhysical(env, obj); if (scanner == NULL) { return; } scanner->sc_cur_frame_num = (uint64_t) frame_no; return; }<|fim▁end|>
/* scanner specific debug_ trace functions */ void debug_header(char *msg, header_t *header) { debug_trace(msg,
<|file_name|>Entity.java<|end_file_name|><|fim▁begin|>package com.ek.mobileapp.model; import java.io.Serializable; public abstract class Entity implements Serializable { protected int id; public int getId() { return id; }<|fim▁hole|> public String getCacheKey() { return cacheKey; } public void setCacheKey(String cacheKey) { this.cacheKey = cacheKey; } }<|fim▁end|>
protected String cacheKey;
<|file_name|>test_link_aggregator.py<|end_file_name|><|fim▁begin|>import unittest import logging from domaincrawl.link_aggregator import LinkAggregator from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme from domaincrawl.site_graph import SiteGraph from domaincrawl.util import URLNormalizer, extract_domain_port class LinkAggregatorTest(unittest.TestCase): logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%m/%d/%Y %I:%M:%S %p') def test_link_dedup(self): base_url = "acme.com:8999" base_domain, port = extract_domain_port(base_url) logger = logging.getLogger() url_norm = URLNormalizer(base_domain, port) normalized_url = url_norm.normalize_with_domain(base_url) logger.debug("Constructed normalized base url : %s"%normalized_url) <|fim▁hole|> valid_links = ["/a/b","/a/b/./","http://acme.com:8002/a","https://acme.com:8002/b?q=asd#frag"] expected_links = ["http://acme.com:8999/a/b","http://acme.com:8002/a","https://acme.com:8002/b"] # This time, we also specify a referrer page filtered_links = link_aggregator.filter_update_links(valid_links, normalized_url) self.assertListEqual(expected_links,filtered_links) self.assertSetEqual(set(expected_links),link_aggregator._links) # Second invocation should result in deduplication filtered_links = link_aggregator.filter_update_links(valid_links, None) self.assertTrue(len(filtered_links) == 0) self.assertSetEqual(set(expected_links),link_aggregator._links) # None of the invalid links should pass invalid_links = ["mailto://[email protected]","code.acme.com","code.acme.com/b","https://127.122.9.1"] filtered_links = link_aggregator.filter_update_links(invalid_links, None) self.assertTrue(len(filtered_links) == 0) self.assertSetEqual(set(expected_links),link_aggregator._links) # A new valid link should pass new_valid_links = ["http://acme.com:8999/"] filtered_links = link_aggregator.filter_update_links(new_valid_links, None) expected_result = ["http://acme.com:8999"] self.assertListEqual(expected_result,filtered_links) expected_result_set = set(expected_links) expected_result_set.update(set(expected_result)) self.assertSetEqual(expected_result_set,link_aggregator._links) self.assertEqual(len(expected_result_set), site_graph.num_nodes()) for link in expected_result_set: self.assertTrue(site_graph.has_vertex(link)) self.assertEqual(len(expected_links), site_graph.num_edges()) for link in expected_links: self.assertTrue(site_graph.has_edge(normalized_url, link))<|fim▁end|>
domain_filter = DomainFilter(base_domain, logger) site_graph = SiteGraph(logger) link_aggregator = LinkAggregator(logger, site_graph, link_mappers=[url_norm.normalize_with_domain], link_filters=[domain_filter.passes, is_acceptable_url_scheme])
<|file_name|>browser_features.test.ts<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met:<|fim▁hole|> * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import { BrowserTracker } from '@snowplow/browser-tracker-core'; import { buildLinkClick, trackerCore } from '@snowplow/tracker-core'; import { JSDOM } from 'jsdom'; import { BrowserFeaturesPlugin } from '../src/index'; declare var jsdom: JSDOM; describe('Browser Features plugin', () => { it('Returns undefined or false for unavailable mimeTypes', (done) => { Object.defineProperty(jsdom.window.navigator, 'mimeTypes', { value: { 'application/pdf': { enabledPlugin: false }, length: 1, }, configurable: true, }); const core = trackerCore({ base64: false, callback: (payloadBuilder) => { const payload = payloadBuilder.build(); expect(payload['f_pdf']).toBe('0'); expect(payload['f_qt']).toBeUndefined(); done(); }, }); BrowserFeaturesPlugin().activateBrowserPlugin?.({ core } as BrowserTracker); core.track(buildLinkClick({ targetUrl: 'https://example.com' })); }); it('Returns values for available mimeTypes', (done) => { Object.defineProperty(jsdom.window.navigator, 'mimeTypes', { value: { 'application/pdf': { enabledPlugin: true }, 'video/quicktime': { enabledPlugin: true }, 'audio/x-pn-realaudio-plugin': { enabledPlugin: true }, 'application/x-mplayer2': { enabledPlugin: true }, 'application/x-director': { enabledPlugin: true }, 'application/x-shockwave-flash': { enabledPlugin: true }, 'application/x-java-vm': { enabledPlugin: true }, 'application/x-googlegears': { enabledPlugin: true }, 'application/x-silverlight': { enabledPlugin: true }, length: 9, }, configurable: true, }); const core = trackerCore({ base64: false, callback: (payloadBuilder) => { const payload = payloadBuilder.build(); expect(payload['f_pdf']).toBe('1'); expect(payload['f_qt']).toBe('1'); expect(payload['f_realp']).toBe('1'); expect(payload['f_wma']).toBe('1'); expect(payload['f_dir']).toBe('1'); expect(payload['f_fla']).toBe('1'); expect(payload['f_java']).toBe('1'); expect(payload['f_gears']).toBe('1'); expect(payload['f_ag']).toBe('1'); done(); }, }); BrowserFeaturesPlugin().activateBrowserPlugin?.({ core } as BrowserTracker); core.track(buildLinkClick({ targetUrl: 'https://example.com' })); }); });<|fim▁end|>
* * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer.
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from jsonfield import JSONField from model_utils import Choices from model_utils.models import TimeStampedModel <|fim▁hole|> ACTIONS = Choices( ("package_create", _("Package Created")), ("package_delete", _("Package Deleted")), ("release_create", _("Release Created")), ("release_delete", _("Release Deleted")), ("file_add", _("File Added")), ("file_remove", _("File Removed")), ) package = models.SlugField(max_length=150) version = models.CharField(max_length=512, blank=True) action = models.CharField(max_length=25, choices=ACTIONS) data = JSONField(null=True, blank=True) @receiver(post_save, sender=Package) def history_package_create(instance, created, **kwargs): if created: Event.objects.create( package=instance.name, action=Event.ACTIONS.package_create ) @receiver(post_delete, sender=Package) def history_package_delete(instance, **kwargs): Event.objects.create( package=instance.name, action=Event.ACTIONS.package_delete ) @receiver(post_save, sender=Release) def history_release_update(instance, created, **kwargs): if created: Event.objects.create( package=instance.package.name, version=instance.version, action=Event.ACTIONS.release_create ) if instance.has_changed("hidden"): if instance.hidden: Event.objects.create( package=instance.package.name, version=instance.version, action=Event.ACTIONS.release_delete ) else: Event.objects.create( package=instance.package.name, version=instance.version, action=Event.ACTIONS.release_create ) @receiver(post_save, sender=ReleaseFile) def history_releasefile_update(instance, created, **kwargs): e = None if instance.has_changed("hidden"): if instance.hidden: e = Event.objects.create( package=instance.release.package.name, version=instance.release.version, action=Event.ACTIONS.file_remove ) if e is not None: try: e.data = { "filename": instance.filename, "digest": instance.digest, "uri": instance.get_absolute_url(), } except ValueError: pass else: e.save()<|fim▁end|>
from crate.web.packages.models import Package, Release, ReleaseFile class Event(TimeStampedModel):
<|file_name|>assets.js<|end_file_name|><|fim▁begin|><|fim▁hole|>gulp.task('assets', function() { gulp.src(config.src) .pipe(gulp.dest(config.dst)); });<|fim▁end|>
var config = require('../config').assets, gulp = require('gulp');
<|file_name|>inline-link.js<|end_file_name|><|fim▁begin|>import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function InlineLink( props ) { const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }--color-${ props.color }`, underlineClassName = 'none' !== props.underline ? `${ baseClassName }--underline-${ props.underline }` : '', italicClassName = props.italic ? `${ baseClassName }--italic` : '', classes = [ baseClassName, colorClassName, underlineClassName, italicClassName, props.className, ], className = arrayToClassName( classes ), getRouterLink = () => ( <LocationProvider history={ router.appHistory }><|fim▁hole|> to={ props.url } className={ className } > { props.children } </Link> </LocationProvider> ), getExternalLink = () => ( <a href={ props.url } target={ props.target } rel={ props.rel } className={ className } > { props.children } </a> ); return props.url.includes( 'http' ) ? getExternalLink() : getRouterLink(); } InlineLink.propTypes = { className: PropTypes.string, children: PropTypes.string, url: PropTypes.string, target: PropTypes.string, rel: PropTypes.string, text: PropTypes.string, color: PropTypes.oneOf( [ 'primary', 'secondary', 'cta', 'link', 'disabled' ] ), underline: PropTypes.oneOf( [ 'none', 'hover', 'always' ] ), italic: PropTypes.bool, }; InlineLink.defaultProps = { className: '', color: 'link', underline: 'always', target: '_blank', rel: 'noopener noreferrer', };<|fim▁end|>
<Link
<|file_name|>unstable_alloc.rs<|end_file_name|><|fim▁begin|>use alloc::raw_vec::RawVec; /// Alternative way to allocate memory, requiring unstable RawVec.<|fim▁hole|> raw.into_box() } }<|fim▁end|>
pub fn allocate_boxed_slice(cap: usize) -> Box<[u8]> { let raw = RawVec::with_capacity(cap); unsafe {
<|file_name|>sbwatchpoint.rs<|end_file_name|><|fim▁begin|>use super::*; cpp_class!(pub unsafe struct SBWatchpoint as "SBWatchpoint"); unsafe impl Send for SBWatchpoint {} impl SBWatchpoint { pub fn id(&self) -> WatchpointID { cpp!(unsafe [self as "SBWatchpoint*"] -> WatchpointID as "watch_id_t" { return self->GetID(); }) } } impl IsValid for SBWatchpoint { fn is_valid(&self) -> bool { cpp!(unsafe [self as "SBWatchpoint*"] -> bool as "bool" { return self->IsValid(); }) } } impl fmt::Debug for SBWatchpoint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let full = f.alternate();<|fim▁hole|> cpp!(unsafe [self as "SBWatchpoint*", descr as "SBStream*", full as "bool"] -> bool as "bool" { return self->GetDescription(*descr, full ? eDescriptionLevelFull : eDescriptionLevelBrief); }) }) } }<|fim▁end|>
debug_descr(f, |descr| {
<|file_name|>synaptic.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Make use of synaptic as backend.""" # Copyright (C) 2008-2010 Sebastian Heinlein <[email protected]> # Copyright (C) 2005-2007 Canonical # # Licensed under the GNU General Public License Version 2 # # 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. __author__ = "Sebastian Heinlein <[email protected]>, " \ "Michael Vogt <[email protected]" import tempfile from gettext import gettext as _ from gi.repository import GObject from defer import Deferred import sessioninstaller.errors class SynapticBackend(object): """Make use of Synaptic to install and remove packages.""" def _run_synaptic(self, xid, opt, tempf, interaction): deferred = Deferred() if tempf: opt.extend(["--set-selections-file", "%s" % tempf.name]) #FIXME: Take interaction into account opt.extend(["-o", "Synaptic::closeZvt=true"]) if xid: opt.extend(["--parent-window-id", "%s" % (xid)]) cmd = ["/usr/bin/gksu", "--desktop", "/usr/share/applications/update-manager.desktop", "--", "/usr/sbin/synaptic", "--hide-main-window", "--non-interactive"] cmd.extend(opt) flags = GObject.SPAWN_DO_NOT_REAP_CHILD (pid, stdin, stdout, stderr) = GObject.spawn_async(cmd, flags=flags) GObject.child_watch_add(pid, self._on_synaptic_exit, (tempf, deferred))<|fim▁hole|> def _on_synaptic_exit(self, pid, condition, (tempf, deferred)): if tempf: tempf.close() if condition == 0: deferred.callback() else: deferred.errback(sessioninstaller.errors.ModifyFailed()) def remove_packages(self, xid, package_names, interaction): opt = [] # custom progress strings #opt.append("--progress-str") #opt.append("%s" % _("Please wait, this can take some time.")) #opt.append("--finish-str") #opt.append("%s" % _("Update is complete")) tempf = tempfile.NamedTemporaryFile() for pkg_name in package_names: tempf.write("%s\tuninstall\n" % pkg_name) tempf.flush() return self._run_synaptic(xid, opt, tempf, interaction) def install_packages(self, xid, package_names, interaction): opt = [] # custom progress strings #opt.append("--progress-str") #opt.append("%s" % _("Please wait, this can take some time.")) #opt.append("--finish-str") #opt.append("%s" % _("Update is complete")) tempf = tempfile.NamedTemporaryFile() for pkg_name in package_names: tempf.write("%s\tinstall\n" % pkg_name) tempf.flush() return self._run_synaptic(xid, opt, tempf, interaction) def install_package_files(self, xid, package_names, interaction): raise NotImplemented # vim:ts=4:sw=4:et<|fim▁end|>
return deferred
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # phaxio-python documentation build configuration file, created by # sphinx-quickstart on Sun Jan 8 20:17:15 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../../')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', # 'sphinx.ext.githubpages', # 'sphinx.ext.autosectionlabel', 'sphinx.ext.autosummary' ] autosummary_generate = True autodoc_default_flags = ['members', 'undoc-members'] # skips dccumenting to_dict and to_str in model types def skip_member(app, what, name, obj, skip, options): if name in ['to_dict', 'to_str']: return True return skip # skips all docstrings in model types, but leave the :rtype: tags so we have type information and links def remove_module_docstring(app, what, name, obj, options, lines): if name.startswith("phaxio.swagger_client"): lines[:] = [x for x in lines if 'rtype' in x] def setup(app): app.connect('autodoc-skip-member', skip_member) app.connect("autodoc-process-docstring", remove_module_docstring) # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md']<|fim▁hole|># The master toctree document. master_doc = 'index' # General information about the project. project = u'phaxio-python' copyright = u'2017, Ari Polsky' author = u'Ari Polsky' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'.2' # The full version, including alpha/beta/rc tags. release = u'.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'phaxio-pythondoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'phaxio-python.tex', u'phaxio-python Documentation', u'Ari Polsky', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'phaxio-python', u'phaxio-python Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'phaxio-python', u'phaxio-python Documentation', author, 'phaxio-python', 'One line description of project.', 'Miscellaneous'), ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None}<|fim▁end|>
source_suffix = '.rst'
<|file_name|>syscall-latency.py<|end_file_name|><|fim▁begin|># perf script event handlers, generated by perf script -g python # Licensed under the terms of the GNU GPL License version 2 # The common_* event handler fields are the most useful fields common to # all events. They don't necessarily correspond to the 'common_*' fields # in the format files. Those fields not available as handler params can # be retrieved using Python functions of the form common_*(context). # See the perf-trace-python Documentation for the list of available functions. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * syscalls = autodict() def trace_begin(): pass def trace_end(): pass def raw_syscalls__sys_exit(event_name, context, cpu, s, ns, pid, comm, callchain, syscall_id, args): if pid not in syscalls or syscall_id not in syscalls[pid]: return latency = nsecs(s, ns) - syscalls[pid][syscall_id]<|fim▁hole|> s, ns, pid, comm, callchain, syscall_id, ret): syscalls[pid][syscall_id] = nsecs(s, ns) def trace_unhandled(event_name, context, event_fields_dict): pass<|fim▁end|>
print "[%04d] %04d => %9uns" % (pid, syscall_id, latency) def raw_syscalls__sys_enter(event_name, context, cpu,
<|file_name|>image.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Generic types for the handling of [images]. //! //! [images]: https://drafts.csswg.org/css-images/#image-values use Atom; use cssparser::serialize_identifier; use custom_properties; use servo_arc::Arc; use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; /// An [image]. /// /// [image]: https://drafts.csswg.org/css-images/#image-values #[derive(Clone, MallocSizeOf, PartialEq, ToComputedValue)] pub enum Image<Gradient, MozImageRect, ImageUrl> { /// A `<url()>` image. Url(ImageUrl), /// A `<gradient>` image. Gradients are rather large, and not nearly as /// common as urls, so we box them here to keep the size of this enum sane. Gradient(Box<Gradient>), /// A `-moz-image-rect` image. Also fairly large and rare. Rect(Box<MozImageRect>), /// A `-moz-element(# <element-id>)` Element(Atom), /// A paint worklet image. /// <https://drafts.css-houdini.org/css-paint-api/> #[cfg(feature = "servo")] PaintWorklet(PaintWorklet), } /// A CSS gradient. /// <https://drafts.csswg.org/css-images/#gradients> #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Gradient<LineDirection, Length, LengthOrPercentage, Position, Color, Angle> { /// Gradients can be linear or radial. pub kind: GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle>, /// The color stops and interpolation hints. pub items: Vec<GradientItem<Color, LengthOrPercentage>>, /// True if this is a repeating gradient. #[compute(clone)] pub repeating: bool, /// Compatibility mode. #[compute(clone)] pub compat_mode: CompatMode, } #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] /// Whether we used the modern notation or the compatibility `-webkit`, `-moz` prefixes. pub enum CompatMode { /// Modern syntax. Modern, /// `-webkit` prefix. WebKit, /// `-moz` prefix Moz, } /// A gradient kind. #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub enum GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle> { /// A linear gradient. Linear(LineDirection), /// A radial gradient. Radial(EndingShape<Length, LengthOrPercentage>, Position, Option<Angle>), } /// A radial gradient's ending shape. #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum EndingShape<Length, LengthOrPercentage> { /// A circular gradient. Circle(Circle<Length>), /// An elliptic gradient. Ellipse(Ellipse<LengthOrPercentage>), } /// A circle shape. #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub enum Circle<Length> { /// A circle radius. Radius(Length), /// A circle extent. Extent(ShapeExtent), } /// An ellipse shape. #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum Ellipse<LengthOrPercentage> { /// An ellipse pair of radii. Radii(LengthOrPercentage, LengthOrPercentage), /// An ellipse extent. Extent(ShapeExtent), } /// <https://drafts.csswg.org/css-images/#typedef-extent-keyword> #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq)] #[derive(ToComputedValue, ToCss)] pub enum ShapeExtent { ClosestSide, FarthestSide, ClosestCorner, FarthestCorner, Contain, Cover, } /// A gradient item. /// <https://drafts.csswg.org/css-images-4/#color-stop-syntax> #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum GradientItem<Color, LengthOrPercentage> { /// A color stop. ColorStop(ColorStop<Color, LengthOrPercentage>), /// An interpolation hint. InterpolationHint(LengthOrPercentage), } /// A color stop. /// <https://drafts.csswg.org/css-images/#typedef-color-stop-list> #[derive(Clone, Copy, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub struct ColorStop<Color, LengthOrPercentage> { /// The color of this stop. pub color: Color, /// The position of this stop. pub position: Option<LengthOrPercentage>, } /// Specified values for a paint worklet. /// <https://drafts.css-houdini.org/css-paint-api/> #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub struct PaintWorklet { /// The name the worklet was registered with. pub name: Atom, /// The arguments for the worklet. /// TODO: store a parsed representation of the arguments. #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub arguments: Vec<Arc<custom_properties::SpecifiedValue>>, } trivial_to_computed_value!(PaintWorklet); impl ToCss for PaintWorklet { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("paint(")?; serialize_identifier(&*self.name.to_string(), dest)?; for argument in &self.arguments { dest.write_str(", ")?; argument.to_css(dest)?; } dest.write_str(")") } } /// Values for `moz-image-rect`. /// /// `-moz-image-rect(<uri>, top, right, bottom, left);` #[allow(missing_docs)] #[css(comma, function)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> { pub url: MozImageRectUrl, pub top: NumberOrPercentage, pub right: NumberOrPercentage, pub bottom: NumberOrPercentage, pub left: NumberOrPercentage, } impl<G, R, U> fmt::Debug for Image<G, R, U> where G: ToCss, R: ToCss, U: ToCss, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_css(&mut CssWriter::new(f)) } } impl<G, R, U> ToCss for Image<G, R, U> where G: ToCss, R: ToCss, U: ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { match *self { Image::Url(ref url) => url.to_css(dest), Image::Gradient(ref gradient) => gradient.to_css(dest), Image::Rect(ref rect) => rect.to_css(dest), #[cfg(feature = "servo")] Image::PaintWorklet(ref paint_worklet) => paint_worklet.to_css(dest), Image::Element(ref selector) => {<|fim▁hole|> } } } impl<D, L, LoP, P, C, A> ToCss for Gradient<D, L, LoP, P, C, A> where D: LineDirection, L: ToCss, LoP: ToCss, P: ToCss, C: ToCss, A: ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { match self.compat_mode { CompatMode::WebKit => dest.write_str("-webkit-")?, CompatMode::Moz => dest.write_str("-moz-")?, _ => {}, } if self.repeating { dest.write_str("repeating-")?; } dest.write_str(self.kind.label())?; dest.write_str("-gradient(")?; let mut skip_comma = match self.kind { GradientKind::Linear(ref direction) if direction.points_downwards(self.compat_mode) => true, GradientKind::Linear(ref direction) => { direction.to_css(dest, self.compat_mode)?; false }, GradientKind::Radial(ref shape, ref position, ref angle) => { let omit_shape = match *shape { EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::Cover)) | EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner)) => { true }, _ => false, }; if self.compat_mode == CompatMode::Modern { if !omit_shape { shape.to_css(dest)?; dest.write_str(" ")?; } dest.write_str("at ")?; position.to_css(dest)?; } else { position.to_css(dest)?; if let Some(ref a) = *angle { dest.write_str(" ")?; a.to_css(dest)?; } if !omit_shape { dest.write_str(", ")?; shape.to_css(dest)?; } } false }, }; for item in &self.items { if !skip_comma { dest.write_str(", ")?; } skip_comma = false; item.to_css(dest)?; } dest.write_str(")") } } impl<D, L, LoP, P, A> GradientKind<D, L, LoP, P, A> { fn label(&self) -> &str { match *self { GradientKind::Linear(..) => "linear", GradientKind::Radial(..) => "radial", } } } /// The direction of a linear gradient. pub trait LineDirection { /// Whether this direction points towards, and thus can be omitted. fn points_downwards(&self, compat_mode: CompatMode) -> bool; /// Serialises this direction according to the compatibility mode. fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: CompatMode) -> fmt::Result where W: Write; } impl<L> ToCss for Circle<L> where L: ToCss, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { match *self { Circle::Extent(ShapeExtent::FarthestCorner) | Circle::Extent(ShapeExtent::Cover) => { dest.write_str("circle") }, Circle::Extent(keyword) => { dest.write_str("circle ")?; keyword.to_css(dest) }, Circle::Radius(ref length) => { length.to_css(dest) }, } } } impl<C, L> fmt::Debug for ColorStop<C, L> where C: fmt::Debug, L: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.color)?; if let Some(ref pos) = self.position { write!(f, " {:?}", pos)?; } Ok(()) } }<|fim▁end|>
dest.write_str("-moz-element(#")?; serialize_identifier(&selector.to_string(), dest)?; dest.write_str(")") },
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>import os PACKAGE_NAME = 'pyflux' def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(PACKAGE_NAME, parent_package, top_path) config.add_subpackage('__check_build') config.add_subpackage('arma') config.add_subpackage('ensembles') config.add_subpackage('families')<|fim▁hole|> config.add_subpackage('output') config.add_subpackage('ssm') config.add_subpackage('tests') config.add_subpackage('var') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())<|fim▁end|>
config.add_subpackage('garch') config.add_subpackage('gas') config.add_subpackage('gpnarx') config.add_subpackage('inference')
<|file_name|>mempool_spendcoinbase.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Stardust Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test spending coinbase transactions. # The coinbase transaction in block N can appear in block # N+100... so is valid in the mempool when the best block # height is N+99. # This test makes sure coinbase spends that will be mature # in the next block are accepted into the memory pool, # but less mature coinbase spends are NOT. # from test_framework.test_framework import StardustTestFramework from test_framework.util import * # Create one-input, one-output, no-fee transaction: class MempoolSpendCoinbaseTest(StardustTestFramework): def __init__(self): super().__init__() self.num_nodes = 1 self.setup_clean_chain = False def setup_network(self): # Just need one node for this test args = ["-checkmempool", "-debug=mempool"] self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, args)) self.is_network_split = False def run_test(self): chain_height = self.nodes[0].getblockcount() assert_equal(chain_height, 200) node0_address = self.nodes[0].getnewaddress() # Coinbase at height chain_height-100+1 ok in mempool, should # get mined. Coinbase at height chain_height-100+2 is # is too immature to spend. b = [ self.nodes[0].getblockhash(n) for n in range(101, 103) ] coinbase_txids = [ self.nodes[0].getblock(h)['tx'][0] for h in b ] spends_raw = [ create_tx(self.nodes[0], txid, node0_address, 49.99) for txid in coinbase_txids ] spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0]) # coinbase at height 102 should be too immature to spend assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, spends_raw[1]) # mempool should have just spend_101: assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ]) # mine a block, spend_101 should get confirmed self.nodes[0].generate(1)<|fim▁hole|> # ... and now height 102 can be spent: spend_102_id = self.nodes[0].sendrawtransaction(spends_raw[1]) assert_equal(self.nodes[0].getrawmempool(), [ spend_102_id ]) if __name__ == '__main__': MempoolSpendCoinbaseTest().main()<|fim▁end|>
assert_equal(set(self.nodes[0].getrawmempool()), set())
<|file_name|>unary-minus-suffix-inference.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn main() { let a = 1; let a_neg: i8 = -a; println!("{}", a_neg); let b = 1; let b_neg: i16 = -b; println!("{}", b_neg); let c = 1; let c_neg: i32 = -c; println!("{}", c_neg); let d = 1; let d_neg: i64 = -d; println!("{}", d_neg); let e = 1; let e_neg: int = -e; println!("{}", e_neg); // intentional overflows let f = 1; let f_neg: u8 = -f; println!("{}", f_neg); <|fim▁hole|> let h = 1; let h_neg: u32 = -h; println!("{}", h_neg); let i = 1; let i_neg: u64 = -i; println!("{}", i_neg); let j = 1; let j_neg: uint = -j; println!("{}", j_neg); }<|fim▁end|>
let g = 1; let g_neg: u16 = -g; println!("{}", g_neg);
<|file_name|>timeout.rs<|end_file_name|><|fim▁begin|>use std::error::Error; use std::fmt; use std::io; use futures::{Async, Future, Poll, Stream}; use future; use stream; use reactor::wheel::Timer; pub struct TimeoutError<T> { inner: T, } impl<T> TimeoutError<T> { #[inline] fn new(inner: T) -> Self { TimeoutError { inner } } #[inline] pub fn get_ref(&self) -> &T { &self.inner } #[inline] pub fn get_mut(&mut self) -> &mut T { &mut self.inner } #[inline] pub fn into_inner(self) -> T { self.inner } } impl<T> fmt::Display for TimeoutError<T> { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl<T> fmt::Debug for TimeoutError<T> { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl<T> Error for TimeoutError<T> { #[inline] fn description(&self) -> &str { "timed out" } } impl<T> From<TimeoutError<T>> for io::Error { #[inline] fn from(_: TimeoutError<T>) -> Self { io::Error::from(io::ErrorKind::TimedOut) } } impl<T> From<TimeoutError<T>> for () { fn from(_: TimeoutError<T>) -> Self {} } pub struct TimeoutFuture<F> { future: Option<F>, timer: Timer, } impl<F> TimeoutFuture<F> { #[inline] pub fn new(future: F, secs: u64) -> Self { TimeoutFuture { future: Some(future), timer: Timer::new(secs), } } #[inline] pub fn get_ref(&self) -> &F { self.future .as_ref() .expect("Attempted TimeoutFuture::get_ref after completion") } #[inline] pub fn get_mut(&mut self) -> &mut F { self.future .as_mut() .expect("Attempted TimeoutFuture::get_mut after completion") } #[inline] pub fn into_inner(self) -> F { self.future .expect("Attempted TimeoutFuture::into_inner after completion") } #[inline] fn future_mut(&mut self) -> &mut F { self.future .as_mut() .expect("Attempted to poll TimeoutFuture after completion") } } impl<F, E> Future for TimeoutFuture<F> where F: Future<Error = E>, E: From<TimeoutError<F>>, { type Item = F::Item; type Error = E; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.future_mut().poll() { Ok(Async::NotReady) => match self.timer.poll() { Ok(Async::NotReady) => Ok(Async::NotReady), Ok(Async::Ready(())) => match self.future.take() { Some(f) => Err(TimeoutError::new(f).into()), None => ::unreachable(), }, _ => ::unreachable(), }, ready => ready, } } } pub struct TimeoutStream<S> { stream: Option<S>, secs: u64, timer: Timer, } impl<S> TimeoutStream<S> { #[inline] pub fn new(stream: S, secs: u64) -> Self { TimeoutStream { stream: Some(stream), secs, timer: Timer::new(secs), } } #[inline] pub fn get_ref(&self) -> &S { self.stream .as_ref() .expect("Attempted TimeoutStream::get_ref after completion") } #[inline] pub fn get_mut(&mut self) -> &mut S { self.stream .as_mut() .expect("Attempted TimeoutStream::get_mut after completion") } #[inline] pub fn into_inner(self) -> S { self.stream .expect("Attempted TimeoutStream::into_inner after completion") } #[inline] pub fn stream_mut(&mut self) -> &mut S { self.stream .as_mut() .expect("Attempted to poll TimeoutStream after completion") } } impl<S, E> Stream for TimeoutStream<S> where S: Stream<Error = E>, E: From<TimeoutError<S>>, { type Item = S::Item; type Error = E; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { match self.stream_mut().poll() { Ok(Async::NotReady) => match self.timer.poll() { Ok(Async::NotReady) => Ok(Async::NotReady), Ok(Async::Ready(())) => match self.stream.take() { Some(s) => Err(TimeoutError::new(s).into()), None => ::unreachable(), }, _ => ::unreachable(), }, Ok(Async::Ready(Some(v))) => match self.timer.reschedule(self.secs) { true => Ok(Async::Ready(Some(v))),<|fim▁hole|> Some(s) => Err(TimeoutError::new(s).into()), None => ::unreachable(), }, }, ready_none => ready_none, } } } impl<F> future::Timeout for F where F: Future, F::Error: From<TimeoutError<F>>, { type Future = TimeoutFuture<F>; fn timeout(self, secs: u64) -> Self::Future { TimeoutFuture::new(self, secs) } } impl<S> stream::Timeout for S where S: Stream, S::Error: From<TimeoutError<S>>, { type Stream = TimeoutStream<S>; fn timeout(self, secs: u64) -> Self::Stream { TimeoutStream::new(self, secs) } }<|fim▁end|>
false => match self.stream.take() {
<|file_name|>SignUpForm.tsx<|end_file_name|><|fim▁begin|>import { createStyles, FormControl, Input, InputAdornment, InputLabel, Theme, WithStyles, } from '@material-ui/core'; import Button from '@material-ui/core/Button'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import Paper from '@material-ui/core/Paper'; import { withStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; import Typography from '@material-ui/core/Typography'; import Visibility from '@material-ui/icons/Visibility'; import VisibilityOff from '@material-ui/icons/VisibilityOff'; import cookie from 'cookie'; import { gql, FetchResult, useMutation, useApolloClient } from '@apollo/client'; import React, { FormEventHandler } from 'react'; import redirect from '@olimat/web/utils/redirect'; import Link from '../Link'; const styles = (theme: Theme) => createStyles({ signUpBox: { position: 'relative', width: 350, // maxHeight: 390, padding: theme.spacing(4), }, signUpHead: { marginBottom: theme.spacing(2), textAlign: 'center', }, passwordInput: { height: 'inherit', }, signUpButton: { marginTop: theme.spacing(2), }, helpMessage: { marginTop: theme.spacing(2), }, }); interface Props extends WithStyles<typeof styles> {} const signUpMutation = gql` mutation signUpMutation($name: String!, $email: String!, $password: String!) { signup(name: $name, email: $email, password: $password) { token } } `; const SignUpForm: React.FC<Props> = (props) => { const [state, setState] = React.useState({ password: '', showPassword: false, }); const [tryToSignUp, {}] = useMutation<Response, Variables>(signUpMutation); const client = useApolloClient(); const handleCreateUser: FormEventHandler<HTMLFormElement> = (event) => { /* global FormData */ const data = new FormData(event.currentTarget); event.preventDefault(); event.stopPropagation(); tryToSignUp({ variables: { email: data.get('email').toString(), password: data.get('password').toString(), name: data.get('name').toString(), }, }) .then( ({ data: { signup: { token }, }, }: FetchResult<Response>) => { // Store the token in cookie document.cookie = cookie.serialize('token', token, { maxAge: 30 * 24 * 60 * 60, // 30 days }); // Force a reload of all the current queries now that the user is // logged in client.resetStore().then(() => { // Now redirect to the homepage redirect({}, '/'); }); }, ) .catch((error) => { // Something went wrong, such as incorrect password, or no network // available, etc. console.error(error); }); }; const handleChange = (prop) => (event) => { event.persist(); setState((state) => ({ ...state, [prop]: event.target.value })); }; const handleMouseDownPassword = (event) => { event.preventDefault(); }; const handleClickShowPasssword = () => { setState((state) => ({ ...state, showPassword: !state.showPassword })); }; const { classes } = props; return ( <Paper className={classes.signUpBox}> <Typography className={classes.signUpHead} variant="h5"> Crie uma conta!<|fim▁hole|> id="name" name="name" label="Nome" margin="normal" fullWidth onChange={handleChange('name')} /> <TextField id="email" name="email" label="Email" margin="normal" fullWidth onChange={handleChange('email')} /> <TextField id="confirmEmail" name="confirmEmail" label="Confirmar email" margin="normal" fullWidth onChange={handleChange('confirmEmail')} /> <FormControl fullWidth margin="normal"> <InputLabel htmlFor="password">Senha</InputLabel> <Input id="password" name="password" inputProps={{ className: classes.passwordInput }} type={state.showPassword ? 'text' : 'password'} value={state.password} onChange={handleChange('password')} endAdornment={ <InputAdornment position="end"> <IconButton style={{ width: 'auto' }} onClick={handleClickShowPasssword} onMouseDown={handleMouseDownPassword} > {state.showPassword ? <VisibilityOff /> : <Visibility />} </IconButton> </InputAdornment> } /> </FormControl> <Button aria-label="Criar conta" className={classes.signUpButton} fullWidth variant="contained" color="secondary" size="large" type="submit" > Criar conta </Button> </form> <Typography className={classes.helpMessage} variant="caption" align="center" > Já possui uma conta?{' '} <Link color="primary" href="/login"> Faça login aqui. </Link> </Typography> </Paper> ); }; interface Response { signup: { token: string; }; } interface Variables { name: string; email: string; password: string; } export default withStyles(styles)(SignUpForm);<|fim▁end|>
</Typography> <Divider /> <form onSubmit={handleCreateUser}> <TextField
<|file_name|>runtests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ runtests.py [OPTIONS] [-- ARGS] Run tests, building the project first. Examples::<|fim▁hole|> $ python runtests.py --ipython $ python runtests.py --python somescript.py $ python runtests.py --bench Run a debugger: $ gdb --args python runtests.py [...other args...] Generate C code coverage listing under build/lcov/: (requires http://ltp.sourceforge.net/coverage/lcov.php) $ python runtests.py --gcov [...other args...] $ python runtests.py --lcov-html """ # # This is a generic test runner script for projects using Numpy's test # framework. Change the following values to adapt to your project: # PROJECT_MODULE = "numpy" PROJECT_ROOT_FILES = ['numpy', 'LICENSE.txt', 'setup.py'] SAMPLE_TEST = "numpy/linalg/tests/test_linalg.py:test_byteorder_check" SAMPLE_SUBMODULE = "linalg" EXTRA_PATH = ['/usr/lib/ccache', '/usr/lib/f90cache', '/usr/local/lib/ccache', '/usr/local/lib/f90cache'] # --------------------------------------------------------------------- if __doc__ is None: __doc__ = "Run without -OO if you want usage info" else: __doc__ = __doc__.format(**globals()) import sys import os # In case we are run from the source directory, we don't want to import the # project from there: sys.path.pop(0) import shutil import subprocess import time import imp from argparse import ArgumentParser, REMAINDER ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) def main(argv): parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument("--verbose", "-v", action="count", default=1, help="more verbosity") parser.add_argument("--no-build", "-n", action="store_true", default=False, help="do not build the project (use system installed version)") parser.add_argument("--build-only", "-b", action="store_true", default=False, help="just build, do not run any tests") parser.add_argument("--doctests", action="store_true", default=False, help="Run doctests in module") parser.add_argument("--coverage", action="store_true", default=False, help=("report coverage of project code. HTML output goes " "under build/coverage")) parser.add_argument("--gcov", action="store_true", default=False, help=("enable C code coverage via gcov (requires GCC). " "gcov output goes to build/**/*.gc*")) parser.add_argument("--lcov-html", action="store_true", default=False, help=("produce HTML for C code coverage information " "from a previous run with --gcov. " "HTML output goes to build/lcov/")) parser.add_argument("--mode", "-m", default="fast", help="'fast', 'full', or something that could be " "passed to nosetests -A [default: fast]") parser.add_argument("--submodule", "-s", default=None, help="Submodule whose tests to run (cluster, constants, ...)") parser.add_argument("--pythonpath", "-p", default=None, help="Paths to prepend to PYTHONPATH") parser.add_argument("--tests", "-t", action='append', help="Specify tests to run") parser.add_argument("--python", action="store_true", help="Start a Python shell with PYTHONPATH set") parser.add_argument("--ipython", "-i", action="store_true", help="Start IPython shell with PYTHONPATH set") parser.add_argument("--shell", action="store_true", help="Start Unix shell with PYTHONPATH set") parser.add_argument("--debug", "-g", action="store_true", help="Debug build") parser.add_argument("--parallel", "-j", type=int, default=0, help="Number of parallel jobs during build") parser.add_argument("--show-build-log", action="store_true", help="Show build output rather than using a log file") parser.add_argument("--bench", action="store_true", help="Run benchmark suite instead of test suite") parser.add_argument("--bench-compare", action="store", metavar="COMMIT", help=("Compare benchmark results to COMMIT. " "Note that you need to commit your changes first!")) parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER, help="Arguments to pass to Nose, Python or shell") args = parser.parse_args(argv) if args.bench_compare: args.bench = True args.no_build = True # ASV does the building if args.lcov_html: # generate C code coverage output lcov_generate() sys.exit(0) if args.pythonpath: for p in reversed(args.pythonpath.split(os.pathsep)): sys.path.insert(0, p) if args.gcov: gcov_reset_counters() if args.debug and args.bench: print("*** Benchmarks should not be run against debug " "version; remove -g flag ***") if not args.no_build: site_dir = build_project(args) sys.path.insert(0, site_dir) os.environ['PYTHONPATH'] = site_dir extra_argv = args.args[:] if extra_argv and extra_argv[0] == '--': extra_argv = extra_argv[1:] if args.python: # Debugging issues with warnings is much easier if you can see them print("Enabling display of all warnings") import warnings; warnings.filterwarnings("always") if extra_argv: # Don't use subprocess, since we don't want to include the # current path in PYTHONPATH. sys.argv = extra_argv with open(extra_argv[0], 'r') as f: script = f.read() sys.modules['__main__'] = imp.new_module('__main__') ns = dict(__name__='__main__', __file__=extra_argv[0]) exec_(script, ns) sys.exit(0) else: import code code.interact() sys.exit(0) if args.ipython: # Debugging issues with warnings is much easier if you can see them print("Enabling display of all warnings and pre-importing numpy as np") import warnings; warnings.filterwarnings("always") import IPython import numpy as np IPython.embed(user_ns={"np": np}) sys.exit(0) if args.shell: shell = os.environ.get('SHELL', 'sh') print("Spawning a Unix shell...") os.execv(shell, [shell] + extra_argv) sys.exit(1) if args.coverage: dst_dir = os.path.join(ROOT_DIR, 'build', 'coverage') fn = os.path.join(dst_dir, 'coverage_html.js') if os.path.isdir(dst_dir) and os.path.isfile(fn): shutil.rmtree(dst_dir) extra_argv += ['--cover-html', '--cover-html-dir='+dst_dir] if args.bench: # Run ASV items = extra_argv if args.tests: items += args.tests if args.submodule: items += [args.submodule] bench_args = [] for a in items: bench_args.extend(['--bench', a]) if not args.bench_compare: cmd = ['asv', 'run', '-n', '-e', '--python=same'] + bench_args os.chdir(os.path.join(ROOT_DIR, 'benchmarks')) os.execvp(cmd[0], cmd) sys.exit(1) else: commits = [x.strip() for x in args.bench_compare.split(',')] if len(commits) == 1: commit_a = commits[0] commit_b = 'HEAD' elif len(commits) == 2: commit_a, commit_b = commits else: p.error("Too many commits to compare benchmarks for") # Check for uncommitted files if commit_b == 'HEAD': r1 = subprocess.call(['git', 'diff-index', '--quiet', '--cached', 'HEAD']) r2 = subprocess.call(['git', 'diff-files', '--quiet']) if r1 != 0 or r2 != 0: print("*"*80) print("WARNING: you have uncommitted changes --- " "these will NOT be benchmarked!") print("*"*80) # Fix commit ids (HEAD is local to current repo) p = subprocess.Popen(['git', 'rev-parse', commit_b], stdout=subprocess.PIPE) out, err = p.communicate() commit_b = out.strip() p = subprocess.Popen(['git', 'rev-parse', commit_a], stdout=subprocess.PIPE) out, err = p.communicate() commit_a = out.strip() cmd = ['asv', 'continuous', '-e', '-f', '1.05', commit_a, commit_b] + bench_args os.chdir(os.path.join(ROOT_DIR, 'benchmarks')) os.execvp(cmd[0], cmd) sys.exit(1) test_dir = os.path.join(ROOT_DIR, 'build', 'test') if args.build_only: sys.exit(0) elif args.submodule: modname = PROJECT_MODULE + '.' + args.submodule try: __import__(modname) test = sys.modules[modname].test except (ImportError, KeyError, AttributeError): print("Cannot run tests for %s" % modname) sys.exit(2) elif args.tests: def fix_test_path(x): # fix up test path p = x.split(':') p[0] = os.path.relpath(os.path.abspath(p[0]), test_dir) return ':'.join(p) tests = [fix_test_path(x) for x in args.tests] def test(*a, **kw): extra_argv = kw.pop('extra_argv', ()) extra_argv = extra_argv + tests[1:] kw['extra_argv'] = extra_argv from numpy.testing import Tester return Tester(tests[0]).test(*a, **kw) else: __import__(PROJECT_MODULE) test = sys.modules[PROJECT_MODULE].test # Run the tests under build/test try: shutil.rmtree(test_dir) except OSError: pass try: os.makedirs(test_dir) except OSError: pass cwd = os.getcwd() try: os.chdir(test_dir) result = test(args.mode, verbose=args.verbose, extra_argv=extra_argv, doctests=args.doctests, coverage=args.coverage) finally: os.chdir(cwd) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) def build_project(args): """ Build a dev version of the project. Returns ------- site_dir site-packages directory where it was installed """ root_ok = [os.path.exists(os.path.join(ROOT_DIR, fn)) for fn in PROJECT_ROOT_FILES] if not all(root_ok): print("To build the project, run runtests.py in " "git checkout or unpacked source") sys.exit(1) dst_dir = os.path.join(ROOT_DIR, 'build', 'testenv') env = dict(os.environ) cmd = [sys.executable, 'setup.py'] # Always use ccache, if installed env['PATH'] = os.pathsep.join(EXTRA_PATH + env.get('PATH', '').split(os.pathsep)) if args.debug or args.gcov: # assume everyone uses gcc/gfortran env['OPT'] = '-O0 -ggdb' env['FOPT'] = '-O0 -ggdb' if args.gcov: import distutils.sysconfig cvars = distutils.sysconfig.get_config_vars() env['OPT'] = '-O0 -ggdb' env['FOPT'] = '-O0 -ggdb' env['CC'] = cvars['CC'] + ' --coverage' env['CXX'] = cvars['CXX'] + ' --coverage' env['F77'] = 'gfortran --coverage ' env['F90'] = 'gfortran --coverage ' env['LDSHARED'] = cvars['LDSHARED'] + ' --coverage' env['LDFLAGS'] = " ".join(cvars['LDSHARED'].split()[1:]) + ' --coverage' cmd += ["build"] if args.parallel > 1: cmd += ["-j", str(args.parallel)] cmd += ['install', '--prefix=' + dst_dir] log_filename = os.path.join(ROOT_DIR, 'build.log') if args.show_build_log: ret = subprocess.call(cmd, env=env, cwd=ROOT_DIR) else: log_filename = os.path.join(ROOT_DIR, 'build.log') print("Building, see build.log...") with open(log_filename, 'w') as log: p = subprocess.Popen(cmd, env=env, stdout=log, stderr=log, cwd=ROOT_DIR) # Wait for it to finish, and print something to indicate the # process is alive, but only if the log file has grown (to # allow continuous integration environments kill a hanging # process accurately if it produces no output) last_blip = time.time() last_log_size = os.stat(log_filename).st_size while p.poll() is None: time.sleep(0.5) if time.time() - last_blip > 60: log_size = os.stat(log_filename).st_size if log_size > last_log_size: print(" ... build in progress") last_blip = time.time() last_log_size = log_size ret = p.wait() if ret == 0: print("Build OK") else: if not args.show_build_log: with open(log_filename, 'r') as f: print(f.read()) print("Build failed!") sys.exit(1) from distutils.sysconfig import get_python_lib site_dir = get_python_lib(prefix=dst_dir, plat_specific=True) return site_dir # # GCOV support # def gcov_reset_counters(): print("Removing previous GCOV .gcda files...") build_dir = os.path.join(ROOT_DIR, 'build') for dirpath, dirnames, filenames in os.walk(build_dir): for fn in filenames: if fn.endswith('.gcda') or fn.endswith('.da'): pth = os.path.join(dirpath, fn) os.unlink(pth) # # LCOV support # LCOV_OUTPUT_FILE = os.path.join(ROOT_DIR, 'build', 'lcov.out') LCOV_HTML_DIR = os.path.join(ROOT_DIR, 'build', 'lcov') def lcov_generate(): try: os.unlink(LCOV_OUTPUT_FILE) except OSError: pass try: shutil.rmtree(LCOV_HTML_DIR) except OSError: pass print("Capturing lcov info...") subprocess.call(['lcov', '-q', '-c', '-d', os.path.join(ROOT_DIR, 'build'), '-b', ROOT_DIR, '--output-file', LCOV_OUTPUT_FILE]) print("Generating lcov HTML output...") ret = subprocess.call(['genhtml', '-q', LCOV_OUTPUT_FILE, '--output-directory', LCOV_HTML_DIR, '--legend', '--highlight']) if ret != 0: print("genhtml failed!") else: print("HTML output generated under build/lcov/") # # Python 3 support # if sys.version_info[0] >= 3: import builtins exec_ = getattr(builtins, "exec") else: def exec_(code, globs=None, locs=None): """Execute code in a namespace.""" if globs is None: frame = sys._getframe(1) globs = frame.f_globals if locs is None: locs = frame.f_locals del frame elif locs is None: locs = globs exec("""exec code in globs, locs""") if __name__ == "__main__": main(argv=sys.argv[1:])<|fim▁end|>
$ python runtests.py $ python runtests.py -s {SAMPLE_SUBMODULE} $ python runtests.py -t {SAMPLE_TEST}
<|file_name|>ManifestRDFUtils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # # Coypyright (C) 2010, University of Oxford # # Licensed under the MIT License. You may obtain a copy of the License at: # # http://www.opensource.org/licenses/mit-license.php # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # $Id: $ """ Support functions for creating, reading, writing and updating manifest RDF file. """ __author__ = "Bhavana Ananda" __version__ = "0.1" import logging, os, rdflib from os.path import isdir from rdflib import URIRef, Namespace, BNode from rdflib.namespace import RDF from rdflib.graph import Graph from rdflib.plugins.memory import Memory from rdflib import Literal Logger = logging.getLogger("MaifestRDFUtils") oxds = URIRef("http://vocab.ox.ac.uk/dataset/schema#") oxdsGroupingUri = URIRef(oxds+"Grouping") def bindNamespaces(rdfGraph, namespaceDict): # Bind namespaces for key in namespaceDict: keyValue = namespaceDict[key] Logger.debug(key+":"+keyValue) rdfGraph.bind( key, keyValue , override=True) # rdfGraph.bind("dcterms", dcterms, override=True)<|fim▁hole|> # URIRef(dcterms+elementList[index]) return rdfGraph def readManifestFile(manifestPath): """ Read from the manifest file. manifestPath manifest file path """ # Read from the manifest.rdf file into an RDF Graph rdfGraph = Graph() rdfGraph.parse(manifestPath) return rdfGraph def writeToManifestFile(manifestPath, namespaceDict, elementUriList,elementValueList): """ Write to the manifest file. manifestPath manifest file path elementUriList Element Uri List to be written into the manifest files elementValueList Element Values List to be written into the manifest files """ # Create an empty RDF Graph rdfGraph = Graph() subject = BNode() rdfGraph = bindNamespaces(rdfGraph, namespaceDict) # Write to the RDF Graph rdfGraph.add((subject, RDF.type, oxdsGroupingUri)) for index in range(len(elementUriList)): rdfGraph.add((subject,elementUriList[index], Literal(elementValueList[index]))) # Serialise it to a manifest.rdf file saveToManifestFile(rdfGraph, manifestPath) return rdfGraph def updateManifestFile(manifestPath, elementUriList, elementValueList): """ Update the manifest file. manifestPath manifest file path elementUriList Element Uri List whose values need to be to be updated in the manifest files elementValueList Element Values List to be updated into the manifest files """ # Read the manifest file and update the title and the description rdfGraph = readManifestFile(manifestPath) subject = rdfGraph.value(None,RDF.type, oxdsGroupingUri) if subject == None : subject = BNode() for index in range(len(elementUriList)): rdfGraph.set((subject, elementUriList[index], Literal(elementValueList[index]))) saveToManifestFile(rdfGraph,manifestPath) return rdfGraph def saveToManifestFile(rdfGraph, manifestPath): """ Save the RDF Graph into a manifest file. rdfGraph RDF Graph to be serialised into the manifest file manifestPath manifest file path """ # Serialise the RDf Graph into manifest.rdf file rdfGraph.serialize(destination=manifestPath, format='pretty-xml') return def compareRDFGraphs(graphA, graphB, elementUriListToCompare=[]): """ Compare two RDG graphs graphA RDF Graph of Graph A graphB RDF Graph of Graph B graphsEqual Return True if the two graphs are equal or false otherwise """ def graphContains(graph, statement): (s,p,o) = statement if isinstance(s, BNode): s = None if isinstance(p, BNode): p = None if isinstance(o, BNode): o = None return (s,p,o) in graph graphsEqual = True for statement in graphA: if not graphContains(graphB, statement) : return False for statement in graphB: if not graphContains(graphA, statement) : return False subjectA = graphA.value(None,RDF.type, oxdsGroupingUri) subjectB = graphB.value(None,RDF.type, oxdsGroupingUri) for elementUri in elementUriListToCompare : if graphA.value(subjectA,elementUri,None)!=graphB.value(subjectB,elementUri,None) : graphsEqual = False return graphsEqual def getElementValuesFromManifest(rdfGraph,elementUriList): """ Get element values of the element list supplied from the RDF graph rdfGraph RDF Graph elementUriList Element Uri List whose values need to be to be extracted from the manifest files """ elementValueList = [] subject = rdfGraph.value(None, RDF.type, oxdsGroupingUri) for elementUri in elementUriList: elementValueList.append(rdfGraph.value(subject,elementUri,None)) Logger.debug("Element Uri List =" + repr(elementUriList)) Logger.debug("Element Value List =" + repr(elementValueList)) return elementValueList def getDictionaryFromManifest(manifestPath, elementUriList): """ Gets the dictionary of Field-Values from the manifest RDF manifestPath path of the manifest file elementList Element Names List whose values need to be to be updated in the manifest files """ file = None elementValueList = [] elementList = [] dict = {} json = "" Logger.debug(manifestPath) if manifestPath != None and ifFileExists(manifestPath): rdfGraph = readManifestFile(manifestPath) elementValueList = getElementValuesFromManifest(rdfGraph, elementUriList) # Logger.debug("Element URi List =" + repr(elementUriList)) # Logger.debug("Element Value List =" + repr(elementValueList)) for index in range(len(elementUriList)): Logger.debug("Index = " + repr(index)) elementUri = elementUriList[index] position = elementUri.rfind("/") +1 elementList.append(elementUri[position:]) Logger.debug("substring = " + elementUri[position:]) if elementValueList!=[]: dict = createDictionary(elementList, elementValueList) return dict def ifFileExists(filePath): """ Cheks if the file exists; returns True/False filePath File Path """ return os.path.isfile(filePath) def createDictionary(keyList, valueList): """ Creates and returns a dictionary from the keyList and valueList supplied keyUriList List of key uris valueList List of values """ dict = {} for index in range(len(keyList)): dict[keyList[index]] = valueList[index] # Logger.debug(" Key Uri List = "+ repr(keyUriList)) # Logger.debug(" Key value list = "+ repr(valueList)) return dict<|fim▁end|>
# rdfGraph.bind("oxds", oxds, override=True)
<|file_name|>jstool.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import os import sys import argparse import requests import subprocess import shutil class bcolors: HEADER = '\033[90m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' class Console: def __init__(self): self.verbose = False def log(self, string): if self.verbose: print string console = Console() def filter_no_console(line): if 'console' in line: return False return True def consolidate(input_filename, output_filename, filter_functions=None): # read all filenames from input file filenames = [line.rstrip('\n') for line in open(input_filename)] # concat all lines in each file to the output file with open(output_filename, 'w') as outfile: for filename in filenames: if filename.startswith('#') or len(filename) <= 0: continue console.log(bcolors.HEADER + filename + bcolors.ENDC) with open(filename) as infile: # write a header outfile.write("/*\n* " + filename + "\n*/\n") # write contents for index, line in enumerate(infile): # apply filter functions if isinstance(filter_functions, list) and len(filter_functions) > 0: add_line = True for filter_function in filter_functions: if not filter_function(line): add_line = False break if add_line: outfile.write(line) else: console.log('- line ' + str(index) + ': ' + bcolors.FAIL + line.lstrip().rstrip() + bcolors.ENDC) # no filters else: outfile.write(line) # newline outfile.write("\n") def compression_level_to_string(optimization_level): if optimization_level >= 3: compliation_level = 'ADVANCED_OPTIMIZATIONS' elif optimization_level >= 2: compliation_level = 'SIMPLE_OPTIMIZATIONS' else: compliation_level = 'WHITESPACE_ONLY' return compliation_level def get_minified_filename(filename): return os.path.splitext(filename)[0] + '.min.js' def compress_local(filename, optimization_level, compiler_path): # java -jar compiler.jar --js hello.js --js_output_file hello-compiled.js console.log('compiling with ' + compiler_path) subprocess.call(['java', '-jar', compiler_path, '--js', filename, '--js_output_file', filename, '--compilation_level', compression_level_to_string(optimization_level) ]) console.log(bcolors.OKGREEN + filename + ' created' + bcolors.ENDC) def compress_remote(filename, optimization_level): SERVICE_URL = 'http://closure-compiler.appspot.com/compile' console.log('compiling with google closure API: ' + SERVICE_URL) with open(filename, 'r') as file: javascript = file.read() data = { 'js_code': javascript, 'output_format': 'text', 'output_info': 'compiled_code', 'compilation_level': compression_level_to_string(optimization_level) } headers = { 'Content-type': 'application/x-www-form-urlencoded' } r = requests.post(SERVICE_URL, data=data, headers=headers) result = r.text with open(filename, 'w') as outfile: outfile.write(result) console.log(bcolors.OKGREEN + filename + ' created' + bcolors.ENDC) def main(argv): parser = argparse.ArgumentParser() parser.add_argument('-v, --verbose', dest='verbose', default=False, action='store_true', help='detailed program output') parser.add_argument('-i, --input', required=True, dest='input_file', type=str, help='input file (required), containing one filename per line to compile') parser.add_argument('-o, --output', dest='output_file', default='output.js', type=str, help='output file') parser.add_argument('-c, --compression', default=0, dest='compress', type=int, help='compression level of output file\n0: no compression\n1: strip whitespace\n2: simple\n3: advanced') parser.add_argument('--compiler', default=None, dest='compiler_path', type=str, help='path to closure compiler jar file. If not specified, online closure API will be used instead') parser.add_argument('--filter-console', default=False, dest='no_console', help='strips console calls', action='store_true') args = parser.parse_args() console.verbose = args.verbose filters=[] if args.no_console: filters.append(filter_no_console) output_filename = args.output_file consolidate(input_filename=args.input_file, output_filename=output_filename, filter_functions=filters) min_output_filename = get_minified_filename(output_filename) if(args.compress > 0): if(args.compiler_path is not None): compress_local(min_output_filename, optimization_level=args.compress, compiler_path=args.compiler_path) else: compress_remote(min_output_filename, optimization_level=args.compress) else: # no compression was done, but we still want *.min.js shutil.copyfile(output_filename, min_output_filename)<|fim▁hole|><|fim▁end|>
if __name__ == "__main__": main(sys.argv[1:])
<|file_name|>locustfile.py<|end_file_name|><|fim▁begin|>from locust import HttpLocust, TaskSet, task class WebsiteTasks(TaskSet): @task def page1(self): self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/") @task def page2(self): self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/") @task def page3(self): self.client.get("/sugestoes-para/4a-feira-da-quarta-semana-da-pascoa/") @task def page4(self): self.client.get("/sugestoes-para/3a-feira-da-quarta-semana-da-pascoa/") @task def musica1(self): self.client.get("/musica/ressuscitou/") @task def musica2(self): self.client.get("/musica/prova-de-amor-maior-nao-ha/") @task def musica3(self): self.client.get("/musica/porque-ele-vive/") @task def musica4(self): self.client.get("/musica/o-senhor-ressuscitou-aleluia/") <|fim▁hole|>class WebsiteUser(HttpLocust): task_set = WebsiteTasks min_wait = 5000 max_wait = 15000<|fim▁end|>
<|file_name|>bg_BG.js<|end_file_name|><|fim▁begin|>OC.L10N.register( "updatenotification", { "Update notifications" : "Обновяване на известията", "{version} is available. Get more information on how to update." : "{version} е излязла. Прочетете повече как да обновите до нея. ", "Updated channel" : "Обновен канал", "ownCloud core" : "ownCloud core", "Update for %1$s to version %2$s is available." : "Излязло е ново обновление за %1$s до версия %2$s .", "Updater" : "Център за обновяване", "A new version is available: %s" : "Излязла е нова версия: %s", "Open updater" : "Отворяне на център за обновяване",<|fim▁hole|> "You can always update to a newer version / experimental channel. But you can never downgrade to a more stable channel." : "Винаги може да обновите до по-нова версия / експирементален канал. Но не можете вече да върнете до по-стабилен канал.", "Notify members of the following groups about available updates:" : "Уведомяване на членовете на следните групи за излязлите нови версии:", "Only notification for app updates are available, because the selected update channel for ownCloud itself does not allow notifications." : "Има само известия за обновения на приложения, защото избраният канал за обновяване на ownCloud не предоставя известия." }, "nplurals=2; plural=(n != 1);");<|fim▁end|>
"Show changelog" : "Показване на доклада с промени", "Your version is up to date." : "Вие разполагате с най-новата версия.", "Checked on %s" : "Проверено на %s", "Update channel:" : "Обновяване на канал:",
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import StreamingHttpResponse, HttpResponseServerError from download_service.zipbuilder import DDSZipBuilder, NotFoundException, NotSupportedException from django.contrib.auth.decorators import login_required from download_service.utils import make_client from django.http import Http404 @login_required def dds_project_zip(request, project_id, filename): client = make_client(request.user) builder = DDSZipBuilder(project_id, client) try: builder.raise_on_filename_mismatch(filename) response = StreamingHttpResponse(builder.build_streaming_zipfile(), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename={}'.format(filename) return response<|fim▁hole|><|fim▁end|>
except NotFoundException as e: raise Http404(str(e)) except NotSupportedException as e: return HttpResponseServerError(content=str(e))
<|file_name|>cronjob.go<|end_file_name|><|fim▁begin|>/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internalversion import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" api "k8s.io/kubernetes/pkg/api" batch "k8s.io/kubernetes/pkg/apis/batch" restclient "k8s.io/kubernetes/pkg/client/restclient" ) // CronJobsGetter has a method to return a CronJobInterface. // A group's client should implement this interface. type CronJobsGetter interface { CronJobs(namespace string) CronJobInterface } // CronJobInterface has methods to work with CronJob resources. type CronJobInterface interface { Create(*batch.CronJob) (*batch.CronJob, error) Update(*batch.CronJob) (*batch.CronJob, error) UpdateStatus(*batch.CronJob) (*batch.CronJob, error) Delete(name string, options *api.DeleteOptions) error DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error Get(name string, options v1.GetOptions) (*batch.CronJob, error) List(opts api.ListOptions) (*batch.CronJobList, error) Watch(opts api.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *batch.CronJob, err error) CronJobExpansion } // cronJobs implements CronJobInterface type cronJobs struct { client restclient.Interface ns string } // newCronJobs returns a CronJobs func newCronJobs(c *BatchClient, namespace string) *cronJobs { return &cronJobs{ client: c.RESTClient(), ns: namespace, } } // Create takes the representation of a cronJob and creates it. Returns the server's representation of the cronJob, and an error, if there is any. func (c *cronJobs) Create(cronJob *batch.CronJob) (result *batch.CronJob, err error) { result = &batch.CronJob{} err = c.client.Post(). Namespace(c.ns). Resource("cronjobs"). Body(cronJob). Do(). Into(result) return } // Update takes the representation of a cronJob and updates it. Returns the server's representation of the cronJob, and an error, if there is any. func (c *cronJobs) Update(cronJob *batch.CronJob) (result *batch.CronJob, err error) { result = &batch.CronJob{} err = c.client.Put(). Namespace(c.ns). Resource("cronjobs"). Name(cronJob.Name). Body(cronJob). Do(). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclientstatus=false comment above the type to avoid generating UpdateStatus(). func (c *cronJobs) UpdateStatus(cronJob *batch.CronJob) (result *batch.CronJob, err error) { result = &batch.CronJob{} err = c.client.Put(). Namespace(c.ns). Resource("cronjobs"). Name(cronJob.Name). SubResource("status"). Body(cronJob). Do(). Into(result) return } // Delete takes name of the cronJob and deletes it. Returns an error if one occurs. func (c *cronJobs) Delete(name string, options *api.DeleteOptions) error {<|fim▁hole|> Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *cronJobs) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("cronjobs"). VersionedParams(&listOptions, api.ParameterCodec). Body(options). Do(). Error() } // Get takes name of the cronJob, and returns the corresponding cronJob object, and an error if there is any. func (c *cronJobs) Get(name string, options v1.GetOptions) (result *batch.CronJob, err error) { result = &batch.CronJob{} err = c.client.Get(). Namespace(c.ns). Resource("cronjobs"). Name(name). VersionedParams(&options, api.ParameterCodec). Do(). Into(result) return } // List takes label and field selectors, and returns the list of CronJobs that match those selectors. func (c *cronJobs) List(opts api.ListOptions) (result *batch.CronJobList, err error) { result = &batch.CronJobList{} err = c.client.Get(). Namespace(c.ns). Resource("cronjobs"). VersionedParams(&opts, api.ParameterCodec). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested cronJobs. func (c *cronJobs) Watch(opts api.ListOptions) (watch.Interface, error) { return c.client.Get(). Prefix("watch"). Namespace(c.ns). Resource("cronjobs"). VersionedParams(&opts, api.ParameterCodec). Watch() } // Patch applies the patch and returns the patched cronJob. func (c *cronJobs) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *batch.CronJob, err error) { result = &batch.CronJob{} err = c.client.Patch(pt). Namespace(c.ns). Resource("cronjobs"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }<|fim▁end|>
return c.client.Delete(). Namespace(c.ns). Resource("cronjobs").
<|file_name|>Entry.js<|end_file_name|><|fim▁begin|>'use strict';<|fim▁hole|>import shortid from 'shortid'; const EntrySchema = new Schema({ _id: { type: String, unique: true, default: shortid.generate }, stepRef: { type: String, ref: 'Step' }, name: String, value: String, dateCreated: { type: Date, default: Date.now }, dateUpdated: { type: Date } }); const Entry = mongoose.model('Entry', EntrySchema); export default Entry;<|fim▁end|>
import { Schema } from 'mongoose';
<|file_name|>tiledb_ls.cc<|end_file_name|><|fim▁begin|>/** * @file tiledb_list.cc * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2016 MIT and Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @section DESCRIPTION * * It shows how to explore the contents of a TileDB directory. */ #include "tiledb.h" #include <cstdio> #include <cstdlib> int main(int argc, char** argv) { // Sanity check if(argc != 2) { fprintf(stderr, "Usage: ./tiledb_list parent_dir\n"); return -1; } // Initialize context with the default configuration parameters TileDB_CTX* tiledb_ctx; tiledb_ctx_init(&tiledb_ctx, NULL); // Retrieve number of directories int dir_num; tiledb_ls_c(tiledb_ctx, argv[1], &dir_num); // Exit if there are not TileDB objects in the input directory_ if(dir_num == 0) return 0; // Initialize variables char** dirs = new char*[dir_num]; int* dir_types = new int[dir_num]; for(int i=0; i<dir_num; ++i) dirs[i] = (char*) malloc(TILEDB_NAME_MAX_LEN); // List TileDB objects tiledb_ls(<|fim▁hole|> &dir_num); // Directory number // Print TileDB objects for(int i=0; i<dir_num; ++i) { printf("%s ", dirs[i]); if(dir_types[i] == TILEDB_ARRAY) printf("ARRAY\n"); else if(dir_types[i] == TILEDB_METADATA) printf("METADATA\n"); else if(dir_types[i] == TILEDB_GROUP) printf("GROUP\n"); else if(dir_types[i] == TILEDB_WORKSPACE) printf("WORKSPACE\n"); } // Clean up for(int i=0; i<dir_num; ++i) free(dirs[i]); free(dirs); free(dir_types); // Finalize context tiledb_ctx_finalize(tiledb_ctx); return 0; }<|fim▁end|>
tiledb_ctx, // Context argv[1], // Parent directory dirs, // Directories dir_types, // Directory types
<|file_name|>test_attachwatcher.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil from tempfile import mkdtemp import wx from outwiker.core.attachment import Attachment from outwiker.core.tree import WikiDocument from outwiker.pages.text.textpage import TextPageFactory from outwiker.core.application import Application from outwiker.core.attachwatcher import AttachWatcher from test.utils import removeDir from test.basetestcases import BaseWxTestCase class AttachWatcherTest(BaseWxTestCase): def setUp(self): super().setUp() self._eventCount = 0 self._period_ms = 50 self._application = Application self._application.onAttachListChanged += self._onAttachListChanged # Path to path with files self._sample_path = '../test/samplefiles' # Path to wiki self.path = mkdtemp(prefix='OutWiker AttachWatcherTest Тесты') self.wikiroot = WikiDocument.create(self.path) self.page_01 = TextPageFactory().create(self.wikiroot, "Страница 1", []) self.page_02 = TextPageFactory().create(self.wikiroot, "Страница 2", []) def tearDown(self): super().tearDown() self._application.onAttachListChanged -= self._onAttachListChanged removeDir(self.path) def _onAttachListChanged(self, page, params): self._eventCount += 1 def _attach_files(self, page, files_list): ''' Copy files to attachments without explicit onAttachListChanged event calling. ''' files_full = [os.path.join(self._sample_path, fname) for fname in files_list] attach = Attachment(page) attach_path = attach.getAttachPath(True) for fname in files_full: shutil.copy(fname, attach_path) def test_empty_01(self): ''' Wiki is not added to Application ''' watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_02(self): ''' Wiki added to Application _before_ AttachWatcher initializing. No selected pages. ''' self._application.wikiroot = self.wikiroot watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_03(self): ''' Wiki added to Application _after_ AttachWatcher initializing. No selected pages. ''' watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.wikiroot = self.wikiroot wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_04(self): ''' Wiki added to Application _before_ AttachWatcher initializing. Selected page. ''' self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_05(self): ''' Wiki added to Application _after_ AttachWatcher initializing. Selected page. ''' watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_06(self): ''' Change the selected page ''' self._application.wikiroot = self.wikiroot self._application.selectedPage = None watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.selectedPage = self.page_01 wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_07(self): ''' Change the selected page ''' self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.selectedPage = None wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_08(self): ''' Change the selected page ''' self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.selectedPage = self.page_02 wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_09_close_wiki(self): ''' Close current notes tree ''' self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.wikiroot = None wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_empty_10_create_empty_attach_dir(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() Attachment(self._application.selectedPage).getAttachPath(True) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_files_not_change_01(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_files_not_change_02(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = None self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.selectedPage = self.page_01 wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_files_not_change_03(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = None self._attach_files(self.page_01, ['add.png']) self._attach_files(self.page_02, ['add.png', 'dir.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() # Switch pages self._application.selectedPage = self.page_01 self._application.selectedPage = self.page_02 wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_files_not_change_04(self): self._attach_files(self.page_01, ['add.png']) self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() # Close the wiki self._application.wikiroot = None wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_add_files_01(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._attach_files(self.page_01, ['add.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_add_files_02(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._attach_files(self.page_01, ['add.png', 'dir.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_add_files_03(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._attach_files(self.page_01, ['add.png']) wx.MilliSleep(500) self.myYield() self._attach_files(self.page_01, ['dir.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 2) def test_attach_touch_read(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() attach = Attachment(self.page_01) with open(attach.getFullPath('add.png')): pass wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_attach_touch_write(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() attach = Attachment(self.page_01) with open(attach.getFullPath('add.png'), 'w'): pass wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_attach_rename(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) attach = Attachment(self.page_01) src_fname = attach.getFullPath('add.png') dest_fname = attach.getFullPath('newname.png') watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() os.rename(src_fname, dest_fname) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_attach_delete(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() attach = Attachment(self.page_01) attach.removeAttach(['add.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_switch_and_add_file(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) self._attach_files(self.page_02, ['add.png', 'dir.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() # Switch pages self._application.selectedPage = self.page_02 self._attach_files(self.page_02, ['accept.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_close_wiki(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.wikiroot = None self._attach_files(self.page_01, ['dir.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_unselect_page(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.selectedPage = None self._attach_files(self.page_01, ['dir.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_select_again(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.selectedPage = None self._attach_files(self.page_01, ['dir.png']) self._application.selectedPage = self.page_01 wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_select_again_and_add(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self._application.selectedPage = None self._attach_files(self.page_01, ['dir.png']) self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['accept.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_rename_page_01(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self.page_01.title = 'Новый заголовок' wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_rename_page_02(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self.page_01.title = 'Новый заголовок' wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_rename_page_03(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self.page_01.title = 'Новый заголовок' self._attach_files(self.page_01, ['dir.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_delete_page_01(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self.page_01.remove() wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_delete_page_02(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self.page_01.remove() self._application.selectedPage = self.page_02 self._attach_files(self.page_02, ['add.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_move_to_page_01(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self.page_01.moveTo(self.page_02) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_move_to_page_02(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() self.page_01.moveTo(self.page_02) self._attach_files(self.page_01, ['add.png']) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_remove_empty_attach_dir(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 attach = Attachment(self.page_01) attach_dir = attach.getAttachPath(True) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() shutil.rmtree(attach_dir) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 0) def test_remove_attach_dir(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 attach = Attachment(self.page_01) attach_dir = attach.getAttachPath(True) self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, self._period_ms) watcher.initialize() shutil.rmtree(attach_dir) wx.MilliSleep(500) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1) def test_race_01(self): self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 self._attach_files(self.page_01, ['add.png']) watcher = AttachWatcher(self._application, 500) watcher.initialize() self._application.selectedPage = self.page_02 wx.MilliSleep(1000) self.myYield()<|fim▁hole|> self._application.wikiroot = self.wikiroot self._application.selectedPage = self.page_01 watcher = AttachWatcher(self._application, 500) watcher.initialize() self._attach_files(self.page_01, ['add.png']) self._application.selectedPage = self.page_02 wx.MilliSleep(1000) self.myYield() watcher.clear() self.assertEqual(self._eventCount, 1)<|fim▁end|>
watcher.clear() self.assertEqual(self._eventCount, 0) def test_race_02(self):
<|file_name|>shared.service.ts<|end_file_name|><|fim▁begin|>import { Injectable, ViewContainerRef, ComponentFactoryResolver, Output, EventEmitter } from '@angular/core'; import { Util } from './util/util'; @Injectable() export class SharedService { _util: Util; @Output() sendmsg: EventEmitter<any> = new EventEmitter();<|fim▁hole|> constructor(private _resolver: ComponentFactoryResolver) { this._util = new Util(); } doSendMsg(msg: string, config: any = null) { this.sendmsg.emit({target:this, msg:msg, config:config}); } showMsg(drawer: any, parentEl: ViewContainerRef, msg: string, direction: string = 'top', cls: string = 'red') { let config = {message: msg, direction: direction, cls: cls, zIndex: 1001}; let cmp: any = this.showDrawer(drawer, parentEl, config); cmp.instance.hided.subscribe((e: any) => { cmp.destroy(); }); return cmp; } showDrawer(drawer: any, parentEl: ViewContainerRef, config: any, show: boolean = true) { let cmp: any = this.addComponent(drawer, config, parentEl); if (show) cmp.instance.show(); return cmp; } addComponent(cmpType: any, config: any = {}, parentEl: ViewContainerRef, idx: number = 0) { //http://stackoverflow.com/questions/39297219/angular2-rc6-dynamically-load-component-from-module let factory = this._resolver.resolveComponentFactory(cmpType); let cmp: any = parentEl.createComponent(factory); cmp.instance['config'] = config; return cmp; } util() { return this._util; } isLoggedIn() { return this._util.isLoggedIn(); } getUserId() { return this._util.getUserId(); } validator() { return this._util.validator(); } //data access dataAccess() { return this._util.dataAccess(); } //dom dom() { return this._util.dom(); } }<|fim▁end|>
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>""" Django settings for sparta project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')mg$xo^v*2mmwidr0ak6%9&!@e18v8t#7@+vd+wqg8kydb48k7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'sparta.urls' WSGI_APPLICATION = 'sparta.wsgi.application'<|fim▁hole|> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER':'root', 'NAME':'fordjango', 'PASSWORD':'123456', 'HOST':'localhost', 'PORT':'' } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_ROOT = os.path.join('/home/dexter/weaponx/Django/sparta/sparta/static') STATIC_URL = '/assets/' STATICFILES_DIRS = ( '/home/dexter/weaponx/Django/sparta/sparta/assets', ) TEMPLATE_DIRS=('/home/dexter/weaponx/Django/sparta/sparta/template',)<|fim▁end|>
# Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases
<|file_name|>checkwholepdb.py<|end_file_name|><|fim▁begin|># Test which PDB entries error on PDB/mmCIF parsers # Writes output to a file labelled with the week import os from datetime import datetime from math import ceil<|fim▁hole|>start = datetime.now() basedir = "." pdbl = PDBList() pdblist = pdbl.get_all_entries() outstrs = ["Checking all PDB entries at {}".format(start.isoformat()), "Checking {} entries".format(len(pdblist))] pdb_parser = PDBParser() mmcif_parser = MMCIFParser() for pu in sorted(pdblist): p = pu.lower() try: pdbl.retrieve_pdb_file(p, pdir=basedir, file_format="pdb") except: # Not having a PDB file is acceptable, though a failure to download an # available file may hide an error in parsing try: os.remove("{}/pdb{}.ent".format(basedir, p)) except: pass if os.path.isfile("{}/pdb{}.ent".format(basedir, p)): try: s = pdb_parser.get_structure("", "{}/pdb{}.ent".format(basedir, p)) except: outstrs.append("{} - PDB parsing error".format(pu)) os.remove("{}/pdb{}.ent".format(basedir, p)) try: pdbl.retrieve_pdb_file(p, pdir=basedir, file_format="mmCif") except: try: os.remove("{}/{}.cif".format(basedir, p)) except: pass outstrs.append("{} - no mmCIF download".format(pu)) if os.path.isfile("{}/{}.cif".format(basedir, p)): try: s = mmcif_parser.get_structure("", "{}/{}.cif".format(basedir, p)) except: outstrs.append("{} - mmCIF parsing error".format(pu)) os.remove("{}/{}.cif".format(basedir, p)) if len(outstrs) == 2: outstrs.append("All entries read fine") end = datetime.now() outstrs.append("Time taken - {} minute(s)".format(int(ceil((end - start).seconds / 60)))) datestr = str(end.date()).replace("-", "") # This overwrites any existing file with open("{}/wholepdb_py_{}.txt".format(basedir, datestr), "w") as f: for l in outstrs: f.write(l + "\n")<|fim▁end|>
from Bio.PDB import PDBList from Bio.PDB.PDBParser import PDBParser from Bio.PDB.MMCIFParser import MMCIFParser
<|file_name|>imageVisual.ts<|end_file_name|><|fim▁begin|><|fim▁hole|> * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /// <reference path="../_references.ts"/> module powerbi.visuals { import Utility = jsCommon.Utility; export var imageScalingType = { normal: "Normal", fit: "Fit", fill: "Fill" }; export interface ImageDataViewObjects extends DataViewObjects { general: ImageDataViewObject; imageScaling: ImageScalingDataViewObject; } export interface ImageDataViewObject extends DataViewObject { imageUrl: string; } export interface ImageScalingDataViewObject extends DataViewObject { imageScalingType: string; } export class ImageVisual implements IVisual { private element: JQuery; private imageBackgroundElement: JQuery; private scalingType: string = imageScalingType.normal; public init(options: VisualInitOptions) { this.element = options.element; } public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] { switch (options.objectName) { case 'imageScaling': return this.enumerateImageScaling(); } return null; } private enumerateImageScaling(): VisualObjectInstance[] { return [{ selector: null, objectName: 'imageScaling', properties: { imageScalingType: this.scalingType, } }]; } public onDataChanged(options: VisualDataChangedOptions): void { var dataViews = options.dataViews; if (!dataViews || dataViews.length === 0) return; var objects = <ImageDataViewObjects>dataViews[0].metadata.objects; if (!objects || !objects.general) return; var div: JQuery = this.imageBackgroundElement; if (!div) { div = $("<div class='imageBackground' />"); this.imageBackgroundElement = div; this.imageBackgroundElement.appendTo(this.element); } var imageUrl = objects.general.imageUrl; if (objects.imageScaling) this.scalingType = objects.imageScaling.imageScalingType.toString(); else this.scalingType = imageScalingType.normal; if (Utility.isValidImageDataUrl(imageUrl)) div.css("backgroundImage", "url(" + imageUrl + ")"); if (this.scalingType === imageScalingType.fit) div.css("background-size", "100% 100%"); else if (this.scalingType === imageScalingType.fill) div.css("background-size", "cover"); else div.css("background-size", "contain"); } public onResizing(viewport: IViewport): void { } } }<|fim▁end|>
/*
<|file_name|>SingleSourceHelperImpl.java<|end_file_name|><|fim▁begin|>package org.csstudio.swt.xygraph.util; import org.csstudio.swt.xygraph.figures.XYGraph; import org.eclipse.draw2d.FigureUtilities; import org.eclipse.draw2d.SWTGraphics; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; public class SingleSourceHelperImpl extends SingleSourceHelper { @Override protected Cursor createInternalCursor(Display display, ImageData imageData, int width, int height, int style) { return new Cursor(display, imageData, width, height); } @Override protected Image createInternalVerticalTextImage(String text, Font font, RGB color, boolean upToDown) { final Dimension titleSize = FigureUtilities.getTextExtents(text, font); final int w = titleSize.height; final int h = titleSize.width + 1; Image image = new Image(Display.getCurrent(), w, h); final GC gc = new GC(image); final Color titleColor = new Color(Display.getCurrent(), color); RGB transparentRGB = new RGB(240, 240, 240); gc.setBackground(XYGraphMediaFactory.getInstance().getColor( transparentRGB)); gc.fillRectangle(image.getBounds()); gc.setForeground(titleColor); gc.setFont(font); final Transform tr = new Transform(Display.getCurrent()); if (!upToDown) { tr.translate(0, h); tr.rotate(-90); gc.setTransform(tr); } else { tr.translate(w, 0); tr.rotate(90); gc.setTransform(tr); } gc.drawText(text, 0, 0); tr.dispose(); gc.dispose(); final ImageData imageData = image.getImageData(); image.dispose(); titleColor.dispose(); imageData.transparentPixel = imageData.palette.getPixel(transparentRGB); image = new Image(Display.getCurrent(), imageData); return image; } @Override protected Image getInternalXYGraphSnapShot(XYGraph xyGraph) { Rectangle bounds = xyGraph.getBounds(); Image image = new Image(null, bounds.width + 6, bounds.height + 6); GC gc = new GC(image); SWTGraphics graphics = new SWTGraphics(gc); graphics.translate(-bounds.x + 3, -bounds.y + 3); graphics.setForegroundColor(xyGraph.getForegroundColor()); graphics.setBackgroundColor(xyGraph.getBackgroundColor()); xyGraph.paint(graphics); gc.dispose(); return image; } @Override protected String getInternalImageSavePath() { FileDialog dialog = new FileDialog(Display.getDefault().getShells()[0], SWT.SAVE); dialog.setFilterNames(new String[] { "PNG Files", "All Files (*.*)" }); dialog.setFilterExtensions(new String[] { "*.png", "*.*" }); // Windows String path = dialog.open(); return path; } <|fim▁hole|><|fim▁end|>
}
<|file_name|>lru_cache_test.py<|end_file_name|><|fim▁begin|># Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test LRUCache by running different input batch sizes on same network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes<|fim▁hole|>from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.platform import test class LRUCacheTest(trt_test.TfTrtIntegrationTestBase): def GetParams(self): dtype = dtypes.float32 input_name = "input" input_dims = [[[1, 10, 10, 2]], [[2, 10, 10, 2]], [[4, 10, 10, 2]], [[2, 10, 10, 2]]] expected_output_dims = [[[1, 10, 10, 1]], [[2, 10, 10, 1]], [[4, 10, 10, 1]], [[2, 10, 10, 1]]] output_name = "output" g = ops.Graph() with g.as_default(): x = array_ops.placeholder( dtype=dtype, shape=[None, 10, 10, 2], name=input_name) conv_filter = constant_op.constant( np.random.randn(3, 3, 2, 1), dtype=dtypes.float32) x = nn.conv2d( input=x, filter=conv_filter, strides=[1, 1, 1, 1], padding="SAME", name="conv") bias = constant_op.constant( np.random.randn(1, 10, 10, 1), dtype=dtypes.float32) x = math_ops.add(x, bias) x = nn.relu(x) x = array_ops.identity(x, name="output") return trt_test.TfTrtIntegrationTestParams( gdef=g.as_graph_def(), input_names=[input_name], input_dims=input_dims, output_names=[output_name], expected_output_dims=expected_output_dims) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return ["TRTEngineOp_0"] def ShouldRunTest(self, run_params): return (run_params.dynamic_engine and not trt_test.IsQuantizationMode(run_params.precision_mode)) if __name__ == "__main__": test.main()<|fim▁end|>
from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops
<|file_name|>block_contact.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
../../../../../../../../share/pyshared/papyon/service/AddressBook/scenario/contacts/block_contact.py
<|file_name|>ImportVmModel.java<|end_file_name|><|fim▁begin|>package org.ovirt.engine.ui.uicommonweb.models.vms; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.StorageType; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.storage_domain_static; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.compat.Event; import org.ovirt.engine.core.compat.EventArgs; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.IEventListener; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.compat.ObservableCollection; import org.ovirt.engine.core.compat.PropertyChangedEventArgs; import org.ovirt.engine.core.compat.StringFormat; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.ListModel; import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel; import org.ovirt.engine.ui.uicommonweb.validation.IValidation; import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation; @SuppressWarnings("unused") public class ImportVmModel extends ListWithDetailsModel { boolean sameSelectedDestinationStorage = false; ArrayList<storage_domains> uniqueDestStorages; ArrayList<storage_domains> allDestStorages; storage_domains selectedDestinationStorage; HashMap<Guid, ArrayList<Guid>> templateGuidUniqueStorageDomainDic; HashMap<Guid, ArrayList<Guid>> templateGuidAllStorageDomainDic; HashMap<Guid, ArrayList<DiskImage>> templateGuidDiskImagesDic; VmImportDiskListModel importDiskListModel; ArrayList<storage_domains> allStorageDomains; int uniqueDomains; Guid templateGuid; private storage_domain_static privateSourceStorage; public storage_domain_static getSourceStorage() { return privateSourceStorage; } public void setSourceStorage(storage_domain_static value) { privateSourceStorage = value; } private storage_pool privateStoragePool; public storage_pool getStoragePool() { return privateStoragePool; } public void setStoragePool(storage_pool value) { privateStoragePool = value; } private ListModel privateDestinationStorage; public ListModel getDestinationStorage() { return privateDestinationStorage; } private void setDestinationStorage(ListModel value) { privateDestinationStorage = value; } private ListModel privateAllDestinationStorage; public ListModel getAllDestinationStorage() { return privateAllDestinationStorage; } private void setAllDestinationStorage(ListModel value) { privateAllDestinationStorage = value; } private ListModel privateCluster; public ListModel getCluster() { return privateCluster; } private void setCluster(ListModel value) { privateCluster = value; } private ListModel privateSystemDiskFormat; public ListModel getSystemDiskFormat() { return privateSystemDiskFormat; } private void setSystemDiskFormat(ListModel value) { privateSystemDiskFormat = value; } private ListModel privateDataDiskFormat; public ListModel getDataDiskFormat() { return privateDataDiskFormat; } private void setDataDiskFormat(ListModel value) { privateDataDiskFormat = value; } private EntityModel collapseSnapshots; public EntityModel getCollapseSnapshots() { return collapseSnapshots; } public void setCollapseSnapshots(EntityModel value) { this.collapseSnapshots = value; } private boolean isMissingStorages; public boolean getIsMissingStorages() { return isMissingStorages; } public void setIsMissingStorages(boolean value) { if (isMissingStorages != value) { isMissingStorages = value; OnPropertyChanged(new PropertyChangedEventArgs("IsMissingStorages")); } } private String nameAndDescription; private AsyncQuery onCollapseSnapshotsChangedFinish; public String getNameAndDescription() { return nameAndDescription; } public void setNameAndDescription(String value) { if (!StringHelper.stringsEqual(nameAndDescription, value)) { nameAndDescription = value; OnPropertyChanged(new PropertyChangedEventArgs("NameAndDescription")); } } private java.util.List<VM> problematicItems; public java.util.List<VM> getProblematicItems() { return problematicItems; } public void setProblematicItems(java.util.List<VM> value) { if (problematicItems != value) { problematicItems = value; OnPropertyChanged(new PropertyChangedEventArgs("ProblematicItems")); } } private EntityModel privateIsSingleDestStorage; public EntityModel getIsSingleDestStorage() { return privateIsSingleDestStorage; } public void setIsSingleDestStorage(EntityModel value) { privateIsSingleDestStorage = value; } private ListModel privateStorageDoamins; public ListModel getStorageDoamins() { return privateStorageDoamins; } private void setStorageDoamins(ListModel value) { privateStorageDoamins = value; } private HashMap<Guid, HashMap<Guid, Guid>> privateDiskStorageMap; public HashMap<Guid, HashMap<Guid, Guid>> getDiskStorageMap() { return privateDiskStorageMap; } public void setDiskStorageMap(HashMap<Guid, HashMap<Guid, Guid>> value) { privateDiskStorageMap = value; } @Override public void setSelectedItem(Object value) { super.setSelectedItem(value); OnEntityChanged(); } public ImportVmModel() { setProblematicItems(new ArrayList<VM>()); setCollapseSnapshots(new EntityModel()); getCollapseSnapshots().setEntity(false); getCollapseSnapshots().getPropertyChangedEvent().addListener( new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { OnCollapseSnapshotsChanged(); } }); setDestinationStorage(new ListModel()); getDestinationStorage().getSelectedItemChangedEvent().addListener( new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { DestinationStorage_SelectedItemChanged(); } }); setCluster(new ListModel()); setSystemDiskFormat(new ListModel()); setDataDiskFormat(new ListModel()); setDiskStorageMap(new HashMap<Guid, HashMap<Guid, Guid>>()); setIsSingleDestStorage(new EntityModel()); getIsSingleDestStorage().setEntity(true); setAllDestinationStorage(new ListModel()); } public void OnCollapseSnapshotsChanged(AsyncQuery _asyncQuery) { this.onCollapseSnapshotsChangedFinish = _asyncQuery; OnCollapseSnapshotsChanged(); } public void initStorageDomains() { templateGuidUniqueStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>(); templateGuidAllStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>(); templateGuidDiskImagesDic = new java.util.HashMap<Guid, ArrayList<DiskImage>>(); uniqueDomains = 0; for (Object item : getItems()) { VM vm = (VM) item; templateGuid = vm.getvmt_guid(); if (templateGuid.equals(NGuid.Empty)) { uniqueDomains++; templateGuidUniqueStorageDomainDic.put(templateGuid, null); templateGuidAllStorageDomainDic.put(templateGuid, null); } else {<|fim▁hole|> ImportVmModel importVmModel = (ImportVmModel) target; ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue; ArrayList<ArrayList<Guid>> allSourceStorages = new ArrayList<ArrayList<Guid>>(); for (DiskImage disk : disks) { allSourceStorages.add(disk.getstorage_ids()); } ArrayList<Guid> intersectStorageDomains = Linq.Intersection(allSourceStorages); ArrayList<Guid> unionStorageDomains = Linq.Union(allSourceStorages); uniqueDomains++; templateGuidUniqueStorageDomainDic.put(importVmModel.templateGuid, intersectStorageDomains); templateGuidAllStorageDomainDic.put(importVmModel.templateGuid, unionStorageDomains); templateGuidDiskImagesDic.put(importVmModel.templateGuid, disks); importVmModel.postInitStorageDomains(); } }), templateGuid); } } postInitStorageDomains(); } protected void postInitStorageDomains() { if (templateGuidUniqueStorageDomainDic.size() != uniqueDomains) { return; } AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.Model = this; _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { allStorageDomains = (ArrayList<storage_domains>) returnValue; OnCollapseSnapshotsChanged(); initDiskStorageMap(); } }; AsyncDataProvider.GetDataDomainsListByDomain(_asyncQuery, this.getSourceStorage().getId()); } private void initDiskStorageMap() { for (Object item : getItems()) { VM vm = (VM) item; for (DiskImage disk : vm.getDiskMap().values()) { if (NGuid.Empty.equals(vm.getvmt_guid())) { Guid storageId = !allDestStorages.isEmpty() ? allDestStorages.get(0).getId() : new Guid(); addToDiskStorageMap(vm.getId(), disk, storageId); } else { ArrayList<Guid> storageIds = templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()); Guid storageId = storageIds != null ? templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()).get(0) : new Guid(); addToDiskStorageMap(vm.getId(), disk, storageId); } } } } public void OnCollapseSnapshotsChanged() { if (this.getItems() == null || allStorageDomains == null) { return; } selectedDestinationStorage = null; sameSelectedDestinationStorage = false; uniqueDestStorages = new ArrayList<storage_domains>(); allDestStorages = new ArrayList<storage_domains>(); setIsMissingStorages(false); if (getDestinationStorage().getSelectedItem() != null) { selectedDestinationStorage = (storage_domains) getDestinationStorage().getSelectedItem(); } for (storage_domains domain : allStorageDomains) { boolean addStorage = false; if (Linq.IsDataActiveStorageDomain(domain)) { allDestStorages.add(domain); if (((Boolean) getCollapseSnapshots().getEntity()).equals(true)) { addStorage = true; } else { for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidUniqueStorageDomainDic.entrySet()) { if (NGuid.Empty.equals(keyValuePair.getKey())) { addStorage = true; } else { addStorage = false; for (Guid storageDomainId : keyValuePair.getValue()) { if (storageDomainId.equals(domain.getId())) { addStorage = true; break; } } } if (addStorage == false) { break; } } } } else { for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidAllStorageDomainDic.entrySet()) { if (!NGuid.Empty.equals(keyValuePair.getKey())) { for (Guid storageDomainId : keyValuePair.getValue()) { if (storageDomainId.equals(domain.getId())) { setIsMissingStorages(true); break; } } } } } if (addStorage) { uniqueDestStorages.add(domain); if (sameSelectedDestinationStorage == false && domain.equals(selectedDestinationStorage)) { sameSelectedDestinationStorage = true; selectedDestinationStorage = domain; } } } getAllDestinationStorage().setItems(allDestStorages); getDestinationStorage().setItems(uniqueDestStorages); if (sameSelectedDestinationStorage) { getDestinationStorage().setSelectedItem(selectedDestinationStorage); } else { getDestinationStorage().setSelectedItem(Linq.FirstOrDefault(uniqueDestStorages)); } if (getDetailModels() != null && getActiveDetailModel() instanceof VmImportDiskListModel) { VmImportDiskListModel detailModel = (VmImportDiskListModel) getActiveDetailModel(); detailModel .setCollapseSnapshots((Boolean) getCollapseSnapshots() .getEntity()); } if (onCollapseSnapshotsChangedFinish != null) { onCollapseSnapshotsChangedFinish.asyncCallback.OnSuccess( onCollapseSnapshotsChangedFinish.getModel(), null); onCollapseSnapshotsChangedFinish = null; } } @Override protected void ActiveDetailModelChanged() { super.ActiveDetailModelChanged(); OnCollapseSnapshotsChanged(); } @Override protected void InitDetailModels() { super.InitDetailModels(); importDiskListModel = new VmImportDiskListModel(); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new VmGeneralModel()); list.add(new VmImportInterfaceListModel()); list.add(importDiskListModel); list.add(new VmAppListModel()); setDetailModels(list); } public boolean Validate() { getDestinationStorage().ValidateSelectedItem( new IValidation[] { new NotEmptyValidation() }); getCluster().ValidateSelectedItem( new IValidation[] { new NotEmptyValidation() }); return getDestinationStorage().getIsValid() && getCluster().getIsValid(); } @Override protected void OnSelectedItemChanged() { super.OnSelectedItemChanged(); if (getSelectedItem() != null) { VM vm = (VM) getSelectedItem(); setNameAndDescription(StringFormat.format("%1$s%2$s", vm.getvm_name(), !StringHelper.isNullOrEmpty(vm.getvm_description()) ? " [" + vm.getvm_description() + "]" : "")); } else { setNameAndDescription(""); } } public void setItems(Iterable value) { super.setItems(value); for (Object vm : getItems()) { getDiskStorageMap().put(((VM) vm).getId(), new HashMap<Guid, Guid>()); } initStorageDomains(); } @Override protected String getListName() { return "ImportVmModel"; } public void setSelectedVMsCount(int size) { importDiskListModel.setSelectedVMsCount(((List) getItems()).size()); } storage_domains currStorageDomain = null; private void DestinationStorage_SelectedItemChanged() { storage_domains selectedStorageDomain = (storage_domains) getDestinationStorage().getSelectedItem(); List destinationStorageDomains = ((List) getDestinationStorage().getItems()); if (selectedStorageDomain == null && !destinationStorageDomains.isEmpty()) { selectedStorageDomain = (storage_domains) destinationStorageDomains.get(0); } if (currStorageDomain == null || selectedStorageDomain == null || !currStorageDomain.getQueryableId().equals(selectedStorageDomain.getQueryableId())) { currStorageDomain = selectedStorageDomain; UpdateImportWarnings(); } } public void DestinationStorage_SelectedItemChanged(DiskImage disk, String storageDomainName) { VM item = (VM) getSelectedItem(); addToDiskStorageMap(item.getId(), disk, getStorageDomainByName(storageDomainName).getId()); } public void addToDiskStorageMap(Guid vmId, DiskImage disk, Guid storageId) { HashMap<Guid, Guid> vmDiskStorageMap = getDiskStorageMap().get(vmId); vmDiskStorageMap.put(disk.getId(), storageId); } private storage_domains getStorageDomainByName(String storageDomainName) { storage_domains storage = null; for (Object storageDomain : getDestinationStorage().getItems()) { storage = (storage_domains) storageDomain; if (storageDomainName.equals(storage.getstorage_name())) { break; } } return storage; } @Override protected void ItemsChanged() { super.ItemsChanged(); UpdateImportWarnings(); } public VmImportDiskListModel getImportDiskListModel() { return importDiskListModel; } private void UpdateImportWarnings() { // Clear problematic state. getProblematicItems().clear(); if (getItems() == null) { return; } storage_domains destinationStorage = (storage_domains) getDestinationStorage() .getSelectedItem(); for (Object item : getItems()) { VM vm = (VM) item; if (vm.getDiskMap() != null) { for (java.util.Map.Entry<String, DiskImage> pair : vm .getDiskMap().entrySet()) { DiskImage disk = pair.getValue(); if (disk.getvolume_type() == VolumeType.Sparse && disk.getvolume_format() == VolumeFormat.RAW && destinationStorage != null && (destinationStorage.getstorage_type() == StorageType.ISCSI || destinationStorage .getstorage_type() == StorageType.FCP)) { getProblematicItems().add(vm); } } } } // Decide what to do with the CollapseSnapshots option. if (problematicItems.size() > 0) { if (problematicItems.size() == Linq.Count(getItems())) { // All items are problematic. getCollapseSnapshots().setIsChangable(false); getCollapseSnapshots().setEntity(true); getCollapseSnapshots() .setMessage( "Note that all snapshots will be collapsed due to different storage types"); } else { // Some items are problematic. getCollapseSnapshots() .setMessage( "Use a separate import operation for the marked VMs or\nApply \"Collapse Snapshots\" for all VMs"); } } else { // No problematic items. getCollapseSnapshots().setIsChangable(true); getCollapseSnapshots().setMessage(null); } } public void VolumeType_SelectedItemChanged(DiskImage disk, VolumeType tempVolumeType) { for (Object item : getItems()) { VM vm = (VM) item; java.util.HashMap<String, DiskImageBase> diskDictionary = new java.util.HashMap<String, DiskImageBase>(); for (java.util.Map.Entry<String, DiskImage> a : vm.getDiskMap() .entrySet()) { if (a.getValue().getQueryableId().equals(disk.getQueryableId())) { a.getValue().setvolume_type(tempVolumeType); break; } } } } public ArrayList<String> getAvailableStorageDomainsByDiskId(Guid diskId) { ArrayList<String> storageDomains = null; ArrayList<Guid> storageDomainsIds = getImportDiskListModel().getAvailableStorageDomainsByDiskId(diskId); if (storageDomainsIds != null) { storageDomains = new ArrayList<String>(); for (Guid storageId : storageDomainsIds) { if (Linq.IsActiveStorageDomain(getStorageById(storageId))) { storageDomains.add(getStorageNameById(storageId)); } } } if (storageDomains != null) { Collections.sort(storageDomains); } return storageDomains; } public String getStorageNameById(NGuid storageId) { String storageName = ""; for (Object storageDomain : getAllDestinationStorage().getItems()) { storage_domains storage = (storage_domains) storageDomain; if (storage.getId().equals(storageId)) { storageName = storage.getstorage_name(); } } return storageName; } public storage_domains getStorageById(Guid storageId) { for (storage_domains storage : allDestStorages) { if (storage.getId().equals(storageId)) { return storage; } } return null; } }<|fim▁end|>
AsyncDataProvider.GetTemplateDiskList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) {
<|file_name|>InteractionBuilder.py<|end_file_name|><|fim▁begin|>import sys, string import os.path import unique import export import gene_associations import traceback import time ################# Parse directory files def filepath(filename): fn = unique.filepath(filename) return fn def read_directory(sub_dir): dir_list = unique.read_directory(sub_dir) #add in code to prevent folder names from being included dir_list2 = [] for file in dir_list: lf = string.lower(file) if '.txt' in lf or '.sif' in lf or '.tab' in lf: dir_list2.append(file) return dir_list2 ################# Begin Analysis from parsing files def getEnsemblGeneData(filename): fn=filepath(filename) global ensembl_symbol_db; ensembl_symbol_db={}; global symbol_ensembl_db; symbol_ensembl_db={} for line in open(fn,'rU').xreadlines(): data,null = string.split(line,'\n') t = string.split(data,'\t') ensembl=t[0];symbol=t[1] ### Have to do this in order to get the WEIRD chromosomal assocaitions and the normal to the same genes try: symbol_ensembl_db[symbol].append(ensembl) except Exception: symbol_ensembl_db[symbol] = [ensembl] try: symbol_ensembl_db[string.lower(symbol)].append(ensembl) except Exception: symbol_ensembl_db[string.lower(symbol)] = [ensembl] try: symbol_ensembl_db[symbol.title()].append(ensembl) except Exception: symbol_ensembl_db[symbol.title()] = [ensembl] ensembl_symbol_db[ensembl] = symbol def getHMDBData(species): program_type,database_dir = unique.whatProgramIsThis() filename = database_dir+'/'+species+'/gene/HMDB.txt' x=0 fn=filepath(filename) for line in open(fn,'rU').xreadlines(): data = cleanUpLine(line) if x==0: x=1 else: t = string.split(data,'\t') try: hmdb_id,symbol,description,secondary_id,iupac,cas_number,chebi_id,pubchem_compound_id,Pathways,ProteinNames = t except Exception: ### Bad Tab introduced from HMDB hmdb_id = t[0]; symbol = t[1]; ProteinNames = t[-1] symbol_hmdb_db[symbol]=hmdb_id hmdb_symbol_db[hmdb_id] = symbol ProteinNames=string.split(ProteinNames,',') ### Add gene-metabolite interactions to databases for protein_name in ProteinNames: try: for ensembl in symbol_ensembl_db[protein_name]: z = InteractionInformation(hmdb_id,ensembl,'HMDB','Metabolic') interaction_annotation_dbase[ensembl,hmdb_id] = z ### This is the interaction direction that is appropriate try: interaction_db[hmdb_id][ensembl]=1 except KeyError: db = {ensembl:1}; interaction_db[hmdb_id] = db ###weight of 1 (weights currently not-supported) try: interaction_db[ensembl][hmdb_id]=1 except KeyError: db = {hmdb_id:1}; interaction_db[ensembl] = db ###weight of 1 (weights currently not-supported) except Exception: None def verifyFile(filename): status = 'not found' try: fn=filepath(filename) for line in open(fn,'rU').xreadlines(): status = 'found';break except Exception: status = 'not found' return status def importInteractionDatabases(interactionDirs): """ Import multiple interaction format file types (designated by the user) """ exclude=[] for file in interactionDirs: status = verifyFile(file) if status == 'not found': exclude.append(file) for i in exclude: interactionDirs.remove(i) for fn in interactionDirs: #loop through each file in the directory to output results x=0; imported=0; stored=0 file = export.findFilename(fn) print "Parsing interactions from:",file for line in open(fn,'rU').xreadlines(): data,null = string.split(line,'\n') t = string.split(data,'\t') if x==0: x=1 #elif 'PAZAR' in data or 'Amadeus' in data:x+=0 else: obligatory = False imported+=1 proceed = True source='' interaction_type = 'interaction' try: symbol1,interaction_type, symbol2, ensembl1,ensembl2,source = t ens_ls1=[ensembl1]; ens_ls2=[ensembl2] if 'HMDB' in ensembl1: ensembl1 = string.replace(ensembl1,' ','') ### HMDB ID sometimes proceeded by ' ' symbol_hmdb_db[symbol1]=ensembl1 hmdb_symbol_db[ensembl1] = symbol1 interaction_type = 'Metabolic' if 'HMDB' in ensembl2: ensembl2 = string.replace(ensembl2,' ','') ### HMDB ID sometimes proceeded by ' ' symbol_hmdb_db[symbol2]=ensembl2 hmdb_symbol_db[ensembl2] = symbol2 interaction_type = 'Metabolic' except Exception: try: ensembl1,ensembl2,symbol1,symbol2,interaction_type=t if ensembl1 == '': try: ens_ls1 = symbol_ensembl_db[symbol1] ens_ls2 = symbol_ensembl_db[symbol2] except Exception: None except Exception: proceed = False if proceed: ### If the interaction data conformed to one of the two above types (typically two valid interacting gene IDs) if (len(ens_ls1)>0 and len(ens_ls2)>0): secondary_proceed = True stored+=1 for ensembl1 in ens_ls1: for ensembl2 in ens_ls2: """ if (ensembl1,ensembl2) == ('ENSG00000111704','ENSG00000152284'): print t;sys.exit() if (ensembl1,ensembl2) == ('ENSG00000152284','ENSG00000111704'): print t;sys.exit() """ if 'WikiPathways' in file or 'KEGG' in file: if ensembl2 != ensembl1: if (ensembl2,ensembl1) in interaction_annotation_dbase: del interaction_annotation_dbase[(ensembl2,ensembl1)] ### Exclude redundant entries with fewer interaction details (e.g., arrow direction BIOGRID) - overwrite with the opposite gene arrangement below if (ensembl1,ensembl2) in interaction_annotation_dbase: if interaction_annotation_dbase[(ensembl1,ensembl2)].InteractionType() !='physical': secondary_proceed = False ### Don't overwrite a more informative annotation like transcriptional regulation or microRNA targeting if 'DrugBank' in fn: source = 'DrugBank' interaction_type = 'drugInteraction' obligatory=True ensembl1, ensembl2 = ensembl2, ensembl1 ### switch the order of these (drugs reported as first ID and gene as the second) if secondary_proceed: z = InteractionInformation(ensembl1,ensembl2,source,interaction_type) interaction_annotation_dbase[ensembl1,ensembl2] = z #z = InteractionInformation(ensembl2,ensembl1,source,interaction_type) #interaction_annotation_dbase[ensembl2,ensembl1] = z try: interaction_db[ensembl1][ensembl2]=1 except KeyError: db = {ensembl2:1}; interaction_db[ensembl1] = db ###weight of 1 (weights currently not-supported) try: interaction_db[ensembl2][ensembl1]=1 except KeyError: db = {ensembl1:1}; interaction_db[ensembl2] = db ###weight of 1 (weights currently not-supported) if obligatory and source in obligatoryList: ### Include these in the final pathway if linked to any input node (e.g., miRNAs, drugs) try: obligatory_interactions[ensembl1][ensembl2]=1 except KeyError: db = {ensembl2:1}; obligatory_interactions[ensembl1] = db ###weight of 1 (weights currentlynot-supported) elif source in secondDegreeObligatoryCategories: try: second_degree_obligatory[ensembl1][ensembl2]=1 except KeyError: db = {ensembl2:1}; second_degree_obligatory[ensembl1] = db ###weight of 1 (weights currently not-supported) else: proceed = False try: ID1, null, ID2 = t proceed = True except Exception: try: ID1, ID2 = t proceed = True except Exception: None if proceed: if 'microRNATargets' in fn: if 'mir' in ID2: prefix = 'MIR' else: prefix = 'LET' ID2='MIR'+string.split(ID2,'-')[2] ### Ensembl naming convention source = 'microRNATargets' interaction_type = 'microRNAInteraction' obligatory=True try: ID_ls1 = symbol_ensembl_db[ID1] except Exception: ID_ls1 = [ID1] try: ID_ls2 = symbol_ensembl_db[ID2] except Exception: ID_ls2 = [ID2] """if 'microRNATargets' in fn: if '*' not in ID2: print ID_ls2;sys.exit()""" addInteractions = True for ID1 in ID_ls1: for ID2 in ID_ls2: z = InteractionInformation(ID2,ID1,source,interaction_type) interaction_annotation_dbase[ID2,ID1] = z ### This is the interaction direction that is appropriate try: interaction_db[ID1][ID2]=1 except KeyError: db = {ID2:1}; interaction_db[ID1] = db ###weight of 1 (weights currently supported) try: interaction_db[ID2][ID1]=1 except KeyError: db = {ID1:1}; interaction_db[ID2] = db ###weight of 1 (weights currently supported) if source in secondDegreeObligatoryCategories: try: second_degree_obligatory[ID1][ID2]=1 except KeyError: db = {ID2:1}; second_degree_obligatory[ID1] = db ###weight of 1 (weights currently supported) elif obligatory and source in obligatoryList: ### Include these in the final pathway if linked to any input node (e.g., miRNAs, drugs) try: obligatory_interactions[ID1][ID2]=1 except KeyError: db = {ID2:1}; obligatory_interactions[ID1] = db ###weight of 1 (weights currently supported) ### Evaluate the most promiscous interactors (e.g., UBC) remove_list=[] for ID in interaction_db: if len(interaction_db[ID])>2000: remove_list.append(ID) #print len(interaction_db[ID]),ensembl_symbol_db[ID] for ID in remove_list: #print 'removing', ID del interaction_db[ID] blackList[ID] = [] print 'Imported interactions:',len(interaction_annotation_dbase) class InteractionInformation: def __init__(self, ensembl1, ensembl2, source, interaction_type): self._ensembl1 = ensembl1; self._ensembl2 = ensembl2; self._source = source self._interaction_type = interaction_type def Ensembl1(self): return self._ensembl1 def Ensembl2(self): return self._ensembl2 def Source(self): return self._source def InteractionType(self): return self._interaction_type def Report(self): output = self.Ensembl1()+'|'+self.Ensembl2() return output def __repr__(self): return self.Report() def cleanUpLine(line): line = string.replace(line,'\n','') line = string.replace(line,'\c','') data = string.replace(line,'\r','') data = string.replace(data,'"','') return data<|fim▁hole|>def importqueryResults(species,dir_file,id_db): global query_db; query_db = {} query_interactions={} ### This is the final list of shown interactions if dir_file == None: fileRead = dir_file elif '.' in dir_file: fn=filepath(dir_file) fileRead = open(fn,'rU').xreadlines() else: fileRead = dir_file ### This is a list of IDs passed to this function rather than in a file if len(id_db)==0: ### Otherwise, already provided gene IDs to query translated=0 try: x=0 for line in fileRead: try: data = cleanUpLine(line) t = string.split(data,'\t') except Exception: t = line if x==1: x = 1 ### no longer statement since the first row may be a valid ID(s) else: id = t[0] ensembl_ls1=[] if id in ensembl_symbol_db: symbol = ensembl_symbol_db[id] query_db[id] = symbol ensembl_ls1 = [id] translated+=1 elif id in symbol_ensembl_db: ensembl_ls1 = symbol_ensembl_db[id] translated+=1 for ensembl in ensembl_ls1: query_db[ensembl] = id elif id in symbol_hmdb_db: hmdb = symbol_hmdb_db[id] query_db[hmdb] = id elif id in hmdb_symbol_db: symbol = hmdb_symbol_db[id] query_db[id] = symbol else: query_db[id] = id ### Currently not dealt with ensembl_ls1 = [id] ### If a SIF file add genes and interactions if len(t)>1 and 'SIF' in inputDataType: ### Potentially SIF format interaction_type = t[1] try: id2 = t[2] except Exception: id2 = t[1]; interaction_type = 'undetermined' ensembl_ls2=[] if id2 in ensembl_symbol_db: symbol = ensembl_symbol_db[id2] query_db[id2] = symbol ensembl_ls2 = [id2] elif id2 in symbol_ensembl_db: ensembl_ls2 = symbol_ensembl_db[id2] for ensembl in ensembl_ls2: query_db[ensembl] = id2 elif id2 in symbol_hmdb_db: hmdb = symbol_hmdb_db[id2] query_db[hmdb] = id2 elif id2 in hmdb_symbol_db: symbol = hmdb_symbol_db[id2] query_db[id2] = symbol else: query_db[id2] = id2 for ensembl1 in ensembl_ls1: for ensembl2 in ensembl_ls2: try: query_interactions[ensembl1].append(ensembl2) except Exception: query_interactions[ensembl1] = [ensembl2] z = InteractionInformation(ensembl1,ensembl2,'custom',interaction_type) interaction_annotation_dbase[ensembl1,ensembl2] = z except Exception: print traceback.format_exc() print 'No valid directories or IDs provided. Exiting.'; kill if translated==0: import WikiPathways_webservice try: query_db = WikiPathways_webservice.importDataSimple(dir_file,None,MOD='Ensembl',Species=species)[0] except Exception: ### If metabolomics query_db = WikiPathways_webservice.importDataSimple(dir_file,None,MOD='HMDB',Species=species)[0] ### Translate the Ensembl IDs to symbols (where possible) for id in query_db: if id in ensembl_symbol_db: symbol = ensembl_symbol_db[id] else: symbol=id query_db[id] = symbol else: for id in id_db: if id_db[id]==None: try: id_db[id] = ensembl_symbol_db[id] ### Save symbol (done for imported pathway genes) except Exception: id_db[id]=id query_db = id_db ### Input gene IDs (not in a file) print 'Number of IDs from', dir_file, 'is', len(query_db) return query_db,query_interactions,dir_file def associateQueryGenesWithInteractions(query_db,query_interactions,dir_file): suffix='' if dir_file!=None: if len(dir_file)!=0: suffix='-'+intNameShort+'_'+export.findFilename(dir_file)[:-4] if len(suffix)==0: try: suffix = '_'+FileName except Exception: None file_name = 'AltAnalyze-network'+suffix query_interactions_unique={} interacting_genes={} connections = 1 primary=0 secondary=0 terciary=0 for ensemblGene in query_db: if ensemblGene in interaction_db: for interacting_ensembl in interaction_db[ensemblGene]: if interacting_ensembl not in blackList: ###Only allow direct interactions found in query if interacting_ensembl in query_db: try: query_interactions[ensemblGene].append(interacting_ensembl) except KeyError: query_interactions[ensemblGene] = [interacting_ensembl] try: query_interactions[interacting_ensembl].append(ensemblGene) except KeyError: query_interactions[interacting_ensembl] = [ensemblGene] primary+=1 if degrees == 2 or degrees == 'indirect': try: interacting_genes[interacting_ensembl].append(ensemblGene) except KeyError: interacting_genes[interacting_ensembl] = [ensemblGene] elif degrees == 'allInteracting' or degrees == 'all possible': try: query_interactions[ensemblGene].append(interacting_ensembl) except KeyError: query_interactions[ensemblGene] = [interacting_ensembl] if interacting_ensembl in secondaryQueryIDs: ### IDs in the expression file secondary+=1 ### When indirect degrees selected, no additional power added by this (only for direct or shortest path) try: query_interactions[ensemblGene].append(interacting_ensembl) except KeyError: query_interactions[ensemblGene] = [interacting_ensembl] if ensemblGene in second_degree_obligatory: for interacting_ensembl in second_degree_obligatory[ensemblGene]: try: interacting_genes[interacting_ensembl].append(ensemblGene) except KeyError: interacting_genes[interacting_ensembl] = [ensemblGene] ### Include indirect interactions to secondaryQueryIDs from the expression file if degrees == 2 or degrees == 'indirect': for ensemblGene in secondaryQueryIDs: if ensemblGene in interaction_db: for interacting_ensembl in interaction_db[ensemblGene]: if interacting_ensembl not in blackList: try: interacting_genes[interacting_ensembl].append(ensemblGene) terciary+=1#; print interacting_ensembl except KeyError: None ### Only increase the interacting_genes count if the interacting partner is present from the primary query list #print primary,secondary,terciary ### Report the number of unique interacting genes for interacting_ensembl in interacting_genes: if len(interacting_genes[interacting_ensembl])==1: interacting_genes[interacting_ensembl] = 1 else: unique_interactions = unique.unique(interacting_genes[interacting_ensembl]) interacting_genes[interacting_ensembl] = len(unique_interactions) query_indirect_interactions={}; indirect_interacting_gene_list=[]; interacting_gene_list=[]; added=[] if degrees=='shortestPath' or degrees=='shortest path': ### Typically identifying the single smallest path(s) between two nodes. query_indirect_interactions, indirect_interacting_gene_list, interacting_gene_list = evaluateShortestPath(query_db,interaction_db,10) else: if degrees==2 or degrees=='indirect' or len(secondDegreeObligatoryCategories)>0: for ensembl in interacting_genes: if interacting_genes[ensembl] > connections: if ensembl in interaction_db: ### Only nodes removed due to promiscuity will not be found for interacting_ensembl in interaction_db[ensembl]: if interacting_ensembl in query_db or interacting_ensembl in secondaryQueryIDs: try: query_indirect_interactions[interacting_ensembl].append(ensembl) except KeyError: query_indirect_interactions[interacting_ensembl] = [ensembl] ###Record the highest linked nodes indirect_interacting_gene_list.append((interacting_genes[ensembl],ensembl)) if len(obligatory_interactions)>0: ### Include always all_reported_genes = combineDBs(query_interactions,query_indirect_interactions) ### combinesDBs and returns a unique list of genes for ensemblGene in all_reported_genes: ###This only includes genes in the original input list if ensemblGene in obligatory_interactions: for interacting_ensembl in obligatory_interactions[ensemblGene]: #symbol = ensembl_symbol_db[ensemblGene] try: query_interactions[ensemblGene].append(interacting_ensembl) except KeyError: query_interactions[ensemblGene] = [interacting_ensembl] z = dict(query_interactions.items() + query_indirect_interactions.items()) interaction_restricted_db={} for ensembl in z: interacting_nodes = z[ensembl] for node in interacting_nodes: if ensembl in interaction_restricted_db: db = interaction_restricted_db[ensembl] db[node] = 1 else: interaction_restricted_db[ensembl] = {node:1} if node in interaction_restricted_db: db = interaction_restricted_db[node] db[ensembl] = 1 else: interaction_restricted_db[node] = {ensembl:1} if degrees==2 or degrees=='indirect': ### get rid of non-specific interactions query_indirect_interactions, indirect_interacting_gene_list, interacting_gene_list = evaluateShortestPath(query_db,interaction_restricted_db,4) ###Record the highest linked nodes for ensembl in query_interactions: linked_nodes = len(unique.unique(query_interactions[ensembl])) interacting_gene_list.append((linked_nodes,ensembl)) interacting_gene_list.sort(); interacting_gene_list.reverse() indirect_interacting_gene_list.sort(); indirect_interacting_gene_list.reverse() print "Length of query_interactions:",len(query_interactions) query_interactions_unique=[] for gene1 in query_interactions: for gene2 in query_interactions[gene1]: temp = []; temp.append(gene2); temp.append(gene1)#; temp.sort() if gene1 == gene2: interaction_type = 'self' else: interaction_type = 'distinct' temp.append(interaction_type); temp.reverse() query_interactions_unique.append(temp) for gene1 in query_indirect_interactions: for gene2 in query_indirect_interactions[gene1]: temp = []; temp.append(gene2); temp.append(gene1)#; temp.sort() if gene1 == gene2: interaction_type = 'self' else: interaction_type = 'indirect' temp.append(interaction_type); temp.reverse() query_interactions_unique.append(temp) query_interactions_unique = unique.unique(query_interactions_unique) query_interactions_unique.sort() ###Write out nodes linked to many other nodes new_file = outputDir+'/networks/'+file_name+ '-interactions_'+str(degrees)+'_degrees_summary.txt' data = export.ExportFile(new_file) for (linked_nodes,ensembl) in interacting_gene_list: try: symbol = query_db[ensembl] except KeyError: symbol = ensembl_symbol_db[ensembl] data.write(str(linked_nodes)+'\t'+ensembl+'\t'+symbol+'\t'+'direct'+'\n') for (linked_nodes,ensembl) in indirect_interacting_gene_list: try: symbol = query_db[ensembl] except KeyError: try: symbol = ensembl_symbol_db[ensembl] except KeyError: symbol = ensembl if 'HMDB' in symbol: try: symbol = hmdb_symbol_db[ensembl] except Exception: pass data.write(str(linked_nodes)+'\t'+ensembl+'\t'+symbol+'\t'+'indirect'+'\n') data.close() regulated_gene_db = query_db sif_export,symbol_pair_unique = exportInteractionData(file_name,query_interactions_unique,regulated_gene_db) return sif_export,symbol_pair_unique def combineDBs(db1,db2): ### combinesDBs and returns a unique list of genes new_db={} for i in db1: new_db[i]=[] for k in db1[i]: new_db[k]=[] for i in db2: new_db[i]=[] for k in db2[i]: new_db[k]=[] return new_db def evaluateShortestPath(query_db,interaction_restricted_db,depth): interactions_found=0 start_time = time.time() query_indirect_interactions={}; indirect_interacting_gene_list=[]; interacting_gene_list=[]; added=[] print 'Performing shortest path analysis on %s IDs...' % len(query_db), for gene1 in query_db: for gene2 in query_db: if (gene1,gene2) not in added and (gene2,gene1) not in added: if gene1 != gene2 and gene1 in interaction_restricted_db and gene2 in interaction_restricted_db: try: path = shortest_path(interaction_restricted_db,gene1,gene2,depth) added.append((gene1,gene2)) i=1 while i<len(path): ### Add the relationship pairs try: query_indirect_interactions[path[i-1]].append(path[i]) except Exception: query_indirect_interactions[path[i-1]]=[path[i]] interactions_found+=1 i+=1 except Exception: #tb = traceback.format_exc() pass if len(query_indirect_interactions)==0: print 'None of the query genes interacting in the selected interaction databases...'; queryGeneError print interactions_found, 'interactions found in', time.time()-start_time, 'seconds' return query_indirect_interactions, indirect_interacting_gene_list, interacting_gene_list def shortest_path(G, start, end, depth): #http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/ import heapq def flatten(L): # Flatten linked list of form [0,[1,[2,[]]]] while len(L) > 0: yield L[0] L = L[1] q = [(0, start, ())] # Heap of (cost, path_head, path_rest). visited = set() # Visited vertices. while True: (cost, v1, path) = heapq.heappop(q) if v1 not in visited and v1 in G: visited.add(v1) if v1 == end: final_path = list(flatten(path))[::-1] + [v1] if len(final_path)<depth: return final_path else: return None path = (v1, path) for (v2, cost2) in G[v1].iteritems(): if v2 not in visited: heapq.heappush(q, (cost + cost2, v2, path)) def exportInteractionData(file_name,query_interactions_unique,regulated_gene_db): file_name = string.replace(file_name,':','-') new_file = outputDir+'/networks/'+file_name + '-interactions_'+str(degrees)+'.txt' sif_export = outputDir+'/networks/'+file_name + '-interactions_'+str(degrees)+'.sif' fn=filepath(new_file); fn2=filepath(sif_export) data = open(fn,'w'); data2 = open(fn2,'w') added = {} ### Don't add the same entry twice symbol_added={}; symbol_pair_unique={} for (interaction_type,gene1,gene2) in query_interactions_unique: try: symbol1 = query_db[gene1] except KeyError: try: symbol1 = ensembl_symbol_db[gene1] except KeyError: symbol1 = gene1 if 'HMDB' in symbol1: symbol1 = hmdb_symbol_db[gene1] try: symbol2 = query_db[gene2] except KeyError: try: symbol2 = ensembl_symbol_db[gene2] except KeyError: symbol2 = gene2 if 'HMDB' in symbol2: symbol2 = hmdb_symbol_db[gene2] gene_pair = ''; symbol_pair=''; direction = 'interactsWith' if (gene1,gene2) in interaction_annotation_dbase: gene_pair = gene1,gene2; symbol_pair = symbol1,symbol2 elif (gene2,gene1) in interaction_annotation_dbase: gene_pair = gene2,gene1; symbol_pair = symbol2,symbol1 else: print gene1, gene2, symbol1, symbol2; kill if len(gene_pair)>0: y = interaction_annotation_dbase[gene_pair] gene1,gene2 = gene_pair ### This is the proper order of the interaction symbol1,symbol2 = symbol_pair interaction_type = y.InteractionType() if interaction_type == 'drugInteraction': ### Switch their order gene1, gene2, symbol1, symbol2 = gene2, gene1, symbol2, symbol1 direction = interaction_type if (gene_pair,direction) not in added: added[(gene_pair,direction)]=[] data.write(gene1+'\t'+gene2+'\t'+symbol1+'\t'+symbol2+'\t'+interaction_type+'\n') if len(symbol1)>1 and len(symbol2)>1 and (symbol_pair,direction) not in symbol_added: if symbol1 != symbol2: data2.write(symbol1+'\t'+direction+'\t'+symbol2+'\n') symbol_added[(symbol_pair,direction)]=[] symbol_pair_unique[symbol_pair]=[] data.close(); data2.close() print "Interaction data exported" return sif_export,symbol_pair_unique def eliminate_redundant_dict_values(database): db1={} for key in database: list = unique.unique(database[key]) list.sort() db1[key] = list return db1 def importInteractionData(interactionDirs): global interaction_db; interaction_db = {} global interaction_annotation_dbase; interaction_annotation_dbase = {} global obligatory_interactions; obligatory_interactions={} global second_degree_obligatory; second_degree_obligatory={} global blackList; blackList = {} ###Collect both Human and Mouse interactions (Mouse directly sorted in interaction_db importInteractionDatabases(interactionDirs) def interactionPermuteTest(species,Degrees,inputType,inputDir,outputdir,interactionDirs,Genes=None, geneSetType=None,PathwayFilter=None,OntologyID=None,directory=None,expressionFile=None, obligatorySet=None,secondarySet=None,IncludeExpIDs=False): global degrees global outputDir global inputDataType global obligatoryList ### Add these if connected to anything global secondaryQueryIDs global secondDegreeObligatoryCategories ### Add if common to anything in the input - Indicates systems to apply this to global symbol_hmdb_db; symbol_hmdb_db={}; global hmdb_symbol_db; hmdb_symbol_db={} ### Create an annotation database for HMDB IDs global FileName secondaryQueryIDs = {} degrees = Degrees outputDir = outputdir inputDataType = inputType obligatoryList = obligatorySet secondDegreeObligatoryCategories=[] if obligatoryList == None: obligatoryList=[] if expressionFile == None: expressionFile = inputDir ### If it doesn't contain expression values, view as yellow nodes if secondarySet!= None and (degrees==1 or degrees=='direct'): ### If degrees == 2, this is redundant ### This currently adds alot of predictions - either make more stringent or currently exclude secondDegreeObligatoryCategories = secondarySet if PathwayFilter != None: FileName = PathwayFilter elif OntologyID != None: FileName = OntologyID elif Genes != None: FileName = Genes ### Import Ensembl-Symbol annotations getEnsemblGeneData('AltDatabase/ensembl/'+species+'/'+species+'_Ensembl-annotations.txt') ### Import interaction databases indicated in interactionDirs importInteractionData(interactionDirs) getHMDBData(species) ### overwrite the symbol annotation from any HMDB that comes from a WikiPathway or KEGG pathway that we also include (for consistent official annotation) input_IDs = getGeneIDs(Genes) try: input_IDs = gene_associations.simpleGenePathwayImport(species,geneSetType,PathwayFilter,OntologyID,directory) except Exception: None permutations = 10000; p = 0 secondaryQueryIDs = importqueryResults(species,expressionFile,{})[0] input_IDs,query_interactions,dir_file = importqueryResults(species,inputDir,input_IDs) ### Get the number of unique genes sif_file, original_symbol_pair_unique = associateQueryGenesWithInteractions(input_IDs,query_interactions,dir_file) #print len(original_symbol_pair_unique) ensembl_unique = map(lambda x: x, ensembl_symbol_db) interaction_lengths = [] import random while p < permutations: random_inputs = random.sample(ensembl_unique,len(input_IDs)) random_input_db={} #print len(random_inputs), len(input_IDs); sys.exit() for i in random_inputs: random_input_db[i]=i secondaryQueryIDs = importqueryResults(species,random_inputs,{})[0] input_IDs,query_interactions,dir_file = importqueryResults(species,inputDir,input_IDs) sif_file, symbol_pair_unique = associateQueryGenesWithInteractions(input_IDs,query_interactions,inputDir) #print len(symbol_pair_unique);sys.exit() interaction_lengths.append(len(symbol_pair_unique)) p+=1 interaction_lengths.sort(); interaction_lengths.reverse() y = len(original_symbol_pair_unique) print 'permuted length distribution:',interaction_lengths print 'original length:',y k=0 for i in interaction_lengths: if i>=y: k+=1 print 'p-value:',float(k)/float(permutations) def buildInteractions(species,Degrees,inputType,inputDir,outputdir,interactionDirs,Genes=None, geneSetType=None,PathwayFilter=None,OntologyID=None,directory=None,expressionFile=None, obligatorySet=None,secondarySet=None,IncludeExpIDs=False): global degrees global outputDir global inputDataType global obligatoryList ### Add these if connected to anything global secondaryQueryIDs global secondDegreeObligatoryCategories ### Add if common to anything in the input - Indicates systems to apply this to global symbol_hmdb_db; symbol_hmdb_db={}; global hmdb_symbol_db; hmdb_symbol_db={} ### Create an annotation database for HMDB IDs global FileName global intNameShort secondaryQueryIDs = {} degrees = Degrees outputDir = outputdir inputDataType = inputType obligatoryList = obligatorySet secondDegreeObligatoryCategories=[] intNameShort='' if obligatoryList == None: obligatoryList=[] if expressionFile == None: expressionFile = inputDir ### If it doesn't contain expression values, view as yellow nodes if secondarySet!= None and (degrees==1 or degrees=='direct'): ### If degrees == 2, this is redundant ### This currently adds alot of predictions - either make more stringent or currently exclude secondDegreeObligatoryCategories = secondarySet if PathwayFilter != None: if len(PathwayFilter)==1: FileName = PathwayFilter[0] if isinstance(PathwayFilter, tuple) or isinstance(PathwayFilter, list): FileName = string.join(list(PathwayFilter),' ') FileName = string.replace(FileName,':','-') else: FileName = PathwayFilter if len(FileName)>40: FileName = FileName[:40] elif OntologyID != None: FileName = OntologyID elif Genes != None: FileName = Genes ### Import Ensembl-Symbol annotations getEnsemblGeneData('AltDatabase/ensembl/'+species+'/'+species+'_Ensembl-annotations.txt') if len(interactionDirs[0]) == 1: interactionDirs = [interactionDirs] ### Import interaction databases indicated in interactionDirs for i in interactionDirs: print i i = export.findFilename(i) i=string.split(i,'-')[1] intNameShort+=i[0] importInteractionData(interactionDirs) getHMDBData(species) ### overwrite the symbol annotation from any HMDB that comes from a WikiPathway or KEGG pathway that we also include (for consistent official annotation) input_IDs = getGeneIDs(Genes) try: if isinstance(PathwayFilter, tuple): for pathway in PathwayFilter: IDs = gene_associations.simpleGenePathwayImport(species,geneSetType,pathway,OntologyID,directory) for id in IDs:input_IDs[id]=None else: input_IDs = gene_associations.simpleGenePathwayImport(species,geneSetType,PathwayFilter,OntologyID,directory) except Exception: None if expressionFile == None or len(expressionFile)==0: expressionFile = exportSelectedIDs(input_IDs) ### create an expression file elif IncludeExpIDs: ### Prioritize selection of IDs for interactions WITH the primary query set (not among expression input IDs) secondaryQueryIDs = importqueryResults(species,expressionFile,{})[0] input_IDs,query_interactions,dir_file = importqueryResults(species,inputDir,input_IDs) sif_file,symbol_pair_unique = associateQueryGenesWithInteractions(input_IDs,query_interactions,dir_file) output_filename = exportGraphImage(species,sif_file,expressionFile) return output_filename def exportSelectedIDs(input_IDs): expressionFile = outputDir+'/networks/IDList.txt' data = export.ExportFile(expressionFile) data.write('UID\tSystemCode\n') for id in input_IDs: if 'HMDB' in id: id = hmdb_symbol_db[id] data.write(id+'\tEn\n') data.close() return expressionFile def exportGraphImage(species,sif_file,expressionFile): import clustering output_filename = clustering.buildGraphFromSIF('Ensembl',species,sif_file,expressionFile) return output_filename def getGeneIDs(Genes): input_IDs={} if Genes == None: None elif len(Genes)>0: ### Get IDs from list of gene IDs Genes=string.replace(Genes,'|',',') Genes=string.replace(Genes,' ',',') if ',' in Genes: Genes = string.split(Genes,',') else: Genes = [Genes] for i in Genes: if len(i)>0: if i in symbol_ensembl_db: for ensembl in symbol_ensembl_db[i]: input_IDs[ensembl]=i ### Translate to Ensembl elif i in symbol_hmdb_db: hmdb=symbol_hmdb_db[i] symbol = hmdb_symbol_db[hmdb] ### Get the official symbol input_IDs[hmdb]=symbol ### Translate to HMDB else: try: input_IDs[i] = ensembl_symbol_db[i] ### If an input Ensembl ID except Exception: input_IDs[i] = i ### Currently not dealt with return input_IDs if __name__ == '__main__': Species = 'Hs' Degrees = 2 inputType = 'IDs' inputDir='' inputDir='/Users/nsalomonis/Desktop/dataAnalysis/Sarwal/Urine-AR-increased/met/networks/AltAnalyze-network_Met.inceased_AR_1.5fold_metabolite-interactions_shortest path.sif' inputDir='/Users/saljh8/Documents/1-dataAnalysis/PaulTang/ARVC_genes.txt' obligatorySet = []#['drugInteraction']#'microRNAInteraction' Genes = 'POU5F1,NANOG,TCF7L1,WNT1,CTNNB1,SOX2,TCF4,GSK3B' Genes = 'Glucose'; Degrees = 'shortestPath'; Degrees = 'indirect'; Degrees = 'all possible' Genes = ''; Degrees='indirect' interactionDirs = [] Genes='' outputdir = filepath('AltAnalyze/test') outputdir = '/Users/saljh8/Desktop/Archived/Documents/1-manuscripts/Salomonis/SIDS-WikiPathways/Interactomics/' interaction_root = 'AltDatabase/goelite/'+Species+'/gene-interactions' files = read_directory('AltDatabase/goelite/'+Species+'/gene-interactions') rooot = '/Users/nsalomonis/Desktop/dataAnalysis/Sarwal/CTOTC/AltAnalyze Based/GO-Elite/MarkerFinder/' expressionFile=None expressionFile = '/Users/nsalomonis/Desktop/dataAnalysis/Sarwal/Urine-AR-increased/UrinProteomics_Kidney-All/GO-Elite/input/GE.AR_vs_STA-fold1.5_rawp0.05.txt' expressionFile = '/Users/nsalomonis/Desktop/dataAnalysis/Sarwal/BKVN infection/GO-Elite/input/AR_vs_norm_adjp05.txt' expressionFile = '/Users/nsalomonis/Desktop/dataAnalysis/Sarwal/Blood AR-BK/AR-STA/Batches/overlap/AR_vs_STA_p0.05_fold1_common.txt' expressionFile=None #files2 = read_directory(rooot) #inputType = 'SIF' for file in files: if 'micro' not in file and 'all-Drug' not in file and 'GRID' not in file and 'Drug' not in file and 'TF' not in file: # and 'TF' not in file and 'KEGG' not in file: interactionDirs.append(filepath(interaction_root+'/'+file)) #""" inputDir='/Users/saljh8/Desktop/Archived/Documents/1-manuscripts/Salomonis/SIDS-WikiPathways/Interactomics/CoreGeneSet67/core_SIDS.txt' expressionFile = '/Users/saljh8/Desktop/Archived/Documents/1-manuscripts/Salomonis/SIDS-WikiPathways/Interactomics/Proteomics/proteomics_kinney.txt' interactionPermuteTest(Species,Degrees,inputType,inputDir,outputdir,interactionDirs,Genes=Genes,obligatorySet=obligatorySet,expressionFile=expressionFile, IncludeExpIDs=True) sys.exit() buildInteractions(Species,Degrees,inputType,inputDir,outputdir,interactionDirs,Genes=Genes,obligatorySet=obligatorySet,expressionFile=expressionFile, IncludeExpIDs=True) sys.exit() #""" #canonical Wnt signaling: GO:0060070 # BioMarkers 'Pluripotent Stem Cells' 'gene-mapp' #inputDir = '/Users/nsalomonis/Desktop/dataAnalysis/Sarwal/Diabetes-Blood/ACR/log2/MergedFiles-Symbol_ACR.txt' #inputDir = '/Users/nsalomonis/Desktop/dataAnalysis/SplicingFactors/RBM20_splicing_network.txt'; inputType = 'SIF' #inputDir = '/Users/nsalomonis/Documents/1-manuscripts/Salomonis/SIDS-WikiPathways/67_SIDS-genes.txt' #Genes=None #exportGraphImage(Species,'/Users/nsalomonis/Desktop/AltAnalyze/AltAnalyze/test/networks/AltAnalyze-network-interactions_1degrees.sif',inputDir);sys.exit() #buildInteractions(Species,Degrees,inputType,inputDir,outputdir,interactionDirs,Genes=None,obligatorySet=obligatorySet,geneSetType='BioMarkers',PathwayFilter='Pluripotent Stem Cells',directory='gene-mapp') buildInteractions(Species,Degrees,inputType,inputDir,outputdir,interactionDirs,Genes=Genes,obligatorySet=obligatorySet,expressionFile=expressionFile)<|fim▁end|>
<|file_name|>defaults.py<|end_file_name|><|fim▁begin|>__author__ = 'Artur Barseghyan <[email protected]>' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('FIT_METHOD_CROP_SMART', 'FIT_METHOD_CROP_CENTER', 'FIT_METHOD_CROP_SCALE', 'FIT_METHOD_FIT_WIDTH', 'FIT_METHOD_FIT_HEIGHT', 'DEFAULT_FIT_METHOD', 'FIT_METHODS_CHOICES', 'FIT_METHODS_CHOICES_WITH_EMPTY_OPTION', 'IMAGES_UPLOAD_DIR') from django.utils.translation import ugettext_lazy as _ FIT_METHOD_CROP_SMART = 'smart' FIT_METHOD_CROP_CENTER = 'center' FIT_METHOD_CROP_SCALE = 'scale' FIT_METHOD_FIT_WIDTH = 'fit_width' FIT_METHOD_FIT_HEIGHT = 'fit_height' DEFAULT_FIT_METHOD = FIT_METHOD_CROP_CENTER FIT_METHODS_CHOICES = ( (FIT_METHOD_CROP_SMART, _("Smart crop")), (FIT_METHOD_CROP_CENTER, _("Crop center")), (FIT_METHOD_CROP_SCALE, _("Crop scale")), (FIT_METHOD_FIT_WIDTH, _("Fit width")), (FIT_METHOD_FIT_HEIGHT, _("Fit height")),<|fim▁hole|>IMAGES_UPLOAD_DIR = 'dash-image-plugin-images'<|fim▁end|>
) FIT_METHODS_CHOICES_WITH_EMPTY_OPTION = [('', '---------')] + list(FIT_METHODS_CHOICES)
<|file_name|>waypointMaps.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python """ Copyright 2012 Paul Willworth <[email protected]> This file is part of Galaxy Harvester. Galaxy Harvester is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Galaxy Harvester 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<|fim▁hole|> along with Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>. """ import os import sys import cgi import Cookie import dbSession import dbShared import MySQLdb import ghShared import ghLists from jinja2 import Environment, FileSystemLoader # Get current url try: url = os.environ['SCRIPT_NAME'] except KeyError: url = '' uiTheme = '' form = cgi.FieldStorage() # Get Cookies useCookies = 1 cookies = Cookie.SimpleCookie() try: cookies.load(os.environ['HTTP_COOKIE']) except KeyError: useCookies = 0 if useCookies: try: currentUser = cookies['userID'].value except KeyError: currentUser = '' try: loginResult = cookies['loginAttempt'].value except KeyError: loginResult = 'success' try: sid = cookies['gh_sid'].value except KeyError: sid = form.getfirst('gh_sid', '') try: uiTheme = cookies['uiTheme'].value except KeyError: uiTheme = '' else: currentUser = '' loginResult = form.getfirst('loginAttempt', '') sid = form.getfirst('gh_sid', '') # Get a session logged_state = 0 linkappend = '' disableStr = '' # escape input to prevent sql injection sid = dbShared.dbInsertSafe(sid) if loginResult == None: loginResult = 'success' sess = dbSession.getSession(sid, 2592000) if (sess != ''): logged_state = 1 currentUser = sess if (uiTheme == ''): uiTheme = dbShared.getUserAttr(currentUser, 'themeName') if (useCookies == 0): linkappend = 'gh_sid=' + sid else: disableStr = ' disabled="disabled"' if (uiTheme == ''): uiTheme = 'crafter' pictureName = dbShared.getUserAttr(currentUser, 'pictureName') print 'Content-type: text/html\n' env = Environment(loader=FileSystemLoader('templates')) env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL template = env.get_template('waypointmaps.html') print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, galaxyList=ghLists.getGalaxyList(), planetList=ghLists.getPlanetList())<|fim▁end|>
GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License
<|file_name|>test_cmdparse.py<|end_file_name|><|fim▁begin|>import pickle import pytest from doit.cmdparse import DefaultUpdate, CmdParseError, CmdOption, CmdParse class TestDefaultUpdate(object): def test(self): du = DefaultUpdate() du.set_default('a', 0) du.set_default('b', 0) assert 0 == du['a'] assert 0 == du['b'] du['b'] = 1 du.update_defaults({'a':2, 'b':2}) assert 2 == du['a'] assert 1 == du['b'] def test_add_defaults(self): du = DefaultUpdate() du.add_defaults({'a': 0, 'b':1}) du['c'] = 5 du.add_defaults({'a':2, 'c':2}) assert 0 == du['a'] assert 1 == du['b'] assert 5 == du['c'] # http://bugs.python.org/issue826897 def test_pickle(self): du = DefaultUpdate() du.set_default('x', 0) dump = pickle.dumps(du,2) pickle.loads(dump) <|fim▁hole|>class TestCmdOption(object): def test_repr(self): opt = CmdOption({'name':'opt1', 'default':'', 'short':'o', 'long':'other'}) assert "CmdOption(" in repr(opt) assert "'name':'opt1'" in repr(opt) assert "'short':'o'" in repr(opt) assert "'long':'other'" in repr(opt) def test_non_required_fields(self): opt1 = CmdOption({'name':'op1', 'default':''}) assert '' == opt1.long def test_invalid_field(self): opt_dict = {'name':'op1', 'default':'', 'non_existent':''} pytest.raises(CmdParseError, CmdOption, opt_dict) def test_missing_field(self): opt_dict = {'name':'op1', 'long':'abc'} pytest.raises(CmdParseError, CmdOption, opt_dict) class TestCmdOption_help_param(object): def test_bool_param(self): opt1 = CmdOption({'name':'op1', 'default':'', 'type':bool, 'short':'b', 'long': 'bobo'}) assert '-b, --bobo' == opt1.help_param() def test_non_bool_param(self): opt1 = CmdOption({'name':'op1', 'default':'', 'type':str, 'short':'s', 'long': 'susu'}) assert '-s ARG, --susu=ARG' == opt1.help_param() def test_no_long(self): opt1 = CmdOption({'name':'op1', 'default':'', 'type':str, 'short':'s'}) assert '-s ARG' == opt1.help_param() opt_bool = {'name': 'flag', 'short':'f', 'long': 'flag', 'inverse':'no-flag', 'type': bool, 'default': False, 'help': 'help for opt1'} opt_rare = {'name': 'rare', 'long': 'rare-bool', 'type': bool, 'default': False, 'help': 'help for opt2'} opt_int = {'name': 'num', 'short':'n', 'long': 'number', 'type': int, 'default': 5, 'help': 'help for opt3'} opt_no = {'name': 'no', 'short':'', 'long': '', 'type': int, 'default': 5, 'help': 'user cant modify me'} class TestCmdOption_help_doc(object): def test_param(self): opt1 = CmdOption(opt_bool) got = opt1.help_doc() assert '-f, --flag' in got[0] assert 'help for opt1' in got[0] assert '--no-flag' in got[1] assert 2 == len(got) def test_no_doc_param(self): opt1 = CmdOption(opt_no) assert 0 == len(opt1.help_doc()) class TestCommand(object): @pytest.fixture def cmd(self, request): opt_list = (opt_bool, opt_rare, opt_int, opt_no) options = [CmdOption(o) for o in opt_list] cmd = CmdParse(options) return cmd def test_short(self, cmd): assert "fn:" == cmd.get_short(), cmd.get_short() def test_long(self, cmd): assert ["flag", "no-flag", "rare-bool", "number="] == cmd.get_long() def test_getOption(self, cmd): # short opt, is_inverse = cmd.get_option('-f') assert (opt_bool['name'], False) == (opt.name, is_inverse) # long opt, is_inverse = cmd.get_option('--rare-bool') assert (opt_rare['name'], False) == (opt.name, is_inverse) # inverse opt, is_inverse = cmd.get_option('--no-flag') assert (opt_bool['name'], True) == (opt.name, is_inverse) # not found opt, is_inverse = cmd.get_option('not-there') assert (None, None) == (opt, is_inverse) def test_parseDefaults(self, cmd): params, args = cmd.parse([]) assert False == params['flag'] assert 5 == params['num'] def test_parseShortValues(self, cmd): params, args = cmd.parse(['-n','89','-f']) assert True == params['flag'] assert 89 == params['num'] def test_parseLongValues(self, cmd): params, args = cmd.parse(['--rare-bool','--num','89', '--no-flag']) assert True == params['rare'] assert False == params['flag'] assert 89 == params['num'] def test_parsePositionalArgs(self, cmd): params, args = cmd.parse(['-f','p1','p2','--sub-arg']) assert ['p1','p2','--sub-arg'] == args def test_parseError(self, cmd): pytest.raises(CmdParseError, cmd.parse, ['--not-exist-param']) def test_parseWrongType(self, cmd): pytest.raises(CmdParseError, cmd.parse, ['--num','oi'])<|fim▁end|>
<|file_name|>ajax.py<|end_file_name|><|fim▁begin|># coding=utf-8 import os from __init__ import * import traceback, cStringIO, re from flask import current_app from werkzeug.datastructures import FileStorage from server import user_server, article_server, status_server, form, \ account_server, news_server, resource_server from server import general, honor_server from dao.dbACCOUNT import Account from dao import dbCompetition, dbPlayer from util import json, CJsonEncoder from flask.globals import _app_ctx_stack from flask import request, jsonify from sqlalchemy.exc import IntegrityError from server.account_server import AccountUpdatingException, AccountExistException from util import function # # @blueprint: ajax # @created: 2015/06/22 # @author: Z2Y # ajax = blueprints.Blueprint('ajax', __name__) # # @brief: json for recent contest # @route: /ajax/contest.json # @allowed user: public # @ajax.route("/ajax/contest.json", methods=['GET']) def recent_contests(): import json json_file = open(RECENT_CONTEST_JSON, 'r').read() json_contests = json.JSONDecoder().decode(json_file) contests = [] for contest in json_contests: name, link = contest['name'], contest['link'] new_contest = { 'oj': contest['oj'], 'name': '<a href="' + link + '" class="contest-name" title="' + name + '">' + name + '</a>', 'start_time': contest['start_time'], 'access': contest['access'], } contests.append(new_contest) return json.dumps({ 'data': contests }) # # @brief: ajax rank list # @route: /ajax/rank_list # @allowed user: student and coach # @ajax.route('/ajax/main_rank_table') def main_rank_table(): main_rank_list = general.get_rank_list() return json.dumps({ 'data': main_rank_list }) # # @brief: ajax html for one user item # @allowed user: admin and coach # @login_required def get_user_list_item(user): return render_template('ajax/user_list_item.html', user = user, school_mapper = SCHOOL_MAP, college_mapper = SCHOOL_COLLEGE_MAP) # # @brief: ajax user list # @route: /ajax/user_list # @allowed user: admin and coach # @ajax.route('/ajax/user_list', methods=["GET", "POST"]) @login_required def get_users(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) search = request.args.get('search', None) per_page = USER_MANAGE_PER_PAGE pagination = None if current_user.is_admin: pagination = user_server.get_list_pageable(page, per_page, search=search) elif current_user.is_coach: pagination = user_server.get_list_pageable(page, per_page, search=search, school=current_user.school) page_list = list(pagination.iter_pages(left_current=1, right_current=2)) return jsonify(items=[get_user_list_item(user) for user in pagination.items], prev_num=pagination.prev_num, next_num=pagination.next_num, page_list=page_list, page=pagination.page, pages=pagination.pages) # # @brief: add user # @route: /ajax/create_user # @accepted methods: [post] # @allowed user: admin and coach # @ajax return: 用户是否添加成功 # @ajax.route('/ajax/create_user', methods=["POST"]) @login_required def create_user(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) reg_form = form.RegisterForm() if reg_form.validate_on_submit(): try: rights_list = request.form.getlist('rights') rights = 0 for item in rights_list: rights = rights | int(item) ret = user_server.create_user(reg_form, rights) if ret == 'OK': return u"添加用户成功" return u"添加用户失败: " + ret except Exception, e: current_app.logger.error(traceback.format_exc()) return u"添加用户失败: " + e.message else: #print reg_form.errors return u"添加用户失败: 表单填写有误" # # @brief: add many users # @route: /ajax/create_users # @accepted methods: [post] # @allowed user: admin and coach # @ajax return: 用户添加成功的数量 # @ajax.route('/ajax/create_users', methods=["POST"]) @login_required def create_users(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) reg_form = form.MultiRegisterForm() if reg_form.validate_on_submit(): try: ret = user_server.create_many_users(reg_form, current_user) return ret except Exception, e: current_app.logger.error(traceback.format_exc()) return u"添加用户失败: " + e.message else: #print reg_form.errors return u"添加用户失败: 表单填写有误" # # @brief: check apply user # @route: /ajax/check_apply # @accepted methods: [post] # @allowed user: admin and coach # @ajax return: 操作结果 # @ajax.route("/ajax/check_apply", methods= ['POST']) @login_required def check_apply(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) try: apply_id = request.form.get('uid') user = user_server.get_by_id(apply_id) opt = request.form.get('opt') ret = user_server.update_apply(apply_id, opt) if ret == 'OK': function.reply_of_apply(mail, user.serialize, _app_ctx_stack.top, opt) return ret except Exception: current_app.logger.error(traceback.format_exc()) return u'操作失败' # # @brief: edit user # @route: /ajax/edit_user # @accepted methods: [post] # @allowed user: admin and coach # @ajax.route('/ajax/edit_user', methods=["POST"]) @login_required def edit_user(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) user_modify_form = form.UserModifyForm() if user_modify_form.validate_on_submit(): try: rights_list = request.form.getlist('rights') rights = 0 for item in rights_list: rights = rights | int(item) ret = user_server.update_user(user_modify_form, rights) if ret == 'OK': return u"修改用户成功" return u'修改用户失败: ' + ret except Exception, e: current_app.logger.error(traceback.format_exc()) return u"修改用户失败: " + e.message else: #print user_modify_form.errors return u"修改用户失败: 表单填写有误" # # @brief: edit user for self # @route: /ajax/edit_user_self # @accepted methods: [post] # @allowed user: all # @ajax.route('/ajax/edit_user_self', methods=["POST"]) @login_required def edit_user_self(): user_modify_form = form.UserModifyForm() if user_modify_form.validate_on_submit(): try: ret = user_server.update_user(user_modify_form, for_self=True) if ret == 'OK': return u"修改用户成功" return u'修改用户失败: ' + ret except Exception, e: current_app.logger.error(traceback.format_exc()) return u"修改用户失败: " + e.message else: #print user_modify_form.errors return u"修改用户失败: 表单填写有误" # # @brief: modify password # @route: /ajax/modify_password # @accepted methods: [post] # @allowed user: all # @ajax return: 密码是否修改成功 => string # @ajax.route('/ajax/modify_password', methods=['POST']) @login_required def modify_password(): pwd_modify_form = form.PasswordModifyForm() if pwd_modify_form.validate_on_submit(): if not current_user.verify_password(pwd_modify_form.password.data): return u"当前密码输入错误" return user_server.modify_password(pwd_modify_form, current_user) return u"修改密码失败" # # @brief: delete user # @route: /ajax/delete_user<|fim▁hole|># @allowed user: admin and coach # @ajax.route('/ajax/delete_user', methods=["POST"]) @login_required def delete_user(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) try: id = request.form.get('user_id') user_server.delete_by_id(id) return u"OK" except Exception, e: current_app.logger.error(traceback.format_exc()) return u"FAIL" # # @brief: ajax html for one user item # @allowed user: administrator # @login_required def get_news_list_item(news): return render_template('ajax/news_list_item.html', news=news) # # @brief: ajax news list # @route: /ajax/news_list # @allowed user: administrator # @ajax.route('/ajax/news_list', methods=['GET', 'POST']) @login_required def get_news_list(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) search = request.args.get('search', None) per_page = NEWS_MANAGE_PER_PAGE pagination = news_server.get_list_pageable(page, per_page, show_draft=True, search=search) page_list = list(pagination.iter_pages(left_current=1, right_current=2)) return jsonify(items=[get_news_list_item(news) for news in pagination.items], prev_num=pagination.prev_num, next_num=pagination.next_num, page_list=page_list, page=pagination.page, pages=pagination.pages) # # @brief: delete news # @route: /ajax/delete_news # @accepted methods: [post] # @allowed user: admin and coach # @ajax.route("/ajax/delete_news", methods = ['POST']) @login_required def delete_news(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) try: news_id = request.form.get('news_id') news_server.delete_by_id(news_id) return u'OK' except Exception, e: current_app.logger.error(traceback.format_exc()) return u'FAIL' # # @brief: post news # @route: /ajax/post_news # @accepted methods: [post] # @allowed user: admin and coach # @ajax.route('/ajax/post_news', methods=['POST']) @login_required def post_news(): if not current_user.is_admin and not current_user.is_coach: return u"没有权限" news_form = form.NewsForm() if news_form.validate_on_submit(): try: is_draft = int(request.args['draft']) news_server.post(news_form, current_user, is_draft) return u"发表成功!" except IntegrityError: current_app.logger.error(traceback.format_exc()) return u"发表新闻失败: 固定链接已存在" except Exception, e: current_app.logger.error(traceback.format_exc()) return u"发表新闻失败: " + e.message else: return u"发表新闻失败,请检查内容" # # @brief: ajax html for one account item # @allowed user: self, admin and coach # @login_required def get_account_item(account, user): return render_template('ajax/account_info_item.html', account = account, user = user, str = str) # # @brief: add or modify account # @route: /ajax/account_manager # @accepted methods: [post] # @allowed user: administrator or the user # @ajax.route('/ajax/account_info_list', methods=['POST', 'GET']) @login_required def account_info_list(): try: profile_user = user_server.get_by_username_or_404(request.args['username']) except: profile_user = current_user account_info_list = account_server.get_account_info_list(profile_user) return jsonify(account_list = [get_account_item(account_info, profile_user) for account_info in account_info_list], length = len(account_info_list)) # # @brief: update the statistics info of account # @route: /ajax/update_account # @accepted methods: [post] # @allowed user: admin, coach or the user # @ajax.route('/ajax/update_account', methods=['POST']) @login_required def update_account(): try: profile_user = user_server.get_by_id(request.form.get('user_id')) except: profile_user = current_user if profile_user != current_user and\ (not current_user.is_admin and not current_user.is_coach_of(profile_user)): return u"没有权限" try: account_id = request.form.get('account_id') account_server.update_account_by_id(account_id) return u"ok" except AccountUpdatingException, e: current_app.logger.error(traceback.format_exc()) return 'ERROR: ' + e.message except: current_app.logger.error(traceback.format_exc()) return 'ERROR: unknown error' # # @brief: add or modify account # @route: /ajax/account_manager # @accepted methods: [post] # @allowed user: administrator or the user # @ajax return: string # @ajax.route('/ajax/account_manager', methods=['POST']) @login_required def account_manager(): try: profile_user = user_server.get_by_username_or_404(request.args['username']) except: profile_user = current_user account_form = form.AccountForm() if current_user != profile_user and\ (not current_user.is_admin and not current_user.is_coach_of(profile_user)): return u"没有权限" if account_form.validate_on_submit(): try: has_account = Account.query\ .filter_by(user=profile_user, oj_name=account_form.oj_name.data)\ .first() if has_account: account_server.modify_account(has_account, account_form) return u"ok" else: account_server.add_account(profile_user, account_form) return u"ok" except AccountUpdatingException, e: current_app.logger.error(traceback.format_exc()) return 'ERROR: ' + e.message except AccountExistException, e: current_app.logger.error(traceback.format_exc()) return 'ERROR: ' + e.message except: current_app.logger.error(traceback.format_exc()) return 'ERROR: unknown error' else: return u"添加账号失败" # # @brief: delete account # @route: /ajax/delete_account # @accepted methods: [post] # @allowed user: administrator or the user # @ajax return: string # @ajax.route('/ajax/delete_account', methods=['POST']) @login_required def delete_account(): try: profile_user = user_server.get_by_id(request.form.get('user_id')) except: profile_user = current_user if profile_user != current_user and\ (not current_user.is_admin and not current_user.is_coach_of(profile_user)): return u"没有权限" try: account_id = request.form.get('account_id') account_server.delete_account_by_id(profile_user, account_id) return u"OK" except AccountUpdatingException, e: current_app.logger.error(traceback.format_exc()) return 'ERROR: ' + e.message except: current_app.logger.error(traceback.format_exc()) return 'ERROR: unknown error' # # @brief: add or modify solution # @route: /ajax/solution_manager # @accepted methods: [post] # @allowed user: administrator or the user # @ajax return: string # @ajax.route('/ajax/solution_manager', methods=['POST']) @login_required def solution_manager(): try: profile_user = user_server.get_by_username_or_404(request.args['username']) except: profile_user = current_user solution_form = form.SolutionForm() if solution_form.validate_on_submit(): try: is_draft = int(request.args['draft']) article_server.post(solution_form, profile_user, is_draft) return u"发表成功!" except Exception, e: current_app.logger.error(traceback.format_exc()) return u"发表文章失败" + e.message else: return u"发表文章失败,请检查内容" # # @brief: ajax to get status list # @route: /ajax/fitch_status/<oj_name> # @allowed user: all # @ajax.route('/ajax/fitch_status/<oj_name>', methods=['POST']) @login_required def fitch_status(oj_name): headers = ['account_name', 'run_id', 'pro_id', 'lang', 'run_time', 'memory', 'submit_time'] ret = status_server.DataTablesServer(request.form, oj_name, headers).run_query() return json.dumps(ret, cls=CJsonEncoder) # # @brief: ajax html for one img choose item # @allowed user: admin and coach # @login_required def get_img_choose_item(img_item): return render_template('ajax/img-choose-item.html', img_item = img_item, file_url = resource_server.file_url) # # @brief: ajax img choose list # @route: /ajax/img_choose_list # @allowed user: admin and coach # @ajax.route('/ajax/img_choose_list', methods=["POST"]) @login_required def get_img_choose_list(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) offset = request.form.get('offset') limit = request.form.get('limit') type = request.form.get('type') from dao.dbResource import ResourceUsage if type == 'honor': images = resource_server.get_image_list(offset, limit, ResourceUsage.HONOR_RES) sum = resource_server.get_image_count(ResourceUsage.HONOR_RES) else: images = resource_server.get_image_list(offset, limit) sum = resource_server.get_image_count() return jsonify(img_list=[get_img_choose_item(img) for img in images], sum=sum, offset=int(offset), limit=len(images)) # # @brief: ajax html for one resource item # @allowed user: self, admin and coach # @login_required def get_resource_list_item(resource): return render_template('ajax/resource_list_item.html', resource = resource, file_size = resource_server.file_size, file_url = resource_server.file_url) # # @brief: ajax resource list # @route: /ajax/resource_list # @accepted methods: [post] # @allowed user: self, admin, coach # @ajax.route('/ajax/resource_list', methods=['GET', 'POST']) @login_required def get_resource_list(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) search = request.args.get('search', None) per_page = RESOURCE_MANAGE_PER_PAGE pagination = resource_server.get_list_pageable(page, per_page, current_user, search) page_list = list(pagination.iter_pages(left_current=1, right_current=2)) return jsonify(items=[get_resource_list_item(resource) for resource in pagination.items], prev_num=pagination.prev_num, next_num=pagination.next_num, page_list=page_list, page=pagination.page, pages=pagination.pages) # # @brief: ajax to upload resource # @route: /ajax/upload # @accepted methods: [post] # @ajax.route('/ajax/upload', methods=['POST']) @login_required def upload(): file_form = form.FileUploadForm() if file_form.validate_on_submit(): try: if file_form.upload.data: file = request.files[file_form.upload.name] msg = resource_server.save_file(file_form, file, current_user, 'other') return msg else: return u'上传数据失败' except Exception, e: current_app.logger.error(traceback.format_exc()) return u'错误: ' + e.message return u'数据填写有误' # # @brief: ajax to upload poster # @route: /ajax/upload # @accepted methods: [post] # @ajax.route('/ajax/upload/poster', methods=['POST']) @login_required def upload_poster(): from dao.dbResource import ResourceLevel, ResourceUsage file_form = form.FileUploadForm() file_form.level.data = str(ResourceLevel.PUBLIC) file_form.usage.data = str(ResourceUsage.POSTER_RES) if file_form.validate_on_submit(): try: file_canvas = request.form.get('croppedImage') if file_canvas: file_string = re.sub('^data:image/.+;base64,', '', file_canvas).decode('base64') file_binary = cStringIO.StringIO(file_string) file = FileStorage(file_binary, file_form.name.data + '.jpg') msg = resource_server.save_file(file_form, file, current_user, 'poster') return msg else: return u'上传数据失败' except Exception, e: current_app.logger.error(traceback.format_exc()) return u'错误: ' + e.message current_app.logger.error(file_form.errors) return u'数据填写有误' # # @brief: ajax to get modal with edit-resource form # @route: /ajax/resource_info # @accepted methods: [post] # @ajax.route('/ajax/resource_info', methods=['POST']) @login_required def get_resource_info(): resource_id = request.form.get('resource_id') rs = resource_server.get_by_id(resource_id) if rs.level >= 2 and not current_user.is_admin and not current_user.is_coach_of(rs.user): return u'permission denied' file_edit_form = form.FileInfoForm() if not current_user.is_admin and not current_user.is_coach: file_edit_form.usage.choices = [('3',u'题解资源'), ('4',u'其他资源')] file_edit_form.id.data = rs.id file_edit_form.level.data = str(rs.level) file_edit_form.name.data = rs.name file_edit_form.description.data = rs.description file_edit_form.usage.data = str(rs.usage) return render_template('ajax/resource_modify_modal.html', file_edit_form = file_edit_form) # # @brief: ajax to edit resource # @route: /ajax/resource_info # @accepted methods: [post] # @ajax.route("/ajax/edit_resource", methods = ['POST']) @login_required def edit_resource(): file_edit_form = form.FileInfoForm() if file_edit_form.validate_on_submit(): return resource_server.modify_file(file_edit_form, current_user) return u'表单填写错误' # # @brief: ajax to delete resource # @route: /ajax/delete_resource # @accepted methods: [post] # @ajax.route("/ajax/delete_resource", methods = ['POST']) @login_required def delete_resource(): try: resource_id = request.form.get('resource_id') msg = resource_server.delete_file(resource_id, current_user) return msg except: current_app.logger.error(traceback.format_exc()) return u'删除失败' # # @brief: ajax html for one honor item # @allowed user: self, admin and coach # @login_required def get_honor_list_item(honor): from config import HONOR_LEVEL_MAP return render_template('ajax/honor_list_item.html', honor = honor, level_mapper = HONOR_LEVEL_MAP) # # @brief: ajax honor list # @route: /ajax/honor_list # @accepted methods: [post] # @allowed user: self, admin, coach # @ajax.route('/ajax/honor_list', methods=['GET', 'POST']) @login_required def get_honor_list(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) search = request.args.get('search', None) per_page = HONOR_MANAGE_PER_PAGE pagination = honor_server.get_list_pageable(page, per_page, search) page_list = list(pagination.iter_pages(left_current=1, right_current=2)) return jsonify(items=[get_honor_list_item(honor) for honor in pagination.items], prev_num=pagination.prev_num, next_num=pagination.next_num, page_list=page_list, page=pagination.page, pages=pagination.pages) # # @brief: ajax to add honor # @route: /ajax/add_honor # @accepted methods: [post] # @allowed user: self, admin, coach # @ajax.route("/ajax/add_honor", methods = ['POST']) @login_required def add_honor(): honor_form = form.HonorForm() file_form = form.FileUploadForm() honor_form.users.choices = user_server.get_user_choice() if honor_form.validate_on_submit(): try: from dao.dbResource import ResourceLevel, ResourceUsage resource_list = [] for name, file in request.files.items(multi=True): file_form.level.data = ResourceLevel.PUBLIC file_form.name.data = unicode(file.filename).split('.')[0] file_form.usage.data = ResourceUsage.HONOR_RES resource_server.save_file(file_form, file, current_user, 'honor') resource = resource_server.get_by_name(file_form.name.data) resource_list.append(resource) msg = honor_server.add_honor(honor_form, resource_list) return msg except Exception, e: current_app.logger.error(traceback.format_exc()) return 'failed' return u'数据填写有误' # # @brief: ajax to modify honor # @route: /ajax/modify_honor # @accepted methods: [post] # @allowed user: self, admin, coach # @ajax.route("/ajax/modify_honor", methods = ['POST']) @login_required def modify_honor(): honor_form = form.HonorForm() file_form = form.FileUploadForm() honor_form.users.choices = user_server.get_user_choice() if honor_form.validate_on_submit(): try: honor = honor_server.get_by_id(honor_form.id.data) from dao.dbResource import ResourceLevel, ResourceUsage resource_list = [] for name, file in request.files.items(multi=True): if file.filename == '': continue file_form.level.data = ResourceLevel.PUBLIC file_form.name.data = unicode(file.filename).split('.')[0] file_form.usage.data = ResourceUsage.HONOR_RES ret = resource_server.save_file(file_form, file, current_user, 'honor') if ret == 'OK': resource = resource_server.get_by_name(file_form.name.data) resource_list.append(resource) msg = honor_server.modify_honor(honor, honor_form, resource_list) return msg except: current_app.logger.error(traceback.format_exc()) return 'failed' return u'数据填写有误' # # @brief: ajax to delete honor # @route: /ajax/delete_honor # @accepted methods: [post] # @allowed user: self, admin, coach # @ajax.route("/ajax/delete_honor", methods = ['POST']) @login_required def delete_honor(): try: honor_id = request.form.get('honor_id') msg = honor_server.delete_honor(honor_id) return msg except: current_app.logger.error(traceback.format_exc()) return u'FAIL' # not used @login_required def get_article_list_item(article): return render_template('ajax/article_list_item.html', article = article) # # @brief: ajax article list # @route: /ajax/article_list # @accepted methods: [post] # @allowed user: self, admin, coach # @ajax.route("/ajax/article_list", methods = ['POST']) @login_required def get_article_list(): offset = request.form.get('offset') limit = request.form.get('limit') article_list = article_server.get_list(offset, limit, current_user) sum = article_server.get_count(current_user) return jsonify(article_list=[get_article_list_item(article) for article in article_list], sum=sum, offset=int(offset), limit=len(article_list)) # not used @login_required def get_related_submits_item(submit): return render_template('ajax/related_submits_item.html', submit=submit) # not used @ajax.route("/ajax/related_submits", methods = ['POST']) @login_required def get_related_submits(): article_id = request.form.get('article_id') offset = request.form.get('offset') limit = request.form.get('limit') one = article_server.get_by_id(article_id) related_submits = article_server.related_submits(one, offset, limit) sum = article_server.related_submits_count(one) return jsonify(submits_list=[get_related_submits_item(submit) for submit in related_submits], sum=sum, offset=int(offset), limit=len(related_submits)) # not used @login_required def get_related_article_item(article): return render_template('ajax/related_article_item.html', article=article) # not used @ajax.route("/ajax/related_article", methods = ['POST']) @login_required def get_related_article(): submit_id = request.form.get('submit_id') offset = request.form.get('offset') limit = request.form.get('limit') one = general.get_submit_by_id(submit_id) related_article = general.related_article(one, offset, limit) sum = general.related_article_count(one) return jsonify(article_list=[get_related_article_item(article) for article in related_article], sum=sum, offset=int(offset), limit=len(related_article)) # # @brief: ajax to delete article # @route: /ajax/delete_article # @accepted methods: [post] # @allowed user: self, admin, coach # @ajax.route("/ajax/delete_article", methods = ['POST']) @login_required def delete_article(): try: article_id = request.form.get('article_id') article_server.delete_by_id(article_id) return u'删除成功' except Exception, e: current_app.logger.error(traceback.format_exc()) return u'删除失败' # # @brief: ajax to get member situation list # @route: /ajax/members # @accepted methods: [get] # @allowed user: public # @ajax.route("/ajax/members", methods=['GET']) def members(): all_users = user_server.get_list(limit=-1) users = [] for user in all_users: if user.is_student: users.append({ 'name': user.name, 'college': SCHOOL_COLLEGE_MAP[user.college] if user.college else '', 'grade': user.grade + u'级' if user.grade else '', 'situation': user.situation }) return json.dumps({ 'data': users }) # # @brief: ajax html for one competition item # @allowed user: admin and coach # @login_required def get_competition_list_item(competition): from datetime import datetime diff = (competition.event_date - datetime.today()).days if diff > 2: process = 0 elif diff > -1: process = 1 else: process = 2 return render_template('ajax/competition_list_item.html', competition = competition, len = len, process = process) # # @brief: ajax competition list # @route: /ajax/competition_list # @allowed user: admin and coach # @ajax.route('/ajax/competition_list', methods=["GET", "POST"]) @login_required def get_competitions(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) search = request.args.get('search', None) per_page = COMPETITION_MANAGE_PER_PAGE pagination = dbCompetition.get_list_pageable(page, per_page, search=search) page_list = list(pagination.iter_pages(left_current=1, right_current=2)) return jsonify(items=[get_competition_list_item(c) for c in pagination.items], prev_num=pagination.prev_num, next_num=pagination.next_num, page_list=page_list, page=pagination.page, pages=pagination.pages) @ajax.route("/ajax/add_competition", methods = ['POST']) @login_required def add_competition(): competition_form = form.CompetitionForm() if competition_form.validate_on_submit(): try: feedback = dbCompetition.create_competition(competition_form) if feedback == 'OK': return '添加成功' else: return feedback except Exception, e: current_app.logger.error(traceback.format_exc()) return u'添加失败' return u'数据填写有误' @ajax.route("/ajax/edit_competition", methods = ['POST']) @login_required def edit_competition(): competition_form = form.CompetitionForm() if competition_form.validate_on_submit(): try: id = request.form.get('id') feedback = dbCompetition.update_competition(id, competition_form) if feedback == 'OK': return '修改成功' except Exception, e: current_app.logger.error(traceback.format_exc()) return u'修改失败' return u'数据填写有误' @ajax.route("/ajax/delete_competition", methods = ['POST']) @login_required def delete_competition(): try: competition_id = request.form.get('competition_id', -1, type=int) dbCompetition.delete_by_id(competition_id) return u'OK' except Exception, e: current_app.logger.error(traceback.format_exc()) return u'删除失败' # # @brief: ajax html for one player item # @allowed user: admin and coach # @login_required def get_player_list_item(player): return render_template('ajax/player_list_item.html', player = player, college_mapper = SCHOOL_COLLEGE_MAP) # # @brief: ajax player list # @route: /ajax/player_list # @allowed user: admin and coach # @ajax.route('/ajax/player_list', methods=["GET", "POST"]) @login_required def get_players(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) search = request.args.get('search', None) competition_id = request.args.get('competition', 1, type=int) per_page = COMPETITION_MANAGE_PER_PAGE competition = dbCompetition.get_by_id(competition_id) pagination = dbCompetition.get_players_pageable(competition, page, per_page, search=search) page_list = list(pagination.iter_pages(left_current=1, right_current=2)) return jsonify(items=[get_player_list_item(p) for p in pagination.items], prev_num=pagination.prev_num, next_num=pagination.next_num, page_list=page_list, page=pagination.page, pages=pagination.pages) @ajax.route("/ajax/delete_player", methods = ['POST']) @login_required def delete_player(): try: player_id = request.form.get('player_id', -1, type=int) dbPlayer.delete_by_id(player_id) return u'OK' except Exception, e: current_app.logger.error(traceback.format_exc()) return u'删除失败'<|fim▁end|>
# @accepted methods: [post]
<|file_name|>cmac.py<|end_file_name|><|fim▁begin|># This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function from cryptography import utils from cryptography.exceptions import ( AlreadyFinalized, UnsupportedAlgorithm, _Reasons ) from cryptography.hazmat.backends.interfaces import CMACBackend from cryptography.hazmat.primitives import ciphers, mac @utils.register_interface(mac.MACContext) class CMAC(object): def __init__(self, algorithm, backend, ctx=None): if not isinstance(backend, CMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement CMACBackend.", _Reasons.BACKEND_MISSING_INTERFACE ) if not isinstance(algorithm, ciphers.BlockCipherAlgorithm): raise TypeError( "Expected instance of BlockCipherAlgorithm." ) self._algorithm = algorithm self._backend = backend if ctx is None: self._ctx = self._backend.create_cmac_ctx(self._algorithm) else: self._ctx = ctx def update(self, data): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") if not isinstance(data, bytes): raise TypeError("data must be bytes.") self._ctx.update(data) def finalize(self): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.")<|fim▁hole|> def verify(self, signature): if not isinstance(signature, bytes): raise TypeError("signature must be bytes.") if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") ctx, self._ctx = self._ctx, None ctx.verify(signature) def copy(self): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") return CMAC( self._algorithm, backend=self._backend, ctx=self._ctx.copy() )<|fim▁end|>
digest = self._ctx.finalize() self._ctx = None return digest
<|file_name|>mixins.py<|end_file_name|><|fim▁begin|>import warnings from xigt.consts import ( ID, TYPE, ALIGNMENT, CONTENT, SEGMENTATION ) from xigt.errors import ( XigtError, XigtStructureError ) from xigt.ref import id_re # list.clear() doesn't exist in Python2, but del list[:] has other problems try: [].clear except AttributeError: def listclear(x): del x[:] else: def listclear(x): list.clear(x) def _has_parent(obj): return hasattr(obj, '_parent') and obj._parent is not None class XigtContainerMixin(list): """ Common methods for accessing subelements in XigtCorpus, Igt, and Tier objects. """ def __init__(self, container=None, contained_type=None): self._dict = {} self._contained_type = contained_type self._container = container if container is not None else self def __eq__(self, other): try: return ( # quick check for comparing, e.g., XigtCorpus and Igt self._contained_type == other._contained_type and len(self) == len(other) and all(a == b for a, b in zip(self, other)) ) except AttributeError: return False def __getitem__(self, obj_id): if isinstance(obj_id, (int, slice)): return list.__getitem__(self, obj_id) elif obj_id in self._dict: return self._dict[obj_id] else: try: return list.__getitem__(self, int(obj_id)) except ValueError: pass raise KeyError(obj_id) def __setitem__(self, idx, obj): # only allow list indices, not dict keys (IDs) # NOTE: this method is destructive. check for broken refs here? self._assert_type(obj) try: cur_obj = list.__getitem__(self, idx) except TypeError: idx = int(idx) cur_obj = list.__getitem__(self, idx) if cur_obj.id is not None: del self._dict[cur_obj.id] self._create_id_mapping(obj) list.__setitem__(self, idx, obj) def __delitem__(self, obj_id): # NOTE: this method is destructive. check for broken refs here? obj = self[obj_id] self.remove(obj) def get(self, obj_id, default=None): try: return self[obj_id]<|fim▁hole|> except (KeyError, IndexError): pass return default def select(self, **kwargs): # handle namespace separately so we can lookup the nsmap if 'namespace' in kwargs and kwargs['namespace'] in self.nsmap: kwargs['namespace'] = self.nsmap[kwargs['namespace']] def match(x): return all(getattr(x, k, None) == v for k, v in kwargs.items()) return filter(match, self) def _assert_type(self, obj): if self._contained_type and not isinstance(obj, self._contained_type): raise XigtStructureError( 'Only {} objects are allowed in this container.' .format(self._contained_type.__name__) ) def append(self, obj): self._assert_type(obj) obj._parent = self._container self._create_id_mapping(obj) list.append(self, obj) def insert(self, i, obj): self._assert_type(obj) obj._parent = self._container self._create_id_mapping(obj) list.insert(self, i, obj) def extend(self, objs): for obj in objs: self.append(obj) def remove(self, obj): # NOTE: this method is destructive. check for broken refs here? if obj.id is not None: del self._dict[obj.id] list.remove(self, obj) def clear(self): self._dict.clear() # list.clear doesn't exist in Python2 # list.clear(self) listclear(self) def _create_id_mapping(self, obj): if obj.id is not None: if obj.id in self._dict: raise XigtError( 'Id "{}" already exists in collection.'.format(obj.id), ) self._dict[obj.id] = obj def refresh_index(self): self._dict = {} for obj in self: self._create_id_mapping(obj) # deprecated methods def add(self, obj): warnings.warn( 'add(x) is deprecated; use append(x) instead.', DeprecationWarning ) return self.append(obj) def add_list(self, objs): warnings.warn( 'add_list(xs) is deprecated; use extend(xs) instead.', DeprecationWarning ) return self.extend(objs) class XigtAttributeMixin(object): def __init__(self, id=None, type=None, attributes=None, namespace=None, nsmap=None): self.id = id self.type = type self.attributes = dict(attributes or []) self.namespace = namespace self.nsmap = nsmap # if id is not None or ID not in self.attributes: # self.attributes[ID] = id # if type is not None or TYPE not in self.attributes: # self.attributes[TYPE] = type def __eq__(self, other): try: return ( self.id == other.id and self.type == other.type and self.attributes == other.attributes and self.namespace == other.namespace # and self.nsmap == other.nsmap ) except AttributeError: return False def get_attribute(self, key, default=None, inherit=False, namespace=None): if key is None: raise ValueError( 'Attribute key must be of type str, not ' + key.__class__.__name__ ) if not key.startswith('{') and ':' in key: prefix, suffix = key.split(':', 1) key = '{%s}%s' % (self.nsmap[prefix], suffix) elif namespace in self.nsmap: key = '{%s}%s' % (self.nsmap[namespace], key) elif namespace: key = '{%s}%s' % (namespace, key) try: return self.attributes[key] except KeyError: if inherit and _has_parent(self): return self._parent.get_attribute( key, default, inherit, namespace=namespace ) else: return default @property def id(self): return self._id @id.setter def id(self, value): if value is not None and not id_re.match(value): raise ValueError('Invalid ID: {}'.format(value)) self._id = value @property def nsmap(self): if self._nsmap is None: if _has_parent(self): return self._parent.nsmap else: return {} else: return self._nsmap @nsmap.setter def nsmap(self, value): if value is not None: value = dict(value or []) self._nsmap = value # no validation for type yet, so the property isn't necessary # @property # def type(self): # return self._type # @type.setter # def type(self, value): # self._type = value class XigtReferenceAttributeMixin(object): def __init__(self, alignment=None, content=None, segmentation=None): if segmentation and (content or alignment): raise XigtError( 'The "segmentation" reference attribute cannot co-occur with ' 'the "content" or "alignment" reference attributes.' ) if alignment is not None: self.attributes[ALIGNMENT] = alignment if content is not None: self.attributes[CONTENT] = content if segmentation is not None: self.attributes[SEGMENTATION] = segmentation def referents(self, refattrs=None): if not getattr(self, 'igt'): raise XigtError('Cannot retrieve referents; unspecified IGT.') if not getattr(self, 'id'): raise XigtError('Cannot retrieve referents; unspecified id.') return self.igt.referents(self.id, refattrs=refattrs) def referrers(self, refattrs=None): if not getattr(self, 'igt'): raise XigtError('Cannot retrieve referrers; unspecified IGT.') if not getattr(self, 'id'): raise XigtError('Cannot retrieve referrers; unspecified id.') return self.igt.referrers(self.id, refattrs=refattrs) @property def alignment(self): return self.attributes.get(ALIGNMENT) @alignment.setter def alignment(self, value): self.attributes[ALIGNMENT] = value @property def content(self): return self.attributes.get(CONTENT) @content.setter def content(self, value): self.attributes[CONTENT] = value @property def segmentation(self): return self.attributes.get(SEGMENTATION) @segmentation.setter def segmentation(self, value): self.attributes[SEGMENTATION] = value<|fim▁end|>
<|file_name|>variables_b.js<|end_file_name|><|fim▁begin|>var searchData= [<|fim▁hole|>];<|fim▁end|>
['neighbours',['neighbours',['../struct_parser_1_1_cell_atom_grammar.html#a6367dce3041506f4112c82e2ba5998a9',1,'Parser::CellAtomGrammar']]], ['newgrid',['newGrid',['../struct_compiler_1_1_state.html#a3a949d5132b7854fee15d6d13344652c',1,'Compiler::State']]]
<|file_name|>the_if.rs<|end_file_name|><|fim▁begin|>// // closure // see https://rustbyexample.com/fn/closures.html // fn _if<T, F1, F2>(cond: bool, mut then: F1, mut els: F2) -> T where F1: FnMut() -> T, F2: FnMut() -> T { if cond { then() } else { els() } } #[test] fn test() {<|fim▁hole|><|fim▁end|>
assert!(_if(true, || 1, || 2) == 1); }
<|file_name|>subprocess.py<|end_file_name|><|fim▁begin|># subprocess - Subprocesses with accessible I/O streams # # For more information about this module, see PEP 324. # # Copyright (c) 2003-2005 by Peter Astrand <[email protected]> # # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. r"""subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions: os.system os.spawn* Information about how the subprocess module can be used to replace these modules and functions can be found below. Using the subprocess module =========================== This module defines one class called Popen: class Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=()): Arguments are: args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or string, but can be explicitly set by using the executable argument. On POSIX, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. A string will be treated as a sequence with the string as the only item (the program to execute). On POSIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments. On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime. bufsize will be supplied as the corresponding argument to the io.open() function when creating the stdin/stdout/stderr pipe file objects: 0 means unbuffered (read & write are one system call and can return short), 1 means line buffered, any other positive value means use a buffer of approximately that size. A negative bufsize, the default, means the system default of io.DEFAULT_BUFFER_SIZE will be used. stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same<|fim▁hole|>On POSIX, if preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. The use of preexec_fn is not thread safe, using it in the presence of threads could lead to a deadlock in the child process before the new executable is executed. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. The default for close_fds varies by platform: Always true on POSIX. True when stdin/stdout/stderr are None on Windows, false otherwise. pass_fds is an optional sequence of file descriptors to keep open between the parent and child. Providing any pass_fds implicitly sets close_fds to true. if shell is true, the specified command will be executed through the shell. If cwd is not None, the current directory will be changed to cwd before the child is executed. On POSIX, if restore_signals is True all signals that Python sets to SIG_IGN are restored to SIG_DFL in the child process before the exec. Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. This parameter does nothing on Windows. On POSIX, if start_new_session is True, the setsid() system call will be made in the child process prior to executing the command. If env is not None, it defines the environment variables for the new process. If universal_newlines is false, the file objects stdin, stdout and stderr are opened as binary files, and no line ending conversion is done. If universal_newlines is true, the file objects stdout and stderr are opened as a text files, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the old Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method. The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only) This module also defines some shortcut functions: call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: >>> retcode = subprocess.call(["ls", "-l"]) check_call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: >>> subprocess.check_call(["ls", "-l"]) 0 getstatusoutput(cmd): Return (status, output) of executing cmd in a shell. Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). Universal newlines mode is used, meaning that the result with be decoded to a string. A trailing newline is stripped from the output. The exit status for the command can be interpreted according to the rules for the function 'wait'. Example: >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') (256, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (256, 'sh: /bin/junk: not found') getoutput(cmd): Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' check_output(*popenargs, **kwargs): Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> output = subprocess.check_output(["ls", "-l", "/dev/null"]) There is an additional optional argument, "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument. Exceptions ---------- Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called 'child_traceback', which is a string containing traceback information from the child's point of view. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors. A ValueError will be raised if Popen is called with invalid arguments. Exceptions defined within this module inherit from SubprocessError. check_call() and check_output() will raise CalledProcessError if the called process returns a non-zero return code. TimeoutExpired be raised if a timeout was specified and expired. Security -------- Unlike some other popen functions, this implementation will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Popen objects ============= Instances of the Popen class have the following methods: poll() Check if child process has terminated. Returns returncode attribute. wait() Wait for child process to terminate. Returns returncode attribute. communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. The following attributes are also available: stdin If the stdin argument is PIPE, this attribute is a file object that provides input to the child process. Otherwise, it is None. stdout If the stdout argument is PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None. stderr If the stderr argument is PIPE, this attribute is file object that provides error output from the child process. Otherwise, it is None. pid The process ID of the child process. returncode The child return code. A None value indicates that the process hasn't terminated yet. A negative value -N indicates that the child was terminated by signal N (POSIX only). Replacing older functions with the subprocess module ==================================================== In this section, "a ==> b" means that b can be used as a replacement for a. Note: All functions in this section fail (more or less) silently if the executed program cannot be found; this module raises an OSError exception. In the following examples, we assume that the subprocess module is imported with "from subprocess import *". Replacing /bin/sh shell backquote --------------------------------- output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] Replacing shell pipe line ------------------------- output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] Replacing os.system() --------------------- sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) pid, sts = os.waitpid(p.pid, 0) Note: * Calling the program through the shell is usually not required. * It's easier to look at the returncode attribute than the exitstatus. A more real-world example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print("Child was terminated by signal", -retcode, file=sys.stderr) else: print("Child returned", retcode, file=sys.stderr) except OSError as e: print("Execution failed:", e, file=sys.stderr) Replacing os.spawn* ------------------- P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid P_WAIT example: retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) """ import os import sys mswindows = (sys.platform == "win32") or (sys.platform == "cli" and os.name == "nt") import io import time import signal import builtins import warnings import errno try: from time import monotonic as _time except ImportError: from time import time as _time # Exception classes used by this module. class SubprocessError(Exception): pass class CalledProcessError(SubprocessError): """This exception is raised when a process run by check_call() or check_output() returns a non-zero exit status. The exit status will be stored in the returncode attribute; check_output() will also store the output in the output attribute. """ def __init__(self, returncode, cmd, output=None): self.returncode = returncode self.cmd = cmd self.output = output def __str__(self): return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) class TimeoutExpired(SubprocessError): """This exception is raised when the timeout expires while waiting for a child process. """ def __init__(self, cmd, timeout, output=None): self.cmd = cmd self.timeout = timeout self.output = output def __str__(self): return ("Command '%s' timed out after %s seconds" % (self.cmd, self.timeout)) if mswindows: import threading import msvcrt import _winapi class STARTUPINFO: dwFlags = 0 hStdInput = None hStdOutput = None hStdError = None wShowWindow = 0 else: import _posixsubprocess import select import selectors try: import threading except ImportError: import dummy_threading as threading # When select or poll has indicated that the file is writable, # we can write up to _PIPE_BUF bytes without risk of blocking. # POSIX defines PIPE_BUF as >= 512. _PIPE_BUF = getattr(select, 'PIPE_BUF', 512) # poll/select have the advantage of not requiring any extra file # descriptor, contrarily to epoll/kqueue (also, they require a single # syscall). if hasattr(selectors, 'PollSelector'): _PopenSelector = selectors.PollSelector else: _PopenSelector = selectors.SelectSelector __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput", "getoutput", "check_output", "CalledProcessError", "DEVNULL"] if mswindows: from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE, SW_HIDE, STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW) __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP", "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE", "STD_ERROR_HANDLE", "SW_HIDE", "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"]) class Handle(int): closed = False def Close(self, CloseHandle=_winapi.CloseHandle): if not self.closed: self.closed = True CloseHandle(self) def Detach(self): if not self.closed: self.closed = True return int(self) raise ValueError("already closed") def __repr__(self): return "Handle(%d)" % int(self) __del__ = Close __str__ = __repr__ try: MAXFD = os.sysconf("SC_OPEN_MAX") except: MAXFD = 256 # This lists holds Popen instances for which the underlying process had not # exited at the time its __del__ method got called: those processes are wait()ed # for synchronously from _cleanup() when a new Popen object is created, to avoid # zombie processes. _active = [] def _cleanup(): for inst in _active[:]: res = inst._internal_poll(_deadstate=sys.maxsize) if res is not None: try: _active.remove(inst) except ValueError: # This can happen if two threads create a new Popen instance. # It's harmless that it was already removed, so ignore. pass PIPE = -1 STDOUT = -2 DEVNULL = -3 def _eintr_retry_call(func, *args): while True: try: return func(*args) except InterruptedError: continue # XXX This function is only used by multiprocessing and the test suite, # but it's here so that it can be imported when Python is compiled without # threads. def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args def call(*popenargs, timeout=None, **kwargs): """Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ with Popen(*popenargs, **kwargs) as p: try: return p.wait(timeout=timeout) except: p.kill() p.wait() raise def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the call function. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0 def check_output(*popenargs, timeout=None, **kwargs): r"""Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) b'ls: non_existent_file: No such file or directory\n' There is an additional optional argument, "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it too will be used internally. Example: >>> check_output(["sed", "-e", "s/foo/bar/"], ... input=b"when in the course of fooman events\n") b'when in the course of barman events\n' If universal_newlines=True is passed, the return value will be a string rather than bytes. """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') if 'input' in kwargs: if 'stdin' in kwargs: raise ValueError('stdin and input arguments may not both be used.') inputdata = kwargs['input'] del kwargs['input'] kwargs['stdin'] = PIPE else: inputdata = None with Popen(*popenargs, stdout=PIPE, **kwargs) as process: try: output, unused_err = process.communicate(inputdata, timeout=timeout) except TimeoutExpired: process.kill() output, unused_err = process.communicate() raise TimeoutExpired(process.args, timeout, output=output) except: process.kill() process.wait() raise retcode = process.poll() if retcode: raise CalledProcessError(retcode, process.args, output=output) return output def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. """ # See # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx # or search http://msdn.microsoft.com for # "Parsing C++ Command-Line Arguments" result = [] needquote = False for arg in seq: bs_buf = [] # Add a space to separate this argument from the others if result: result.append(' ') needquote = (" " in arg) or ("\t" in arg) or not arg if needquote: result.append('"') for c in arg: if c == '\\': # Don't know if we need to double yet. bs_buf.append(c) elif c == '"': # Double backslashes. result.append('\\' * len(bs_buf)*2) bs_buf = [] result.append('\\"') else: # Normal char if bs_buf: result.extend(bs_buf) bs_buf = [] result.append(c) # Add remaining backslashes, if any. if bs_buf: result.extend(bs_buf) if needquote: result.extend(bs_buf) result.append('"') return ''.join(result) # Various tools for executing commands and looking at their output and status. # def getstatusoutput(cmd): """ Return (status, output) of executing cmd in a shell. Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). Universal newlines mode is used, meaning that the result with be decoded to a string. A trailing newline is stripped from the output. The exit status for the command can be interpreted according to the rules for the function 'wait'. Example: >>> import subprocess >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') (256, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (256, 'sh: /bin/junk: not found') """ try: data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT) status = 0 except CalledProcessError as ex: data = ex.output status = ex.returncode if data[-1:] == '\n': data = data[:-1] return status, data def getoutput(cmd): """Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: >>> import subprocess >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' """ return getstatusoutput(cmd)[1] _PLATFORM_DEFAULT_CLOSE_FDS = object() class Popen(object): _child_created = False # Set here since __del__ checks it def __init__(self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=()): """Create new Popen instance.""" _cleanup() # Held while anything is calling waitpid before returncode has been # updated to prevent clobbering returncode if wait() or poll() are # called from multiple threads at once. After acquiring the lock, # code must re-check self.returncode to see if another thread just # finished a waitpid() call. self._waitpid_lock = threading.Lock() self._input = None self._communication_started = False if bufsize is None: bufsize = -1 # Restore default if not isinstance(bufsize, int): raise TypeError("bufsize must be an integer") if mswindows: if preexec_fn is not None: raise ValueError("preexec_fn is not supported on Windows " "platforms") any_stdio_set = (stdin is not None or stdout is not None or stderr is not None) if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: if any_stdio_set: close_fds = False else: close_fds = True elif close_fds and any_stdio_set: raise ValueError( "close_fds is not supported on Windows platforms" " if you redirect stdin/stdout/stderr") else: # POSIX if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: close_fds = True if pass_fds and not close_fds: warnings.warn("pass_fds overriding close_fds.", RuntimeWarning) close_fds = True if startupinfo is not None: raise ValueError("startupinfo is only supported on Windows " "platforms") if creationflags != 0: raise ValueError("creationflags is only supported on Windows " "platforms") self.args = args self.stdin = None self.stdout = None self.stderr = None self.pid = None self.returncode = None self.universal_newlines = universal_newlines # Input and output objects. The general principle is like # this: # # Parent Child # ------ ----- # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite # # On POSIX, the child objects are file descriptors. On # Windows, these are Windows file handles. The parent objects # are file descriptors on both platforms. The parent objects # are -1 when not using PIPEs. The child objects are -1 # when not redirecting. (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) # We wrap OS handles *before* launching the child, otherwise a # quickly terminating child could make our fds unwrappable # (see #8458). if mswindows: if p2cwrite != -1: p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) if c2pread != -1: c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) if errread != -1: errread = msvcrt.open_osfhandle(errread.Detach(), 0) if p2cwrite != -1: self.stdin = io.open(p2cwrite, 'wb', bufsize) if universal_newlines: self.stdin = io.TextIOWrapper(self.stdin, write_through=True, line_buffering=(bufsize == 1)) if c2pread != -1: self.stdout = io.open(c2pread, 'rb', bufsize) if universal_newlines: self.stdout = io.TextIOWrapper(self.stdout) if errread != -1: self.stderr = io.open(errread, 'rb', bufsize) if universal_newlines: self.stderr = io.TextIOWrapper(self.stderr) self._closed_child_pipe_fds = False try: self._execute_child(args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session) except: # Cleanup if the child failed starting. for f in filter(None, (self.stdin, self.stdout, self.stderr)): try: f.close() except OSError: pass # Ignore EBADF or other errors. if not self._closed_child_pipe_fds: to_close = [] if stdin == PIPE: to_close.append(p2cread) if stdout == PIPE: to_close.append(c2pwrite) if stderr == PIPE: to_close.append(errwrite) if hasattr(self, '_devnull'): to_close.append(self._devnull) for fd in to_close: try: os.close(fd) except OSError: pass raise def _translate_newlines(self, data, encoding): data = data.decode(encoding) return data.replace("\r\n", "\n").replace("\r", "\n") def __enter__(self): return self def __exit__(self, type, value, traceback): if self.stdout: self.stdout.close() if self.stderr: self.stderr.close() try: # Flushing a BufferedWriter may raise an error if self.stdin: self.stdin.close() finally: # Wait for the process to terminate, to avoid zombies. self.wait() def __del__(self, _maxsize=sys.maxsize): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. self._internal_poll(_deadstate=_maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) def _get_devnull(self): if not hasattr(self, '_devnull'): self._devnull = os.open(os.devnull, os.O_RDWR) return self._devnull def communicate(self, input=None, timeout=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be bytes to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" if self._communication_started and input: raise ValueError("Cannot send input after starting communication") # Optimization: If we are not worried about timeouts, we haven't # started communicating, and we have one or zero pipes, using select() # or threads is unnecessary. if (timeout is None and not self._communication_started and [self.stdin, self.stdout, self.stderr].count(None) >= 2): stdout = None stderr = None if self.stdin: if input: try: self.stdin.write(input) except OSError as e: if e.errno != errno.EPIPE and e.errno != errno.EINVAL: raise self.stdin.close() elif self.stdout: stdout = _eintr_retry_call(self.stdout.read) self.stdout.close() elif self.stderr: stderr = _eintr_retry_call(self.stderr.read) self.stderr.close() self.wait() else: if timeout is not None: endtime = _time() + timeout else: endtime = None try: stdout, stderr = self._communicate(input, endtime, timeout) finally: self._communication_started = True sts = self.wait(timeout=self._remaining_time(endtime)) return (stdout, stderr) def poll(self): return self._internal_poll() def _remaining_time(self, endtime): """Convenience for _communicate when computing timeouts.""" if endtime is None: return None else: return endtime - _time() def _check_timeout(self, endtime, orig_timeout): """Convenience for checking if a timeout has expired.""" if endtime is None: return if _time() > endtime: raise TimeoutExpired(self.args, orig_timeout) if mswindows: # # Windows methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin is None and stdout is None and stderr is None: return (-1, -1, -1, -1, -1, -1) p2cread, p2cwrite = -1, -1 c2pread, c2pwrite = -1, -1 errread, errwrite = -1, -1 if stdin is None: p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE) if p2cread is None: p2cread, _ = _winapi.CreatePipe(None, 0) p2cread = Handle(p2cread) _winapi.CloseHandle(_) elif stdin == PIPE: p2cread, p2cwrite = _winapi.CreatePipe(None, 0) p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite) elif stdin == DEVNULL: p2cread = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stdin, int): p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) if stdout is None: c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE) if c2pwrite is None: _, c2pwrite = _winapi.CreatePipe(None, 0) c2pwrite = Handle(c2pwrite) _winapi.CloseHandle(_) elif stdout == PIPE: c2pread, c2pwrite = _winapi.CreatePipe(None, 0) c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite) elif stdout == DEVNULL: c2pwrite = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stdout, int): c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) if stderr is None: errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE) if errwrite is None: _, errwrite = _winapi.CreatePipe(None, 0) errwrite = Handle(errwrite) _winapi.CloseHandle(_) elif stderr == PIPE: errread, errwrite = _winapi.CreatePipe(None, 0) errread, errwrite = Handle(errread), Handle(errwrite) elif stderr == STDOUT: errwrite = c2pwrite elif stderr == DEVNULL: errwrite = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stderr, int): errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" h = _winapi.DuplicateHandle( _winapi.GetCurrentProcess(), handle, _winapi.GetCurrentProcess(), 0, 1, _winapi.DUPLICATE_SAME_ACCESS) return Handle(h) def _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session): """Execute program (MS Windows version)""" assert not pass_fds, "pass_fds not supported on Windows." if not isinstance(args, str): args = list2cmdline(args) # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() if -1 not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW startupinfo.wShowWindow = _winapi.SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = '{} /c "{}"'.format (comspec, args) # Start the process try: hp, ht, pid, tid = _winapi.CreateProcess(executable, args, # no special security None, None, int(not close_fds), creationflags, env, cwd, startupinfo) finally: # Child is launched. Close the parent's copy of those pipe # handles that only the child should have open. You need # to make sure that no handles to the write end of the # output pipe are maintained in this process or else the # pipe will not close when the child process exits and the # ReadFile will hang. if p2cread != -1: p2cread.Close() if c2pwrite != -1: c2pwrite.Close() if errwrite != -1: errwrite.Close() if hasattr(self, '_devnull'): os.close(self._devnull) # Retain the process handle, but close the thread handle self._child_created = True self._handle = Handle(hp) self.pid = pid _winapi.CloseHandle(ht) def _internal_poll(self, _deadstate=None, _WaitForSingleObject=_winapi.WaitForSingleObject, _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0, _GetExitCodeProcess=_winapi.GetExitCodeProcess): """Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it can only refer to objects in its local scope. """ if self.returncode is None: if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: self.returncode = _GetExitCodeProcess(self._handle) return self.returncode def wait(self, timeout=None, endtime=None): """Wait for child process to terminate. Returns returncode attribute.""" if endtime is not None: timeout = self._remaining_time(endtime) if timeout is None: timeout_millis = _winapi.INFINITE else: timeout_millis = int(timeout * 1000) if self.returncode is None: result = _winapi.WaitForSingleObject(self._handle, timeout_millis) if result == _winapi.WAIT_TIMEOUT: raise TimeoutExpired(self.args, timeout) self.returncode = _winapi.GetExitCodeProcess(self._handle) return self.returncode def _readerthread(self, fh, buffer): buffer.append(fh.read()) fh.close() def _communicate(self, input, endtime, orig_timeout): # Start reader threads feeding into a list hanging off of this # object, unless they've already been started. if self.stdout and not hasattr(self, "_stdout_buff"): self._stdout_buff = [] self.stdout_thread = \ threading.Thread(target=self._readerthread, args=(self.stdout, self._stdout_buff)) self.stdout_thread.daemon = True self.stdout_thread.start() if self.stderr and not hasattr(self, "_stderr_buff"): self._stderr_buff = [] self.stderr_thread = \ threading.Thread(target=self._readerthread, args=(self.stderr, self._stderr_buff)) self.stderr_thread.daemon = True self.stderr_thread.start() if self.stdin: if input is not None: try: self.stdin.write(input) except OSError as e: if e.errno == errno.EPIPE: # communicate() should ignore pipe full error pass elif (e.errno == errno.EINVAL and self.poll() is not None): # Issue #19612: stdin.write() fails with EINVAL # if the process already exited before the write pass else: raise self.stdin.close() # Wait for the reader threads, or time out. If we time out, the # threads remain reading and the fds left open in case the user # calls communicate again. if self.stdout is not None: self.stdout_thread.join(self._remaining_time(endtime)) if self.stdout_thread.is_alive(): raise TimeoutExpired(self.args, orig_timeout) if self.stderr is not None: self.stderr_thread.join(self._remaining_time(endtime)) if self.stderr_thread.is_alive(): raise TimeoutExpired(self.args, orig_timeout) # Collect the output from and close both pipes, now that we know # both have been read successfully. stdout = None stderr = None if self.stdout: stdout = self._stdout_buff self.stdout.close() if self.stderr: stderr = self._stderr_buff self.stderr.close() # All data exchanged. Translate lists into strings. if stdout is not None: stdout = stdout[0] if stderr is not None: stderr = stderr[0] return (stdout, stderr) def send_signal(self, sig): """Send a signal to the process.""" # Don't signal a process that we know has already died. if self.returncode is not None: return if sig == signal.SIGTERM: self.terminate() elif sig == signal.CTRL_C_EVENT: os.kill(self.pid, signal.CTRL_C_EVENT) elif sig == signal.CTRL_BREAK_EVENT: os.kill(self.pid, signal.CTRL_BREAK_EVENT) else: raise ValueError("Unsupported signal: {}".format(sig)) def terminate(self): """Terminates the process.""" # Don't terminate a process that we know has already died. if self.returncode is not None: return try: _winapi.TerminateProcess(self._handle, 1) except PermissionError: # ERROR_ACCESS_DENIED (winerror 5) is received when the # process already died. rc = _winapi.GetExitCodeProcess(self._handle) if rc == _winapi.STILL_ACTIVE: raise self.returncode = rc kill = terminate else: # # POSIX methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = -1, -1 c2pread, c2pwrite = -1, -1 errread, errwrite = -1, -1 if stdin is None: pass elif stdin == PIPE: p2cread, p2cwrite = os.pipe() elif stdin == DEVNULL: p2cread = self._get_devnull() elif isinstance(stdin, int): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == PIPE: c2pread, c2pwrite = os.pipe() elif stdout == DEVNULL: c2pwrite = self._get_devnull() elif isinstance(stdout, int): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == PIPE: errread, errwrite = os.pipe() elif stderr == STDOUT: errwrite = c2pwrite elif stderr == DEVNULL: errwrite = self._get_devnull() elif isinstance(stderr, int): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _close_fds(self, fds_to_keep): start_fd = 3 for fd in sorted(fds_to_keep): if fd >= start_fd: os.closerange(start_fd, fd) start_fd = fd + 1 if start_fd <= MAXFD: os.closerange(start_fd, MAXFD) def _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session): """Execute program (POSIX version)""" if isinstance(args, (str, bytes)): args = [args] else: args = list(args) if shell: args = ["/bin/sh", "-c"] + args if executable: args[0] = executable if executable is None: executable = args[0] orig_executable = executable # For transferring possible exec failure from child to parent. # Data format: "exception name:hex errno:description" # Pickle is not used; it is complex and involves memory allocation. errpipe_read, errpipe_write = os.pipe() # errpipe_write must not be in the standard io 0, 1, or 2 fd range. low_fds_to_close = [] while errpipe_write < 3: low_fds_to_close.append(errpipe_write) errpipe_write = os.dup(errpipe_write) for low_fd in low_fds_to_close: os.close(low_fd) try: try: # We must avoid complex work that could involve # malloc or free in the child process to avoid # potential deadlocks, thus we do all this here. # and pass it to fork_exec() if env is not None: env_list = [os.fsencode(k) + b'=' + os.fsencode(v) for k, v in env.items()] else: env_list = None # Use execv instead of execve. executable = os.fsencode(executable) if os.path.dirname(executable): executable_list = (executable,) else: # This matches the behavior of os._execvpe(). executable_list = tuple( os.path.join(os.fsencode(dir), executable) for dir in os.get_exec_path(env)) fds_to_keep = set(pass_fds) fds_to_keep.add(errpipe_write) self.pid = _posixsubprocess.fork_exec( args, executable_list, close_fds, sorted(fds_to_keep), cwd, env_list, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, errpipe_read, errpipe_write, restore_signals, start_new_session, preexec_fn) self._child_created = True finally: # be sure the FD is closed no matter what os.close(errpipe_write) # self._devnull is not always defined. devnull_fd = getattr(self, '_devnull', None) if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd: os.close(p2cread) if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd: os.close(c2pwrite) if errwrite != -1 and errread != -1 and errwrite != devnull_fd: os.close(errwrite) if devnull_fd is not None: os.close(devnull_fd) # Prevent a double close of these fds from __init__ on error. self._closed_child_pipe_fds = True # Wait for exec to fail or succeed; possibly raising an # exception (limited in size) errpipe_data = bytearray() while True: part = _eintr_retry_call(os.read, errpipe_read, 50000) errpipe_data += part if not part or len(errpipe_data) > 50000: break finally: # be sure the FD is closed no matter what os.close(errpipe_read) if errpipe_data: try: _eintr_retry_call(os.waitpid, self.pid, 0) except OSError as e: if e.errno != errno.ECHILD: raise try: exception_name, hex_errno, err_msg = ( errpipe_data.split(b':', 2)) except ValueError: exception_name = b'SubprocessError' hex_errno = b'0' err_msg = (b'Bad exception data from child: ' + repr(errpipe_data)) child_exception_type = getattr( builtins, exception_name.decode('ascii'), SubprocessError) err_msg = err_msg.decode(errors="surrogatepass") if issubclass(child_exception_type, OSError) and hex_errno: errno_num = int(hex_errno, 16) child_exec_never_called = (err_msg == "noexec") if child_exec_never_called: err_msg = "" if errno_num != 0: err_msg = os.strerror(errno_num) if errno_num == errno.ENOENT: if child_exec_never_called: # The error must be from chdir(cwd). err_msg += ': ' + repr(cwd) else: err_msg += ': ' + repr(orig_executable) raise child_exception_type(errno_num, err_msg) raise child_exception_type(err_msg) def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, _WEXITSTATUS=os.WEXITSTATUS): """All callers to this function MUST hold self._waitpid_lock.""" # This method is called (indirectly) by __del__, so it cannot # refer to anything outside of its local scope. if _WIFSIGNALED(sts): self.returncode = -_WTERMSIG(sts) elif _WIFEXITED(sts): self.returncode = _WEXITSTATUS(sts) else: # Should never happen raise SubprocessError("Unknown child exit status!") def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD): """Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it cannot reference anything outside of the local scope (nor can any methods it calls). """ if self.returncode is None: if not self._waitpid_lock.acquire(False): # Something else is busy calling waitpid. Don't allow two # at once. We know nothing yet. return None try: if self.returncode is not None: return self.returncode # Another thread waited. pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) except OSError as e: if _deadstate is not None: self.returncode = _deadstate elif e.errno == _ECHILD: # This happens if SIGCLD is set to be ignored or # waiting for child processes has otherwise been # disabled for our process. This child is dead, we # can't get the status. # http://bugs.python.org/issue15756 self.returncode = 0 finally: self._waitpid_lock.release() return self.returncode def _try_wait(self, wait_flags): """All callers to this function MUST hold self._waitpid_lock.""" try: (pid, sts) = _eintr_retry_call(os.waitpid, self.pid, wait_flags) except OSError as e: if e.errno != errno.ECHILD: raise # This happens if SIGCLD is set to be ignored or waiting # for child processes has otherwise been disabled for our # process. This child is dead, we can't get the status. pid = self.pid sts = 0 return (pid, sts) def wait(self, timeout=None, endtime=None): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is not None: return self.returncode # endtime is preferred to timeout. timeout is only used for # printing. if endtime is not None or timeout is not None: if endtime is None: endtime = _time() + timeout elif timeout is None: timeout = self._remaining_time(endtime) if endtime is not None: # Enter a busy loop if we have a timeout. This busy loop was # cribbed from Lib/threading.py in Thread.wait() at r71065. delay = 0.0005 # 500 us -> initial delay of 1 ms while True: if self._waitpid_lock.acquire(False): try: if self.returncode is not None: break # Another thread waited. (pid, sts) = self._try_wait(os.WNOHANG) assert pid == self.pid or pid == 0 if pid == self.pid: self._handle_exitstatus(sts) break finally: self._waitpid_lock.release() remaining = self._remaining_time(endtime) if remaining <= 0: raise TimeoutExpired(self.args, timeout) delay = min(delay * 2, remaining, .05) time.sleep(delay) else: while self.returncode is None: with self._waitpid_lock: if self.returncode is not None: break # Another thread waited. (pid, sts) = self._try_wait(0) # Check the pid and loop as waitpid has been known to # return 0 even without WNOHANG in odd situations. # http://bugs.python.org/issue14396. if pid == self.pid: self._handle_exitstatus(sts) return self.returncode def _communicate(self, input, endtime, orig_timeout): if self.stdin and not self._communication_started: # Flush stdio buffer. This might block, if the user has # been writing to .stdin in an uncontrolled fashion. self.stdin.flush() if not input: self.stdin.close() stdout = None stderr = None # Only create this mapping if we haven't already. if not self._communication_started: self._fileobj2output = {} if self.stdout: self._fileobj2output[self.stdout] = [] if self.stderr: self._fileobj2output[self.stderr] = [] if self.stdout: stdout = self._fileobj2output[self.stdout] if self.stderr: stderr = self._fileobj2output[self.stderr] self._save_input(input) if self._input: input_view = memoryview(self._input) with _PopenSelector() as selector: if self.stdin and input: selector.register(self.stdin, selectors.EVENT_WRITE) if self.stdout: selector.register(self.stdout, selectors.EVENT_READ) if self.stderr: selector.register(self.stderr, selectors.EVENT_READ) while selector.get_map(): timeout = self._remaining_time(endtime) if timeout is not None and timeout < 0: raise TimeoutExpired(self.args, orig_timeout) ready = selector.select(timeout) self._check_timeout(endtime, orig_timeout) # XXX Rewrite these to use non-blocking I/O on the file # objects; they are no longer using C stdio! for key, events in ready: if key.fileobj is self.stdin: chunk = input_view[self._input_offset : self._input_offset + _PIPE_BUF] try: self._input_offset += os.write(key.fd, chunk) except OSError as e: if e.errno == errno.EPIPE: selector.unregister(key.fileobj) key.fileobj.close() else: raise else: if self._input_offset >= len(self._input): selector.unregister(key.fileobj) key.fileobj.close() elif key.fileobj in (self.stdout, self.stderr): data = os.read(key.fd, 32768) if not data: selector.unregister(key.fileobj) key.fileobj.close() self._fileobj2output[key.fileobj].append(data) self.wait(timeout=self._remaining_time(endtime)) # All data exchanged. Translate lists into strings. if stdout is not None: stdout = b''.join(stdout) if stderr is not None: stderr = b''.join(stderr) # Translate newlines, if requested. # This also turns bytes into strings. if self.universal_newlines: if stdout is not None: stdout = self._translate_newlines(stdout, self.stdout.encoding) if stderr is not None: stderr = self._translate_newlines(stderr, self.stderr.encoding) return (stdout, stderr) def _save_input(self, input): # This method is called from the _communicate_with_*() methods # so that if we time out while communicating, we can continue # sending input if we retry. if self.stdin and self._input is None: self._input_offset = 0 self._input = input if self.universal_newlines and input is not None: self._input = self._input.encode(self.stdin.encoding) def send_signal(self, sig): """Send a signal to the process.""" # Skip signalling a process that we know has already died. if self.returncode is None: os.kill(self.pid, sig) def terminate(self): """Terminate the process with SIGTERM """ self.send_signal(signal.SIGTERM) def kill(self): """Kill the process with SIGKILL """ self.send_signal(signal.SIGKILL)<|fim▁end|>
file handle as for stdout.
<|file_name|>borrowck-struct-update-with-dtor.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // revisions: ast mir //[mir]compile-flags: -Z borrowck=mir // Issue 4691: Ensure that functional-struct-update can only copy, not // move, when the struct implements Drop. struct B; struct S { a: isize, b: B } impl Drop for S { fn drop(&mut self) { } } struct T { a: isize, mv: Box<isize> } impl Drop for T { fn drop(&mut self) { } } fn f(s0:S) { let _s2 = S{a: 2, ..s0}; //[ast]~^ error: cannot move out of type `S`, which implements the `Drop` trait //[mir]~^^ ERROR [E0509]<|fim▁hole|> let _s2 = T{a: 2, ..s0}; //[ast]~^ error: cannot move out of type `T`, which implements the `Drop` trait //[mir]~^^ ERROR [E0509] } fn main() { }<|fim▁end|>
} fn g(s0:T) {
<|file_name|>_nodeexception.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2017 IBM RESEARCH. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.<|fim▁hole|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """ Exception for errors raised while interpreting nodes. """ class NodeException(Exception): """Base class for errors raised while interpreting nodes.""" def __init__(self, *msg): """Set the error message.""" self.msg = ' '.join(msg) def __str__(self): """Return the message.""" return repr(self.msg)<|fim▁end|>
# You may obtain a copy of the License at
<|file_name|>ImcClientSocket.java<|end_file_name|><|fim▁begin|>package pt.lsts.imc; import java.io.IOException; import java.net.URI; import java.util.concurrent.Future; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;<|fim▁hole|>import org.eclipse.jetty.websocket.client.WebSocketClient; @WebSocket public class ImcClientSocket { protected Session remote; protected WebSocketClient client = new WebSocketClient(); @OnWebSocketConnect public void onConnect(Session remote) { this.remote = remote; } @OnWebSocketMessage public void onBinary(Session session, byte buff[], int offset, int length) { try { IMCMessage msg = ImcProxyServer.deserialize(buff, offset, length); onMessage(msg); } catch (Exception e) { e.printStackTrace(); } } public void onMessage(IMCMessage msg) { msg.dump(System.out); } public void sendMessage(IMCMessage msg) throws IOException { if (remote == null || !remote.isOpen()) throw new IOException("Error sending message: not connected"); remote.getRemote().sendBytes(ImcProxyServer.wrap(msg)); } public Future<Session> connect(URI server) throws Exception { client.start(); return client.connect(this, server, new ClientUpgradeRequest()); } public void close() throws Exception { client.stop(); } public static void main(String[] args) throws Exception { ImcClientSocket socket = new ImcClientSocket(); Future<Session> future = socket.connect(new URI("ws://localhost:9090")); System.out.printf("Connecting..."); future.get(); socket.sendMessage(new Temperature(10.67f)); socket.close(); } }<|fim▁end|>
import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>""" Django settings for testproject project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n$(okl9n*#au0%^wxgu$c#x(f%lby3v_j)wuti&6q-nx_35uj6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'testproject.urls' WSGI_APPLICATION = 'testproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' <|fim▁hole|>USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/'<|fim▁end|>
<|file_name|>actionTypes.js<|end_file_name|><|fim▁begin|><|fim▁hole|>export const CREATE_COURSE = 'CREATE_COURSE';<|fim▁end|>
<|file_name|>borrowck-pat-by-move-and-ref.rs<|end_file_name|><|fim▁begin|>// Test that `ref mut? @ pat_with_by_move_bindings` is prevented. fn main() { struct U; // Prevent promotion. fn u() -> U { U } fn f1(ref a @ b: U) {} //~^ ERROR cannot move out of value because it is borrowed //~| ERROR borrow of moved value fn f2(ref a @ (ref b @ mut c, ref d @ e): (U, U)) {} //~^ ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed //~| ERROR borrow of moved value //~| ERROR borrow of moved value fn f3(ref mut a @ [b, mut c]: [U; 2]) {} //~^ ERROR cannot move out of value because it is borrowed //~| ERROR borrow of partially moved value let ref a @ b = U; //~^ ERROR cannot move out of value because it is borrowed let ref a @ (ref b @ mut c, ref d @ e) = (U, U); //~^ ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed let ref mut a @ [b, mut c] = [U, U]; //~^ ERROR cannot move out of value because it is borrowed //~| ERROR borrow of partially moved value let ref a @ b = u(); //~^ ERROR cannot move out of value because it is borrowed //~| ERROR borrow of moved value let ref a @ (ref b @ mut c, ref d @ e) = (u(), u()); //~^ ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed //~| ERROR borrow of moved value //~| ERROR borrow of moved value let ref mut a @ [b, mut c] = [u(), u()]; //~^ ERROR cannot move out of value because it is borrowed //~| ERROR borrow of partially moved value match Some(U) { ref a @ Some(b) => {} //~^ ERROR cannot move out of value because it is borrowed None => {} } match Some((U, U)) { ref a @ Some((ref b @ mut c, ref d @ e)) => {} //~^ ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed None => {} } match Some([U, U]) { ref mut a @ Some([b, mut c]) => {} //~^ ERROR cannot move out of value because it is borrowed None => {} } match Some(u()) { ref a @ Some(b) => {} //~^ ERROR cannot move out of value because it is borrowed None => {} } match Some((u(), u())) { ref a @ Some((ref b @ mut c, ref d @ e)) => {}<|fim▁hole|> //~| ERROR cannot move out of value because it is borrowed //~| ERROR cannot move out of value because it is borrowed //~| ERROR borrow of moved value //~| ERROR borrow of moved value None => {} } match Some([u(), u()]) { ref mut a @ Some([b, mut c]) => {} //~^ ERROR cannot move out of value because it is borrowed None => {} } }<|fim▁end|>
//~^ ERROR cannot move out of value because it is borrowed
<|file_name|>issue-10806.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast pub fn foo() -> int { 3 } pub fn bar() -> int { 4 } pub mod baz { use {foo, bar}; pub fn quux() -> int { foo() + bar() } } pub mod grault { use {foo}; pub fn garply() -> int { foo() } } pub mod waldo {<|fim▁hole|> pub fn plugh() -> int { 0 } } pub fn main() { let _x = baz::quux(); let _y = grault::garply(); let _z = waldo::plugh(); }<|fim▁end|>
use {};
<|file_name|>dbwrapper_tests.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "dbwrapper.h" #include "uint256.h" #include "random.h" #include "test/test_digibyte.h" #include <boost/assign/std/vector.hpp> // for 'operator+=()' #include <boost/assert.hpp> #include <boost/test/unit_test.hpp> // Test if a string consists entirely of null characters bool is_null_key(const std::vector<unsigned char>& key) { bool isnull = true; for (unsigned int i = 0; i < key.size(); i++) isnull &= (key[i] == '\x00'); return isnull; } BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(dbwrapper) { // Perform tests both obfuscated and non-obfuscated. for (int i = 0; i < 2; i++) { bool obfuscate = (bool)i; boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); char key = 'k'; uint256 in = GetRandHash(); uint256 res; // Ensure that we're doing real obfuscation when obfuscate=true BOOST_CHECK(obfuscate != is_null_key(dbwrapper_private::GetObfuscateKey(dbw))); BOOST_CHECK(dbw.Write(key, in)); BOOST_CHECK(dbw.Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); } } // Test batch operations BOOST_AUTO_TEST_CASE(dbwrapper_batch) { // Perform tests both obfuscated and non-obfuscated. for (int i = 0; i < 2; i++) { bool obfuscate = (bool)i; boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); char key = 'i'; uint256 in = GetRandHash(); char key2 = 'j'; uint256 in2 = GetRandHash(); char key3 = 'k'; uint256 in3 = GetRandHash(); uint256 res; CDBBatch batch(dbw); batch.Write(key, in); batch.Write(key2, in2); batch.Write(key3, in3); // Remove key3 before it's even been written batch.Erase(key3); dbw.WriteBatch(batch); BOOST_CHECK(dbw.Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); BOOST_CHECK(dbw.Read(key2, res)); BOOST_CHECK_EQUAL(res.ToString(), in2.ToString()); // key3 should've never been written BOOST_CHECK(dbw.Read(key3, res) == false); } } BOOST_AUTO_TEST_CASE(dbwrapper_iterator) { // Perform tests both obfuscated and non-obfuscated. for (int i = 0; i < 2; i++) { bool obfuscate = (bool)i; boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); // The two keys are intentionally chosen for ordering char key = 'j'; uint256 in = GetRandHash(); BOOST_CHECK(dbw.Write(key, in)); char key2 = 'k'; uint256 in2 = GetRandHash(); BOOST_CHECK(dbw.Write(key2, in2)); std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator()); // Be sure to seek past the obfuscation key (if it exists) it->Seek(key); char key_res; uint256 val_res; it->GetKey(key_res); it->GetValue(val_res); BOOST_CHECK_EQUAL(key_res, key); BOOST_CHECK_EQUAL(val_res.ToString(), in.ToString()); it->Next(); it->GetKey(key_res); it->GetValue(val_res); BOOST_CHECK_EQUAL(key_res, key2); BOOST_CHECK_EQUAL(val_res.ToString(), in2.ToString()); it->Next(); BOOST_CHECK_EQUAL(it->Valid(), false); } } // Test that we do not obfuscation if there is existing data. BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate) { // We're going to share this boost::filesystem::path between two wrappers boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); create_directories(ph); // Set up a non-obfuscated wrapper to write some initial data. CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false); char key = 'k'; uint256 in = GetRandHash(); uint256 res; BOOST_CHECK(dbw->Write(key, in)); BOOST_CHECK(dbw->Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); // Call the destructor to free leveldb LOCK delete dbw; // Now, set up another wrapper that wants to obfuscate the same directory CDBWrapper odbw(ph, (1 << 10), false, false, true); // Check that the key/val we wrote with unobfuscated wrapper exists and // is readable. uint256 res2; BOOST_CHECK(odbw.Read(key, res2)); BOOST_CHECK_EQUAL(res2.ToString(), in.ToString()); BOOST_CHECK(!odbw.IsEmpty()); // There should be existing data BOOST_CHECK(is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); // The key should be an empty string uint256 in2 = GetRandHash(); uint256 res3; // Check that we can write successfully BOOST_CHECK(odbw.Write(key, in2)); BOOST_CHECK(odbw.Read(key, res3)); BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString()); } // Ensure that we start obfuscating during a reindex. BOOST_AUTO_TEST_CASE(existing_data_reindex) { // We're going to share this boost::filesystem::path between two wrappers boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); create_directories(ph); // Set up a non-obfuscated wrapper to write some initial data. CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false); char key = 'k'; uint256 in = GetRandHash(); uint256 res; BOOST_CHECK(dbw->Write(key, in)); BOOST_CHECK(dbw->Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString());<|fim▁hole|> // Simulate a -reindex by wiping the existing data store CDBWrapper odbw(ph, (1 << 10), false, true, true); // Check that the key/val we wrote with unobfuscated wrapper doesn't exist uint256 res2; BOOST_CHECK(!odbw.Read(key, res2)); BOOST_CHECK(!is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); uint256 in2 = GetRandHash(); uint256 res3; // Check that we can write successfully BOOST_CHECK(odbw.Write(key, in2)); BOOST_CHECK(odbw.Read(key, res3)); BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString()); } BOOST_AUTO_TEST_CASE(iterator_ordering) { boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); CDBWrapper dbw(ph, (1 << 20), true, false, false); for (int x=0x00; x<256; ++x) { uint8_t key = x; uint32_t value = x*x; BOOST_CHECK(dbw.Write(key, value)); } std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator()); for (int c=0; c<2; ++c) { int seek_start; if (c == 0) seek_start = 0x00; else seek_start = 0x80; it->Seek((uint8_t)seek_start); for (int x=seek_start; x<256; ++x) { uint8_t key; uint32_t value; BOOST_CHECK(it->Valid()); if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure break; BOOST_CHECK(it->GetKey(key)); BOOST_CHECK(it->GetValue(value)); BOOST_CHECK_EQUAL(key, x); BOOST_CHECK_EQUAL(value, x*x); it->Next(); } BOOST_CHECK(!it->Valid()); } } struct StringContentsSerializer { // Used to make two serialized objects the same while letting them have a different lengths // This is a terrible idea std::string str; StringContentsSerializer() {} StringContentsSerializer(const std::string& inp) : str(inp) {} StringContentsSerializer& operator+=(const std::string& s) { str += s; return *this; } StringContentsSerializer& operator+=(const StringContentsSerializer& s) { return *this += s.str; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { if (ser_action.ForRead()) { str.clear(); char c = 0; while (true) { try { READWRITE(c); str.push_back(c); } catch (const std::ios_base::failure& e) { break; } } } else { for (size_t i = 0; i < str.size(); i++) READWRITE(str[i]); } } }; BOOST_AUTO_TEST_CASE(iterator_string_ordering) { char buf[10]; boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); CDBWrapper dbw(ph, (1 << 20), true, false, false); for (int x=0x00; x<10; ++x) { for (int y = 0; y < 10; y++) { sprintf(buf, "%d", x); StringContentsSerializer key(buf); for (int z = 0; z < y; z++) key += key; uint32_t value = x*x; BOOST_CHECK(dbw.Write(key, value)); } } std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator()); for (int c=0; c<2; ++c) { int seek_start; if (c == 0) seek_start = 0; else seek_start = 5; sprintf(buf, "%d", seek_start); StringContentsSerializer seek_key(buf); it->Seek(seek_key); for (int x=seek_start; x<10; ++x) { for (int y = 0; y < 10; y++) { sprintf(buf, "%d", x); std::string exp_key(buf); for (int z = 0; z < y; z++) exp_key += exp_key; StringContentsSerializer key; uint32_t value; BOOST_CHECK(it->Valid()); if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure break; BOOST_CHECK(it->GetKey(key)); BOOST_CHECK(it->GetValue(value)); BOOST_CHECK_EQUAL(key.str, exp_key); BOOST_CHECK_EQUAL(value, x*x); it->Next(); } } BOOST_CHECK(!it->Valid()); } } BOOST_AUTO_TEST_SUITE_END()<|fim▁end|>
// Call the destructor to free leveldb LOCK delete dbw;
<|file_name|>BasicTest.java<|end_file_name|><|fim▁begin|>/** * Copyright © 2013 enioka. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.enioka.jqm.api.test; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; import org.junit.Assert; import org.junit.Test; import com.enioka.jqm.api.JqmClientFactory; import com.enioka.jqm.api.Query; import com.enioka.jqm.api.Query.Sort; import com.enioka.jqm.api.State; import com.enioka.jqm.jdbc.Db; import com.enioka.jqm.jdbc.DbConn; import com.enioka.jqm.model.Instruction; import com.enioka.jqm.model.JobDef; import com.enioka.jqm.model.JobDef.PathType; import com.enioka.jqm.model.JobInstance; import com.enioka.jqm.model.Queue; /** * Simple tests for checking query syntax (no data) */ public class BasicTest { private static Logger jqmlogger = Logger.getLogger(BasicTest.class); @Test public void testChain() { // No exception allowed! JqmClientFactory.getClient().getQueues(); jqmlogger.info("q1"); JqmClientFactory.getClient().getQueues(); jqmlogger.info("q2"); } @Test public void testQuery() { Query q = new Query("toto", null); q.setInstanceApplication("marsu"); q.setInstanceKeyword2("pouet"); q.setInstanceModule("module"); q.setParentId(12); q.setJobInstanceId(132); q.setQueryLiveInstances(true); q.setJobDefKeyword2("pouet2"); JqmClientFactory.getClient().getJobs(q); } @Test public void testQueryDate() { Query q = new Query("toto", null); q.setInstanceApplication("marsu"); q.setInstanceKeyword2("pouet"); q.setInstanceModule("module"); q.setParentId(12); q.setJobInstanceId(132); q.setQueryLiveInstances(true); q.setEnqueuedBefore(Calendar.getInstance()); q.setEndedAfter(Calendar.getInstance()); q.setBeganRunningAfter(Calendar.getInstance()); q.setBeganRunningBefore(Calendar.getInstance()); q.setEnqueuedAfter(Calendar.getInstance()); q.setEnqueuedBefore(Calendar.getInstance()); q.setJobDefKeyword2("pouet2"); JqmClientFactory.getClient().getJobs(q); } @Test public void testQueryStatusOne() { Query q = new Query("toto", null); q.setQueryLiveInstances(true); q.setInstanceApplication("marsu"); q.addStatusFilter(State.CRASHED); JqmClientFactory.getClient().getJobs(q); } @Test public void testQueryStatusTwo() { Query q = new Query("toto", null); q.setQueryLiveInstances(true); q.setInstanceApplication("marsu"); q.addStatusFilter(State.CRASHED); q.addStatusFilter(State.HOLDED); JqmClientFactory.getClient().getJobs(q); } @Test public void testFluentQuery() { Query q = new Query("toto", null); q.setQueryLiveInstances(true); q.setInstanceApplication("marsu"); q.addStatusFilter(State.CRASHED); q.addStatusFilter(State.HOLDED); JqmClientFactory.getClient().getJobs(Query.create().addStatusFilter(State.RUNNING).setApplicationName("MARSU")); } @Test public void testQueryPercent() { JqmClientFactory.getClient().getJobs(Query.create().setApplicationName("%TEST")); } @Test public void testQueryNull() { JqmClientFactory.getClient().getJobs(new Query("", null)); } @Test public void testQueueNameId() { Query.create().setQueueName("test").run(); Query.create().setQueueId(12).run(); } @Test public void testPaginationWithFilter() { Query.create().setQueueName("test").setPageSize(10).run(); Query.create().setQueueId(12).setPageSize(10).run();<|fim▁hole|> public void testUsername() { Query.create().setUser("test").setPageSize(10).run(); } @Test public void testSortHistory() { Query.create().setUser("test").setPageSize(10).addSortAsc(Sort.APPLICATIONNAME).addSortDesc(Sort.DATEATTRIBUTION) .addSortAsc(Sort.DATEEND).addSortDesc(Sort.DATEENQUEUE).addSortAsc(Sort.ID).addSortDesc(Sort.QUEUENAME) .addSortAsc(Sort.STATUS).addSortDesc(Sort.USERNAME).addSortAsc(Sort.PARENTID).run(); } @Test public void testSortJi() { Query.create().setQueryHistoryInstances(false).setQueryLiveInstances(true).setUser("test").addSortAsc(Sort.APPLICATIONNAME) .addSortDesc(Sort.DATEATTRIBUTION).addSortDesc(Sort.DATEENQUEUE).addSortAsc(Sort.ID).addSortDesc(Sort.QUEUENAME) .addSortAsc(Sort.STATUS).addSortDesc(Sort.USERNAME).addSortAsc(Sort.PARENTID).run(); } @Test public void testOnlyQueue() { Query.create().setQueryLiveInstances(true).setQueryHistoryInstances(false).setUser("test").run(); } @Test public void testBug159() { Query.create().setJobInstanceId(1234).setQueryLiveInstances(true).setQueryHistoryInstances(false).setPageSize(15).setFirstRow(0) .run(); } @Test public void testBug292() { Query.create().addSortDesc(Query.Sort.ID).setQueueName("QBATCH").setQueryHistoryInstances(true).setQueryLiveInstances(true).run(); } @Test public void testBug305() { Properties p = new Properties(); p.putAll(Db.loadProperties()); Db db = new Db(p); DbConn cnx = null; try { cnx = db.getConn(); int qId = Queue.create(cnx, "q1", "q1 description", true); int jobDefdId = JobDef.create(cnx, "test description", "class", null, "jar", qId, 1, "appName", null, null, null, null, null, false, null, PathType.FS); JobInstance.enqueue(cnx, com.enioka.jqm.model.State.RUNNING, qId, jobDefdId, null, null, null, null, null, null, null, null, null, false, false, null, 1, Instruction.RUN, new HashMap<String, String>()); JobInstance.enqueue(cnx, com.enioka.jqm.model.State.RUNNING, qId, jobDefdId, null, null, null, null, null, null, null, null, null, false, false, null, 1, Instruction.RUN, new HashMap<String, String>()); cnx.commit(); Properties p2 = new Properties(); p2.put("com.enioka.jqm.jdbc.contextobject", db); List<com.enioka.jqm.api.JobInstance> res = JqmClientFactory.getClient("test", p2, false) .getJobs(Query.create().setQueryHistoryInstances(false).setQueryLiveInstances(true).addSortDesc(Query.Sort.ID) .setPageSize(1).setApplicationName("appName")); Assert.assertEquals(1, res.size()); } finally { if (cnx != null) { cnx.closeQuietly(cnx); } } } }<|fim▁end|>
} @Test
<|file_name|>plot_cluster_iris.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= K-means Clustering ========================================================= The plots display firstly what a K-means algorithm would yield using three clusters. It is then shown what the effect of a bad initialization is on the classification process: By setting n_init to only 1 (default is 10), the amount of times that the algorithm will be run with different centroid seeds is reduced. The next plot displays what using eight clusters would deliver and finally the ground truth. """ print(__doc__) # Code source: Gael Varoqueux # Modified for Documentation merge by Jaques Grobler # License: BSD import numpy as np import pylab as pl from mpl_toolkits.mplot3d import Axes3D from sklearn.cluster import KMeans from sklearn import datasets np.random.seed(5) centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data y = iris.target estimators = {'k_means_iris_3': KMeans(n_clusters=3), 'k_means_iris_8': KMeans(n_clusters=8), 'k_means_iris_bad_init': KMeans(n_clusters=3, n_init=1, init='random')} fignum = 1 for name, est in estimators.iteritems(): fig = pl.figure(fignum, figsize=(4, 3)) pl.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) pl.cla() est.fit(X) labels = est.labels_ ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float)) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') fignum = fignum + 1<|fim▁hole|>ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) pl.cla() for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X[y == label, 3].mean(), X[y == label, 0].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=y) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') pl.show()<|fim▁end|>
# Plot the ground truth fig = pl.figure(fignum, figsize=(4, 3)) pl.clf()
<|file_name|>item-handler.ts<|end_file_name|><|fim▁begin|>import { useCallback } from 'react'; import { IUploadItemProps, IUploadFileItem } from '../types'; import { useEventCallbackRef } from '../../utils/hooks/useEventCallbackRef'; <|fim▁hole|>export function useItemHandler<UPLOAD_ITEM extends IUploadFileItem>( props: IUploadItemProps<UPLOAD_ITEM> ) { const { item, onDelete, onRetry } = props; const onDeleteRef = useEventCallbackRef(onDelete); const onRetryRef = useEventCallbackRef(onRetry); const deleteHandler = useCallback<React.MouseEventHandler>( e => { e.stopPropagation(); onDeleteRef.current?.(item); }, [item, onDeleteRef] ); const retryHandler = useCallback<React.MouseEventHandler>( e => { e.stopPropagation(); onRetryRef.current?.(item); }, [item, onRetryRef] ); return { deleteHandler, retryHandler, }; }<|fim▁end|>
<|file_name|>i_before_e_except_after_c.rs<|end_file_name|><|fim▁begin|>// http://rosettacode.org/wiki/I_before_E_except_after_C #[cfg(not(test))] use std::fs::File; #[cfg(not(test))] use std::io::Read; #[cfg(not(test))] use std::path::Path; enum MatchState { Nothing, //Nothing of interest seen so far C, //Last seen a 'c' Ce, //Last seen a 'c' followed by an 'e' Ci, //Last seen a 'c' followed by an 'i' E, //Last seen an 'e' not preceded by a 'c' I //Last seen an 'i' not preceded by a 'c' } struct Occurrences { cie: u32, cei: u32, ie: u32, ei: u32 } fn count_occurrences(data: &str) -> Occurrences { //The counting process is implemented by a state machine. The state variable //tracks what pattern prefix was recognized so far (details at MatchState). //Each time a full pattern is matched the corresponding saw_* variable is set //to true to record its presence for the current word (They are not added //directly to result to ensure that words having multiple occurrences of one //pattern are only counted once.). //At each word boundary add to result what was recorded and clear all state //for next word. let mut result = Occurrences{cie: 0, cei: 0, ie: 0, ei: 0}; let mut saw_cie = false; let mut saw_cei = false; let mut saw_ie = false; let mut saw_ei = false; let mut state = MatchState::Nothing; for c in data.chars() { state = match (state, c.to_lowercase().next().unwrap()) { (_, '\n') | (_, '\r') => { if saw_cie {result.cie += 1; saw_cie = false;} if saw_cei {result.cei += 1; saw_cei = false;} if saw_ie {result.ie += 1; saw_ie = false;} if saw_ei {result.ei += 1; saw_ei = false;} MatchState::Nothing }, (_, 'c') => MatchState::C, (MatchState::C, 'i') => MatchState::Ci, (MatchState::Ce, 'i') => {saw_cei = true; MatchState::Nothing},<|fim▁hole|> (MatchState::C, 'e') => MatchState::Ce, (MatchState::Ci, 'e') => {saw_cie = true; MatchState::Nothing}, (MatchState::I, 'e') => {saw_ie = true; MatchState::Nothing}, (_, 'e') => MatchState::E, _ => MatchState::Nothing }; } result } #[cfg(not(test))] fn main () { let path = Path::new("src/resources/unixdict.txt"); let mut file = File::open(&path).unwrap(); let mut data = String::new(); file.read_to_string(&mut data).unwrap(); let occ = count_occurrences(&data); println!("I before E when not preceded by C is {} (ie: {}, cie: {})", if occ.ie > 2 * occ.cie {"plausible"} else {"implausible"}, occ.ie, occ.cie); println!("E before I when preceded by C is {} (cei: {}, ei: {})", if occ.cei > 2 * occ.ei {"plausible"} else {"implausible"}, occ.cei, occ.ei); } #[test] fn basic_test() { let occ1 = count_occurrences("ceiling\nclient\nleisure\n"); assert_eq!(occ1.cie, 0); assert_eq!(occ1.cei, 1); assert_eq!(occ1.ie, 1); assert_eq!(occ1.ei, 1); }<|fim▁end|>
(MatchState::E, 'i') => {saw_ei = true; MatchState::Nothing}, (_, 'i') => MatchState::I,
<|file_name|>SpecLoginRegisterCloudRequestPane.js<|end_file_name|><|fim▁begin|>require([ 'app/LoginRegisterCloudRequestPane', 'dojo/dom-construct', 'dojo/query' ], function( WidgetUnderTest, domConstruct, query ) { describe('app/LoginRegisterCloudRequestPane', function() { var widget; var destroy = function(widget) { widget.destroyRecursive(); widget = null; }; beforeEach(function() { widget = new WidgetUnderTest(null, domConstruct.create('div', null, document.body)); query( 'input[type="text"], input[type="password"], input[type="email"]', widget.domNode ).forEach(function(node) { node.value = 'anything'; }); }); afterEach(function() { if (widget) { destroy(widget); } }); describe('Sanity', function() { it('should create a LoginRegisterCloudRequestPane', function() { expect(widget).toEqual(jasmine.any(WidgetUnderTest)); }); }); describe('Password Restrictions', function() { it('should be 8 characters in length', function() { expect(widget.validate('aB1234$&').result).toEqual(true);<|fim▁hole|> expect(widget.validate('ab1234$&').result).toEqual(false); }); it('should have one lowercase letter', function() { expect(widget.validate('aB1234$&').result).toEqual(true); expect(widget.validate('AB1234$&').result).toEqual(false); }); it('should have one special character', function() { expect(widget.validate('aB1234$&').result).toEqual(true); expect(widget.validate('aB123456').result).toEqual(false); }); it('should have one number', function() { expect(widget.validate('aB1234$&').result).toEqual(true); expect(widget.validate('aB!@#$%^').result).toEqual(false); }); }); }); });<|fim▁end|>
expect(widget.validate('aB1&').result).toEqual(false); }); it('should have one uppercase letter', function() { expect(widget.validate('aB1234$&').result).toEqual(true);
<|file_name|>MaterialSplitPanelTest.java<|end_file_name|><|fim▁begin|>/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2017 GwtMaterialDesign * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gwt.material.design.addins.client.ui; import gwt.material.design.addins.client.ui.base.AddinsWidgetTestCase; import gwt.material.design.addins.client.splitpanel.MaterialSplitPanel; import gwt.material.design.addins.client.splitpanel.constants.Dock; import gwt.material.design.client.constants.Axis; import gwt.material.design.client.ui.MaterialPanel; /** * Test case for splitpanel component * * @author kevzlou7979 */ public class MaterialSplitPanelTest extends AddinsWidgetTestCase<MaterialSplitPanel> { @Override protected MaterialSplitPanel createWidget() { return new MaterialSplitPanel(); } <|fim▁hole|> MaterialSplitPanel splitPanel = getWidget(false); MaterialPanel leftPanel = new MaterialPanel(); MaterialPanel rightPanel = new MaterialPanel(); splitPanel.add(leftPanel); splitPanel.add(rightPanel); // when / then checkStructure(splitPanel, leftPanel, rightPanel); // Standard // given attachWidget(); // when / then checkStructure(splitPanel, leftPanel, rightPanel); } protected void checkStructure(MaterialSplitPanel splitPanel, MaterialPanel leftPanel, MaterialPanel rightPanel) { assertEquals(leftPanel, splitPanel.getWidget(0)); assertEquals(rightPanel, splitPanel.getWidget(1)); } public void testProperties() { // UiBinder // given MaterialSplitPanel splitPanel = getWidget(false); // when / then checkProperties(splitPanel); // Standard // given attachWidget(); // when / then checkProperties(splitPanel); } protected void checkProperties(MaterialSplitPanel splitPanel) { splitPanel.setBarPosition(20); assertEquals(0.2, splitPanel.getBarPosition()); splitPanel.setLeftMin(10); assertEquals(Double.valueOf(10), splitPanel.getLeftMin()); splitPanel.setLeftMax(40); assertEquals(Double.valueOf(40), splitPanel.getLeftMax()); splitPanel.setBottomMax(20); assertEquals(Double.valueOf(20), splitPanel.getBottomMax()); splitPanel.setBottomMin(30); assertEquals(Double.valueOf(30), splitPanel.getBottomMin()); splitPanel.setTopMax(20); assertEquals(Double.valueOf(20), splitPanel.getTopMax()); splitPanel.setTopMin(30); assertEquals(Double.valueOf(30), splitPanel.getTopMin()); splitPanel.setRightMax(20); assertEquals(Double.valueOf(20), splitPanel.getRightMax()); splitPanel.setRightMin(30); assertEquals(Double.valueOf(30), splitPanel.getRightMin()); splitPanel.setDock(Dock.RIGHT); assertEquals(Dock.RIGHT, splitPanel.getDock()); splitPanel.setDock(Dock.BOTTOM); assertEquals(Dock.BOTTOM, splitPanel.getDock()); splitPanel.setDock(Dock.LEFT); assertEquals(Dock.LEFT, splitPanel.getDock()); splitPanel.setDock(Dock.TOP); assertEquals(Dock.TOP, splitPanel.getDock()); splitPanel.setAxis(Axis.HORIZONTAL); assertEquals(Axis.HORIZONTAL, splitPanel.getAxis()); splitPanel.setAxis(Axis.VERTICAL); assertEquals(Axis.VERTICAL, splitPanel.getAxis()); splitPanel.setThickness(200); assertEquals(Double.valueOf(200), splitPanel.getThickness()); } }<|fim▁end|>
public void testStructure() { // UiBinder // given
<|file_name|>Resolver.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.valves.rewrite; import java.nio.charset.Charset; <|fim▁hole|> */ public abstract class Resolver { public abstract String resolve(String key); public String resolveEnv(String key) { return System.getProperty(key); } public abstract String resolveSsl(String key); public abstract String resolveHttp(String key); public abstract boolean resolveResource(int type, String name); /** * @return The name of the encoding to use to %nn encode URIs * * @deprecated This will be removed in Tomcat 9.0.x */ @Deprecated public abstract String getUriEncoding(); public abstract Charset getUriCharset(); }<|fim▁end|>
/** * Resolver abstract class.
<|file_name|>bitcoin_hi_IN.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="hi_IN" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Stepcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Stepcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Stepcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:[email protected]&quot;&gt;[email protected]&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>दो बार क्लिक करे पता या लेबल संपादन करने के लिए !</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>नया पता लिखिए !</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>These are your Stepcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a Stepcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified Stepcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;मिटाए !!</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>&amp;लेबल कॉपी करे </translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;एडिट</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation>एनक्रिप्ट वॉलेट !</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>वॉलेट खोलिए</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation> डीक्रिप्ट वॉलेट</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>पहचान शब्द/अक्षर बदलिये !</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>कृपा करके पुराना एवं नया पहचान शब्द/अक्षर वॉलेट में डालिए !</translation> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</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 COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>वॉलेट एनक्रिप्ट हो गया !</translation> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Stepcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>वॉलेट एनक्रिप्ट नही हुआ!</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>वॉलेट का लॉक नही खुला !</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation>वॉलेट का सामानया विवरण दिखाए !</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp; लेन-देन </translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>देखिए पुराने लेन-देन के विवरण !</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation>बाहर जायें</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>अप्लिकेशन से बाहर निकलना !</translation> </message> <message> <location line="+4"/> <source>Show information about Stepcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;विकल्प</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>&amp;बैकप वॉलेट</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-55"/> <source>Send coins to a Stepcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Modify configuration options for Stepcoin</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-214"/> <location line="+555"/> <source>Stepcoin</source> <translation type="unfinished"/> </message> <message> <location line="-555"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+193"/> <source>&amp;About Stepcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;File</source> <translation>&amp;फाइल</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;सेट्टिंग्स</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;मदद</translation> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation>टैबस टूलबार</translation> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation>[टेस्टनेट]</translation> </message> <message> <location line="+0"/> <location line="+58"/> <source>Stepcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to Stepcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-812"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+277"/> <source>Up to date</source> <translation>नवीनतम</translation> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>भेजी ट्रांजक्शन</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>प्राप्त हुई ट्रांजक्शन</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>तारीख: %1\n राशि: %2\n टाइप: %3\n पता:%4\n</translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Stepcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</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>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation><numerusform>%n घंटा</numerusform><numerusform>%n घंटे</numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation><numerusform>%n दिन</numerusform><numerusform>%n दिनो</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. Stepcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+537"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-500"/> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source><|fim▁hole|> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>पता एडिट करना</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;लेबल</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;पता</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 type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>नया स्वीकार्य पता</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>नया भेजने वाला पता</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>एडिट स्वीकार्य पता </translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>एडिट भेजने वाला पता</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>डाला गया पता &quot;%1&quot; एड्रेस बुक में पहले से ही मोजूद है|</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Stepcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>वॉलेट को unlock नहीं किया जा सकता|</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>नयी कुंजी का निर्माण असफल रहा|</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>Stepcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>विकल्प</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Stepcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Stepcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Stepcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Connect to the Stepcoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS5 proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Stepcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;ओके</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;कैन्सल</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+47"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+148"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Stepcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>फार्म</translation> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Stepcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;हाल का लेन-देन&lt;/b&gt;</translation> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start stepcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation>लागू नही </translation> </message> <message> <location line="-194"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Stepcoin-Qt help message to get a list with possible Stepcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-237"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Stepcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Stepcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Stepcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the Stepcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+127"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <location line="+35"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <location line="+47"/> <source>Confirm the send action</source> <translation>भेजने की पुष्टि करें</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-174"/> <source>Enter a Stepcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+87"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>सिक्के भेजने की पुष्टि करें</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+247"/> <source>WARNING: Invalid Stepcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>अमाउंट:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>प्राप्तकर्ता:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</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 type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Stepcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Stepcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Stepcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Stepcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Stepcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/अपुष्ट</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 पुष्टियाँ</translation> </message> <message> <location line="+17"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+13"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+19"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>सही</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>ग़लत</translation> </message> <message> <location line="-202"/> <source>, has not been successfully broadcast yet</source> <translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+67"/> <source>unknown</source> <translation>अज्ञात</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>लेन-देन का विवरण</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>पक्के ( %1 पक्का करना)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>स्वीकारा गया</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>स्वीकार्य ओर से</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>भेजा खुद को भुगतान</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(लागू नहीं)</translation> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>ट्रांसेक्शन का प्रकार|</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>ट्रांसेक्शन की मंजिल का पता|</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation>सभी</translation> </message> <message> <location line="-16"/> <source>Today</source> <translation>आज</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>इस हफ्ते</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>इस महीने</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>पिछले महीने</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>इस साल</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>विस्तार...</translation> </message> <message> <location line="+12"/> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>अपनेआप को</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>अन्य</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>लघुत्तम राशि</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>एडिट लेबल</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>विस्तार:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>तक</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+208"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+173"/> <source>Stepcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>खपत :</translation> </message> <message> <location line="+1"/> <source>Send command to -server or stepcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>commands की लिस्ट बनाएं</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>किसी command के लिए मदद लें</translation> </message> <message> <location line="-147"/> <source>Options:</source> <translation>विकल्प:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: stepcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: stepcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>डेटा डायरेक्टरी बताएं </translation> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=stepcoinrpc 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;Stepcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-36"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+63"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation>बैकग्राउंड में डेमॉन बन कर रन करे तथा कमांड्स स्वीकार करें </translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>टेस्ट नेटवर्क का इस्तेमाल करे </translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Stepcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+132"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-68"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-92"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-89"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+116"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+54"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-53"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-59"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect through SOCKS5 proxy</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Unsupported argument -socks found. Setting SOCKS version isn&apos;t possible anymore, only SOCKS5 proxies are supported.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Initialization sanity check failed. Stepcoin is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-174"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+105"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-131"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+127"/> <source>Loading addresses...</source> <translation>पता पुस्तक आ रही है...</translation> </message> <message> <location line="-10"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Stepcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Stepcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>राशि ग़लत है</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation>ब्लॉक इंडेक्स आ रहा है...</translation> </message> <message> <location line="-111"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+126"/> <source>Unable to bind to %s on this computer. Stepcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-102"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Keep at most &lt;n&gt; unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Stepcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Loading wallet...</source> <translation>वॉलेट आ रहा है...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>रि-स्केनी-इंग...</translation> </message> <message> <location line="+2"/> <source>Done loading</source> <translation>लोड हो गया|</translation> </message> <message> <location line="-161"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+188"/> <source>Error</source> <translation>भूल</translation> </message> <message> <location line="-18"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<|file_name|>greedy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) <|fim▁hole|><|fim▁end|>
return choosen_action
<|file_name|>IntegrationRuntimeState.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.synapse.v2019_06_01_preview; <|fim▁hole|>import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for IntegrationRuntimeState. */ public final class IntegrationRuntimeState extends ExpandableStringEnum<IntegrationRuntimeState> { /** Static value Initial for IntegrationRuntimeState. */ public static final IntegrationRuntimeState INITIAL = fromString("Initial"); /** Static value Stopped for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPED = fromString("Stopped"); /** Static value Started for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTED = fromString("Started"); /** Static value Starting for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTING = fromString("Starting"); /** Static value Stopping for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPING = fromString("Stopping"); /** Static value NeedRegistration for IntegrationRuntimeState. */ public static final IntegrationRuntimeState NEED_REGISTRATION = fromString("NeedRegistration"); /** Static value Online for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ONLINE = fromString("Online"); /** Static value Limited for IntegrationRuntimeState. */ public static final IntegrationRuntimeState LIMITED = fromString("Limited"); /** Static value Offline for IntegrationRuntimeState. */ public static final IntegrationRuntimeState OFFLINE = fromString("Offline"); /** Static value AccessDenied for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ACCESS_DENIED = fromString("AccessDenied"); /** * Creates or finds a IntegrationRuntimeState from its string representation. * @param name a name to look for * @return the corresponding IntegrationRuntimeState */ @JsonCreator public static IntegrationRuntimeState fromString(String name) { return fromString(name, IntegrationRuntimeState.class); } /** * @return known IntegrationRuntimeState values */ public static Collection<IntegrationRuntimeState> values() { return values(IntegrationRuntimeState.class); } }<|fim▁end|>
import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator;
<|file_name|>byte.py<|end_file_name|><|fim▁begin|>def hamming_distance(bytes1, bytes2): distance = 0 for b1, b2 in zip(bytes1, bytes2): xored = b1^b2 distance += sum(1 for n in range(8) if (xored >> n) & 0x01) <|fim▁hole|><|fim▁end|>
return distance
<|file_name|>res_config_settings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details.<|fim▁hole|>from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" google_drive_authorization_code = fields.Char(string='Authorization Code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help="The URL to generate the authorization code from Google") @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri = google_drive_uri @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() res.update( google_drive_authorization_code=self.env['ir.config_parameter'].sudo().get_param('google_drive_authorization_code'), ) return res def set_values(self): super(ResConfigSettings, self).set_values() params = self.env['ir.config_parameter'].sudo() authorization_code = self.google_drive_authorization_code refresh_token = False if authorization_code and authorization_code != params.get_param('google_drive_authorization_code'): refresh_token = self.env['google.service'].generate_refresh_token('drive', authorization_code) params.set_param('google_drive_authorization_code', authorization_code) params.set_param('google_drive_refresh_token', refresh_token)<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)<|fim▁hole|># Copyright (C) 2011-15 Agile Business Group sagl (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import print_calendar_report<|fim▁end|>
<|file_name|>exception.py<|end_file_name|><|fim▁begin|># Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2010, Eucalyptus Systems, Inc. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Exception classes - Subclassing allows you to check for specific errors """ import base64 import xml.sax <|fim▁hole|> from boto import handler from boto.compat import json, six, StandardError from boto.resultset import ResultSet class BotoClientError(StandardError): """ General Boto Client error (error accessing AWS) """ def __init__(self, reason, *args): super(BotoClientError, self).__init__(reason, *args) self.reason = reason def __repr__(self): return 'BotoClientError: %s' % self.reason def __str__(self): return 'BotoClientError: %s' % self.reason class SDBPersistenceError(StandardError): pass class StoragePermissionsError(BotoClientError): """ Permissions error when accessing a bucket or key on a storage service. """ pass class S3PermissionsError(StoragePermissionsError): """ Permissions error when accessing a bucket or key on S3. """ pass class GSPermissionsError(StoragePermissionsError): """ Permissions error when accessing a bucket or key on GS. """ pass class BotoServerError(StandardError): def __init__(self, status, reason, body=None, *args): super(BotoServerError, self).__init__(status, reason, body, *args) self.status = status self.reason = reason self.body = body or '' self.request_id = None self.error_code = None self._error_message = None self.message = '' self.box_usage = None if isinstance(self.body, bytes): try: self.body = self.body.decode('utf-8') except UnicodeDecodeError: boto.log.debug('Unable to decode body from bytes!') # Attempt to parse the error response. If body isn't present, # then just ignore the error response. if self.body: # Check if it looks like a ``dict``. if hasattr(self.body, 'items'): # It's not a string, so trying to parse it will fail. # But since it's data, we can work with that. self.request_id = self.body.get('RequestId', None) if 'Error' in self.body: # XML-style error = self.body.get('Error', {}) self.error_code = error.get('Code', None) self.message = error.get('Message', None) else: # JSON-style. self.message = self.body.get('message', None) else: try: h = handler.XmlHandlerWrapper(self, self) h.parseString(self.body) except (TypeError, xml.sax.SAXParseException) as pe: # What if it's JSON? Let's try that. try: parsed = json.loads(self.body) if 'RequestId' in parsed: self.request_id = parsed['RequestId'] if 'Error' in parsed: if 'Code' in parsed['Error']: self.error_code = parsed['Error']['Code'] if 'Message' in parsed['Error']: self.message = parsed['Error']['Message'] except (TypeError, ValueError): # Remove unparsable message body so we don't include garbage # in exception. But first, save self.body in self.error_message # because occasionally we get error messages from Eucalyptus # that are just text strings that we want to preserve. self.message = self.body self.body = None def __getattr__(self, name): if name == 'error_message': return self.message if name == 'code': return self.error_code raise AttributeError def __setattr__(self, name, value): if name == 'error_message': self.message = value else: super(BotoServerError, self).__setattr__(name, value) def __repr__(self): return '%s: %s %s\n%s' % (self.__class__.__name__, self.status, self.reason, self.body) def __str__(self): return '%s: %s %s\n%s' % (self.__class__.__name__, self.status, self.reason, self.body) def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connection): if name in ('RequestId', 'RequestID'): self.request_id = value elif name == 'Code': self.error_code = value elif name == 'Message': self.message = value elif name == 'BoxUsage': self.box_usage = value return None def _cleanupParsedProperties(self): self.request_id = None self.error_code = None self.message = None self.box_usage = None class ConsoleOutput(object): def __init__(self, parent=None): self.parent = parent self.instance_id = None self.timestamp = None self.comment = None self.output = None def startElement(self, name, attrs, connection): return None def endElement(self, name, value, connection): if name == 'instanceId': self.instance_id = value elif name == 'output': self.output = base64.b64decode(value) else: setattr(self, name, value) class StorageCreateError(BotoServerError): """ Error creating a bucket or key on a storage service. """ def __init__(self, status, reason, body=None): self.bucket = None super(StorageCreateError, self).__init__(status, reason, body) def endElement(self, name, value, connection): if name == 'BucketName': self.bucket = value else: return super(StorageCreateError, self).endElement(name, value, connection) class S3CreateError(StorageCreateError): """ Error creating a bucket or key on S3. """ pass class GSCreateError(StorageCreateError): """ Error creating a bucket or key on GS. """ pass class StorageCopyError(BotoServerError): """ Error copying a key on a storage service. """ pass class S3CopyError(StorageCopyError): """ Error copying a key on S3. """ pass class GSCopyError(StorageCopyError): """ Error copying a key on GS. """ pass class SQSError(BotoServerError): """ General Error on Simple Queue Service. """ def __init__(self, status, reason, body=None): self.detail = None self.type = None super(SQSError, self).__init__(status, reason, body) def startElement(self, name, attrs, connection): return super(SQSError, self).startElement(name, attrs, connection) def endElement(self, name, value, connection): if name == 'Detail': self.detail = value elif name == 'Type': self.type = value else: return super(SQSError, self).endElement(name, value, connection) def _cleanupParsedProperties(self): super(SQSError, self)._cleanupParsedProperties() for p in ('detail', 'type'): setattr(self, p, None) class SQSDecodeError(BotoClientError): """ Error when decoding an SQS message. """ def __init__(self, reason, message): super(SQSDecodeError, self).__init__(reason, message) self.message = message def __repr__(self): return 'SQSDecodeError: %s' % self.reason def __str__(self): return 'SQSDecodeError: %s' % self.reason class StorageResponseError(BotoServerError): """ Error in response from a storage service. """ def __init__(self, status, reason, body=None): self.resource = None super(StorageResponseError, self).__init__(status, reason, body) def startElement(self, name, attrs, connection): return super(StorageResponseError, self).startElement(name, attrs, connection) def endElement(self, name, value, connection): if name == 'Resource': self.resource = value else: return super(StorageResponseError, self).endElement(name, value, connection) def _cleanupParsedProperties(self): super(StorageResponseError, self)._cleanupParsedProperties() for p in ('resource'): setattr(self, p, None) class S3ResponseError(StorageResponseError): """ Error in response from S3. """ pass class GSResponseError(StorageResponseError): """ Error in response from GS. """ pass class EC2ResponseError(BotoServerError): """ Error in response from EC2. """ def __init__(self, status, reason, body=None): self.errors = None self._errorResultSet = [] super(EC2ResponseError, self).__init__(status, reason, body) self.errors = [ (e.error_code, e.error_message) \ for e in self._errorResultSet ] if len(self.errors): self.error_code, self.error_message = self.errors[0] def startElement(self, name, attrs, connection): if name == 'Errors': self._errorResultSet = ResultSet([('Error', _EC2Error)]) return self._errorResultSet else: return None def endElement(self, name, value, connection): if name == 'RequestID': self.request_id = value else: return None # don't call subclass here def _cleanupParsedProperties(self): super(EC2ResponseError, self)._cleanupParsedProperties() self._errorResultSet = [] for p in ('errors'): setattr(self, p, None) class JSONResponseError(BotoServerError): """ This exception expects the fully parsed and decoded JSON response body to be passed as the body parameter. :ivar status: The HTTP status code. :ivar reason: The HTTP reason message. :ivar body: The Python dict that represents the decoded JSON response body. :ivar error_message: The full description of the AWS error encountered. :ivar error_code: A short string that identifies the AWS error (e.g. ConditionalCheckFailedException) """ def __init__(self, status, reason, body=None, *args): self.status = status self.reason = reason self.body = body if self.body: self.error_message = self.body.get('message', None) self.error_code = self.body.get('__type', None) if self.error_code: self.error_code = self.error_code.split('#')[-1] class DynamoDBResponseError(JSONResponseError): pass class SWFResponseError(JSONResponseError): pass class EmrResponseError(BotoServerError): """ Error in response from EMR """ pass class _EC2Error(object): def __init__(self, connection=None): self.connection = connection self.error_code = None self.error_message = None def startElement(self, name, attrs, connection): return None def endElement(self, name, value, connection): if name == 'Code': self.error_code = value elif name == 'Message': self.error_message = value else: return None class SDBResponseError(BotoServerError): """ Error in responses from SDB. """ pass class AWSConnectionError(BotoClientError): """ General error connecting to Amazon Web Services. """ pass class StorageDataError(BotoClientError): """ Error receiving data from a storage service. """ pass class S3DataError(StorageDataError): """ Error receiving data from S3. """ pass class GSDataError(StorageDataError): """ Error receiving data from GS. """ pass class InvalidUriError(Exception): """Exception raised when URI is invalid.""" def __init__(self, message): super(InvalidUriError, self).__init__(message) self.message = message class InvalidAclError(Exception): """Exception raised when ACL XML is invalid.""" def __init__(self, message): super(InvalidAclError, self).__init__(message) self.message = message class InvalidCorsError(Exception): """Exception raised when CORS XML is invalid.""" def __init__(self, message): super(InvalidCorsError, self).__init__(message) self.message = message class NoAuthHandlerFound(Exception): """Is raised when no auth handlers were found ready to authenticate.""" pass class InvalidLifecycleConfigError(Exception): """Exception raised when GCS lifecycle configuration XML is invalid.""" def __init__(self, message): super(InvalidLifecycleConfigError, self).__init__(message) self.message = message # Enum class for resumable upload failure disposition. class ResumableTransferDisposition(object): # START_OVER means an attempt to resume an existing transfer failed, # and a new resumable upload should be attempted (without delay). START_OVER = 'START_OVER' # WAIT_BEFORE_RETRY means the resumable transfer failed but that it can # be retried after a time delay within the current process. WAIT_BEFORE_RETRY = 'WAIT_BEFORE_RETRY' # ABORT_CUR_PROCESS means the resumable transfer failed and that # delaying/retrying within the current process will not help. If # resumable transfer included a state tracker file the upload can be # retried again later, in another process (e.g., a later run of gsutil). ABORT_CUR_PROCESS = 'ABORT_CUR_PROCESS' # ABORT means the resumable transfer failed in a way that it does not # make sense to continue in the current process, and further that the # current tracker ID should not be preserved (in a tracker file if one # was specified at resumable upload start time). If the user tries again # later (e.g., a separate run of gsutil) it will get a new resumable # upload ID. ABORT = 'ABORT' class ResumableUploadException(Exception): """ Exception raised for various resumable upload problems. self.disposition is of type ResumableTransferDisposition. """ def __init__(self, message, disposition): super(ResumableUploadException, self).__init__(message, disposition) self.message = message self.disposition = disposition def __repr__(self): return 'ResumableUploadException("%s", %s)' % ( self.message, self.disposition) class ResumableDownloadException(Exception): """ Exception raised for various resumable download problems. self.disposition is of type ResumableTransferDisposition. """ def __init__(self, message, disposition): super(ResumableDownloadException, self).__init__(message, disposition) self.message = message self.disposition = disposition def __repr__(self): return 'ResumableDownloadException("%s", %s)' % ( self.message, self.disposition) class TooManyRecordsException(Exception): """ Exception raised when a search of Route53 records returns more records than requested. """ def __init__(self, message): super(TooManyRecordsException, self).__init__(message) self.message = message class PleaseRetryException(Exception): """ Indicates a request should be retried. """ def __init__(self, message, response=None): self.message = message self.response = response def __repr__(self): return 'PleaseRetryException("%s", %s)' % ( self.message, self.response )<|fim▁end|>
import boto
<|file_name|>strings.js<|end_file_name|><|fim▁begin|>define({ "unit": "Jedinica", "style": "Stil", "dual": "dvostruki", "english": "engleski", "metric": "metrički", "ruler": "ravnalo",<|fim▁hole|> "separator": "Prikaži razdjelnik tisućica" });<|fim▁end|>
"line": "linija", "number": "broj", "spinnerLabel": "Zaokruži broj mjerila na: ", "decimalPlace": "decimalno mjesto",
<|file_name|>HistoryUpdate.java<|end_file_name|><|fim▁begin|>/****************************************************************************** * Copyright (C) 2010-2016 CERN. All rights not expressly granted are reserved. * * This file is part of the CERN Control and Monitoring Platform 'C2MON'. * C2MON 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, either version 3 of the license. * * C2MON is distributed in the hope that it will be useful, but WITHOUT ANY<|fim▁hole|> * more details. * * You should have received a copy of the GNU Lesser General Public License * along with C2MON. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package cern.c2mon.client.ext.history.common; import java.sql.Timestamp; import cern.c2mon.client.ext.history.common.id.HistoryUpdateId; /** * This interface is used to keep track of the data which is from the history. * It have a function to get the execution time of the update so the player will know * when to execute the update. And it also have an identifier. * * @author vdeila * */ public interface HistoryUpdate { /** * * @return the id of the update */ HistoryUpdateId getUpdateId(); /** * * @return the time of when this update should execute */ Timestamp getExecutionTimestamp(); }<|fim▁end|>
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
<|file_name|>generate-messages-header.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright (C) 2010 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import with_statement import sys <|fim▁hole|> if not argv: argv = sys.argv input_path = argv[1] with open(input_path) as input_file: # Python 3, change to: print(webkit.messages.generate_messages_header(input_file), end='') sys.stdout.write(webkit.messages.generate_messages_header(input_file)) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))<|fim▁end|>
import webkit.messages def main(argv=None):
<|file_name|>database.py<|end_file_name|><|fim▁begin|>from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy()<|fim▁hole|><|fim▁end|>
from saef_app.core import models
<|file_name|>flipclock2.js<|end_file_name|><|fim▁begin|>/* Base.js, version 1.1a Copyright 2006-2010, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ var Base = function() { // dummy }; Base.extend = function(_instance, _static) { // subclass "use strict"; var extend = Base.prototype.extend; // build the prototype Base._prototyping = true; var proto = new this(); extend.call(proto, _instance); proto.base = function() { // call this method from any other method to invoke that method's ancestor }; delete Base._prototyping; // create the wrapper for the constructor function //var constructor = proto.constructor.valueOf(); //-dean var constructor = proto.constructor; var klass = proto.constructor = function() { if (!Base._prototyping) { if (this._constructing || this.constructor == klass) { // instantiation this._constructing = true; constructor.apply(this, arguments); delete this._constructing; } else if (arguments[0] !== null) { // casting return (arguments[0].extend || extend).call(arguments[0], proto); } } }; // build the class interface klass.ancestor = this; klass.extend = this.extend; klass.forEach = this.forEach; klass.implement = this.implement; klass.prototype = proto; klass.toString = this.toString; klass.valueOf = function(type) { //return (type == "object") ? klass : constructor; //-dean return (type == "object") ? klass : constructor.valueOf(); }; extend.call(klass, _static); // class initialisation if (typeof klass.init == "function") klass.init(); return klass; }; Base.prototype = { extend: function(source, value) { if (arguments.length > 1) { // extending with a name/value pair var ancestor = this[source]; if (ancestor && (typeof value == "function") && // overriding a method? // the valueOf() comparison is to avoid circular references (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && /\bbase\b/.test(value)) { // get the underlying method var method = value.valueOf(); // override value = function() { var previous = this.base || Base.prototype.base; this.base = ancestor; var returnValue = method.apply(this, arguments); this.base = previous; return returnValue; }; // point to the underlying method value.valueOf = function(type) { return (type == "object") ? value : method; }; value.toString = Base.toString; } this[source] = value; } else if (source) { // extending with an object literal var extend = Base.prototype.extend; // if this object has a customised extend method then use it if (!Base._prototyping && typeof this != "function") { extend = this.extend || extend; } var proto = {toSource: null}; // do the "toString" and other methods manually var hidden = ["constructor", "toString", "valueOf"]; // if we are prototyping then include the constructor var i = Base._prototyping ? 0 : 1; while (key = hidden[i++]) { if (source[key] != proto[key]) { extend.call(this, key, source[key]); } } // copy each of the source object's properties to this object for (var key in source) { if (!proto[key]) extend.call(this, key, source[key]); } } return this; } }; // initialise Base = Base.extend({ constructor: function() { this.extend(arguments[0]); } }, { ancestor: Object, version: "1.1", forEach: function(object, block, context) { for (var key in object) { if (this.prototype[key] === undefined) { block.call(context, object[key], key, object); } } }, implement: function() { for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == "function") { // if it's a function, call it arguments[i](this.prototype); } else { // add the interface using the extend method this.prototype.extend(arguments[i]); } } return this; }, toString: function() { return String(this.valueOf()); } }); /*jshint smarttabs:true */ var FlipClock; /** * FlipClock.js * * @author Justin Kimbrell * @copyright 2013 - Objective HTML, LLC * @licesnse http://www.opensource.org/licenses/mit-license.php */ (function($) { "use strict"; /** * FlipFlock Helper * * @param object A jQuery object or CSS select * @param int An integer used to start the clock (no. seconds) * @param object An object of properties to override the default */ FlipClock = function(obj, digit, options) { if(digit instanceof Object && digit instanceof Date === false) { options = digit; digit = 0; } return new FlipClock.Factory(obj, digit, options); }; /** * The global FlipClock.Lang object */ FlipClock.Lang = {}; /** * The Base FlipClock class is used to extend all other FlipFlock * classes. It handles the callbacks and the basic setters/getters * * @param object An object of the default properties * @param object An object of properties to override the default */ FlipClock.Base = Base.extend({ /** * Build Date */ buildDate: '2014-12-12', /** * Version */ version: '0.7.7', /** * Sets the default options * * @param object The default options * @param object The override options */ constructor: function(_default, options) { if(typeof _default !== "object") { _default = {}; } if(typeof options !== "object") { options = {}; } this.setOptions($.extend(true, {}, _default, options)); }, /** * Delegates the callback to the defined method * * @param object The default options * @param object The override options */ callback: function(method) { if(typeof method === "function") { var args = []; for(var x = 1; x <= arguments.length; x++) { if(arguments[x]) { args.push(arguments[x]); } } method.apply(this, args); } }, /** * Log a string into the console if it exists * * @param string The name of the option * @return mixed */ log: function(str) { if(window.console && console.log) { console.log(str); } }, /** * Get an single option value. Returns false if option does not exist * * @param string The name of the option * @return mixed */ getOption: function(index) { if(this[index]) { return this[index]; } return false; }, /** * Get all options * * @return bool */ getOptions: function() { return this; }, /** * Set a single option value * * @param string The name of the option * @param mixed The value of the option */ setOption: function(index, value) { this[index] = value; }, /** * Set a multiple options by passing a JSON object * * @param object The object with the options * @param mixed The value of the option */ setOptions: function(options) { for(var key in options) { if(typeof options[key] !== "undefined") { this.setOption(key, options[key]); } } } }); }(jQuery)); /*jshint smarttabs:true */ /** * FlipClock.js * * @author Justin Kimbrell * @copyright 2013 - Objective HTML, LLC * @licesnse http://www.opensource.org/licenses/mit-license.php */ (function($) { "use strict"; /** * The FlipClock Face class is the base class in which to extend * all other FlockClock.Face classes. * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ FlipClock.Face = FlipClock.Base.extend({ /** * Sets whether or not the clock should start upon instantiation */ autoStart: true, /** * An array of jQuery objects used for the dividers (the colons) */ dividers: [], /** * An array of FlipClock.List objects */ factory: false, /** * An array of FlipClock.List objects */ lists: [], /** * Constructor * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ constructor: function(factory, options) { this.dividers = []; this.lists = []; this.base(options); this.factory = factory; }, /** * Build the clock face */ build: function() { if(this.autoStart) { this.start(); } }, /** * Creates a jQuery object used for the digit divider * * @param mixed The divider label text * @param mixed Set true to exclude the dots in the divider. * If not set, is false. */ createDivider: function(label, css, excludeDots) { if(typeof css == "boolean" || !css) { excludeDots = css; css = label; } var dots = [ '<span class="'+this.factory.classes.dot+' top"></span>', '<span class="'+this.factory.classes.dot+' bottom"></span>' ].join(''); if(excludeDots) { dots = ''; } label = this.factory.localize(label); var html = [ '<span class="'+this.factory.classes.divider+' '+(css ? css : '').toLowerCase()+'">', '<span class="'+this.factory.classes.label+'">'+(label ? label : '')+'</span>', dots, '</span>' ]; var $html = $(html.join('')); this.dividers.push($html); return $html; }, /** * Creates a FlipClock.List object and appends it to the DOM * * @param mixed The digit to select in the list * @param object An object to override the default properties */ createList: function(digit, options) { if(typeof digit === "object") { options = digit; digit = 0; } var obj = new FlipClock.List(this.factory, digit, options); this.lists.push(obj); return obj; }, /** * Triggers when the clock is reset */ reset: function() { this.factory.time = new FlipClock.Time( this.factory, this.factory.original ? Math.round(this.factory.original) : 0, { minimumDigits: this.factory.minimumDigits } ); this.flip(this.factory.original, false); }, /** * Append a newly created list to the clock */ appendDigitToClock: function(obj) { obj.$el.append(false); }, /** * Add a digit to the clock face */ addDigit: function(digit) { var obj = this.createList(digit, { classes: { active: this.factory.classes.active, before: this.factory.classes.before, flip: this.factory.classes.flip } }); this.appendDigitToClock(obj); }, /** * Triggers when the clock is started */ start: function() {}, /** * Triggers when the time on the clock stops */ stop: function() {}, /** * Auto increments/decrements the value of the clock face */ autoIncrement: function() { if(!this.factory.countdown) { this.increment(); } else { this.decrement(); } }, /** * Increments the value of the clock face */ increment: function() { this.factory.time.addSecond(); }, /** * Decrements the value of the clock face */ decrement: function() { if(this.factory.time.getTimeSeconds() == 0) { this.factory.stop() } else { this.factory.time.subSecond(); } }, /** * Triggers when the numbers on the clock flip */ flip: function(time, doNotAddPlayClass) { var t = this; $.each(time, function(i, digit) { var list = t.lists[i]; if(list) { if(!doNotAddPlayClass && digit != list.digit) { list.play(); } list.select(digit); } else { t.addDigit(digit); } }); } }); }(jQuery)); /*jshint smarttabs:true */ /** * FlipClock.js * * @author Justin Kimbrell * @copyright 2013 - Objective HTML, LLC * @licesnse http://www.opensource.org/licenses/mit-license.php */ (function($) { "use strict"; /** * The FlipClock Factory class is used to build the clock and manage * all the public methods. * * @param object A jQuery object or CSS selector used to fetch the wrapping DOM nodes * @param mixed This is the digit used to set the clock. If an object is passed, 0 will be used. * @param object An object of properties to override the default */ FlipClock.Factory = FlipClock.Base.extend({ /** * The clock's animation rate. * * Note, currently this property doesn't do anything. * This property is here to be used in the future to * programmaticaly set the clock's animation speed */ animationRate: 1000, /** * Auto start the clock on page load (True|False) */ autoStart: true, /** * The callback methods */ callbacks: { destroy: false, create: false, init: false, interval: false, start: false, stop: false, reset: false }, /** * The CSS classes */ classes: { active: 'flip-clock-active', before: 'flip-clock-before', divider: 'flip-clock-divider', dot: 'flip-clock-dot', label: 'flip-clock-label', flip: 'flip', play: 'play', wrapper: 'flip-clock-wrapper' }, /** * The name of the clock face class in use */ clockFace: 'HourlyCounter', /** * The name of the clock face class in use */ countdown: false, /** * The name of the default clock face class to use if the defined * clockFace variable is not a valid FlipClock.Face object */ defaultClockFace: 'HourlyCounter', /** * The default language */ defaultLanguage: 'english', /** * The jQuery object */ $el: false, /**<|fim▁hole|> * The FlipClock.Face object */ face: true, /** * The language object after it has been loaded */ lang: false, /** * The language being used to display labels (string) */ language: 'english', /** * The minimum digits the clock must have */ minimumDigits: 0, /** * The original starting value of the clock. Used for the reset method. */ original: false, /** * Is the clock running? (True|False) */ running: false, /** * The FlipClock.Time object */ time: false, /** * The FlipClock.Timer object */ timer: false, /** * The jQuery object (depcrecated) */ $wrapper: false, /** * Constructor * * @param object The wrapping jQuery object * @param object Number of seconds used to start the clock * @param object An object override options */ constructor: function(obj, digit, options) { if(!options) { options = {}; } this.lists = []; this.running = false; this.base(options); this.$el = $(obj).addClass(this.classes.wrapper); // Depcrated support of the $wrapper property. this.$wrapper = this.$el; this.original = (digit instanceof Date) ? digit : (digit ? Math.round(digit) : 0); this.time = new FlipClock.Time(this, this.original, { minimumDigits: this.minimumDigits, animationRate: this.animationRate }); this.timer = new FlipClock.Timer(this, options); this.loadLanguage(this.language); this.loadClockFace(this.clockFace, options); if(this.autoStart) { this.start(); } }, /** * Load the FlipClock.Face object * * @param object The name of the FlickClock.Face class * @param object An object override options */ loadClockFace: function(name, options) { var face, suffix = 'Face', hasStopped = false; name = name.ucfirst()+suffix; if(this.face.stop) { this.stop(); hasStopped = true; } this.$el.html(''); this.time.minimumDigits = this.minimumDigits; if(FlipClock[name]) { face = new FlipClock[name](this, options); } else { face = new FlipClock[this.defaultClockFace+suffix](this, options); } face.build(); this.face = face if(hasStopped) { this.start(); } return this.face; }, /** * Load the FlipClock.Lang object * * @param object The name of the language to load */ loadLanguage: function(name) { var lang; if(FlipClock.Lang[name.ucfirst()]) { lang = FlipClock.Lang[name.ucfirst()]; } else if(FlipClock.Lang[name]) { lang = FlipClock.Lang[name]; } else { lang = FlipClock.Lang[this.defaultLanguage]; } return this.lang = lang; }, /** * Localize strings into various languages * * @param string The index of the localized string * @param object Optionally pass a lang object */ localize: function(index, obj) { var lang = this.lang; if(!index) { return null; } var lindex = index.toLowerCase(); if(typeof obj == "object") { lang = obj; } if(lang && lang[lindex]) { return lang[lindex]; } return index; }, /** * Starts the clock */ start: function(callback) { var t = this; if(!t.running && (!t.countdown || t.countdown && t.time.time > 0)) { t.face.start(t.time); t.timer.start(function() { t.flip(); if(typeof callback === "function") { callback(); } }); } else { t.log('Trying to start timer when countdown already at 0'); } }, /** * Stops the clock */ stop: function(callback) { this.face.stop(); this.timer.stop(callback); for(var x in this.lists) { if (this.lists.hasOwnProperty(x)) { this.lists[x].stop(); } } }, /** * Reset the clock */ reset: function(callback) { this.timer.reset(callback); this.face.reset(); }, /** * Sets the clock time */ setTime: function(time) { this.time.time = time; this.flip(true); }, /** * Get the clock time * * @return object Returns a FlipClock.Time object */ getTime: function(time) { return this.time; }, /** * Changes the increment of time to up or down (add/sub) */ setCountdown: function(value) { var running = this.running; this.countdown = value ? true : false; if(running) { this.stop(); this.start(); } }, /** * Flip the digits on the clock * * @param array An array of digits */ flip: function(doNotAddPlayClass) { this.face.flip(false, doNotAddPlayClass); } }); }(jQuery)); /*jshint smarttabs:true */ /** * FlipClock.js * * @author Justin Kimbrell * @copyright 2013 - Objective HTML, LLC * @licesnse http://www.opensource.org/licenses/mit-license.php */ (function($) { "use strict"; /** * The FlipClock List class is used to build the list used to create * the card flip effect. This object fascilates selecting the correct * node by passing a specific digit. * * @param object A FlipClock.Factory object * @param mixed This is the digit used to set the clock. If an * object is passed, 0 will be used. * @param object An object of properties to override the default */ FlipClock.List = FlipClock.Base.extend({ /** * The digit (0-9) */ digit: 0, /** * The CSS classes */ classes: { active: 'flip-clock-active', before: 'flip-clock-before', flip: 'flip' }, /** * The parent FlipClock.Factory object */ factory: false, /** * The jQuery object */ $el: false, /** * The jQuery object (deprecated) */ $obj: false, /** * The items in the list */ items: [], /** * The last digit */ lastDigit: 0, /** * Constructor * * @param object A FlipClock.Factory object * @param int An integer use to select the correct digit * @param object An object to override the default properties */ constructor: function(factory, digit, options) { this.factory = factory; this.digit = digit; this.lastDigit = digit; this.$el = this.createList(); // Depcrated support of the $obj property. this.$obj = this.$el; if(digit > 0) { this.select(digit); } this.factory.$el.append(this.$el); }, /** * Select the digit in the list * * @param int A digit 0-9 */ select: function(digit) { if(typeof digit === "undefined") { digit = this.digit; } else { this.digit = digit; } if(this.digit != this.lastDigit) { var $delete = this.$el.find('.'+this.classes.before).removeClass(this.classes.before); this.$el.find('.'+this.classes.active).removeClass(this.classes.active) .addClass(this.classes.before); this.appendListItem(this.classes.active, this.digit); $delete.remove(); this.lastDigit = this.digit; } }, /** * Adds the play class to the DOM object */ play: function() { this.$el.addClass(this.factory.classes.play); }, /** * Removes the play class to the DOM object */ stop: function() { var t = this; setTimeout(function() { t.$el.removeClass(t.factory.classes.play); }, this.factory.timer.interval); }, /** * Creates the list item HTML and returns as a string */ createListItem: function(css, value) { return [ '<li class="'+(css ? css : '')+'">', '<a href="#">', '<div class="up">', '<div class="shadow"></div>', '<div class="inn">'+(value ? value : '')+'</div>', '</div>', '<div class="down">', '<div class="shadow"></div>', '<div class="inn">'+(value ? value : '')+'</div>', '</div>', '</a>', '</li>' ].join(''); }, /** * Append the list item to the parent DOM node */ appendListItem: function(css, value) { var html = this.createListItem(css, value); this.$el.append(html); }, /** * Create the list of digits and appends it to the DOM object */ createList: function() { var lastDigit = this.getPrevDigit() ? this.getPrevDigit() : this.digit; var html = $([ '<ul class="'+this.classes.flip+' '+(this.factory.running ? this.factory.classes.play : '')+'">', this.createListItem(this.classes.before, lastDigit), this.createListItem(this.classes.active, this.digit), '</ul>' ].join('')); return html; }, getNextDigit: function() { return this.digit == 9 ? 0 : this.digit + 1; }, getPrevDigit: function() { return this.digit == 0 ? 9 : this.digit - 1; } }); }(jQuery)); /*jshint smarttabs:true */ /** * FlipClock.js * * @author Justin Kimbrell * @copyright 2013 - Objective HTML, LLC * @licesnse http://www.opensource.org/licenses/mit-license.php */ (function($) { "use strict"; /** * Capitalize the first letter in a string * * @return string */ String.prototype.ucfirst = function() { return this.substr(0, 1).toUpperCase() + this.substr(1); }; /** * jQuery helper method * * @param int An integer used to start the clock (no. seconds) * @param object An object of properties to override the default */ $.fn.FlipClock = function(digit, options) { return new FlipClock($(this), digit, options); }; /** * jQuery helper method * * @param int An integer used to start the clock (no. seconds) * @param object An object of properties to override the default */ $.fn.flipClock = function(digit, options) { return $.fn.FlipClock(digit, options); }; }(jQuery)); /*jshint smarttabs:true */ /** * FlipClock.js * * @author Justin Kimbrell * @copyright 2013 - Objective HTML, LLC * @licesnse http://www.opensource.org/licenses/mit-license.php */ (function($) { "use strict"; /** * The FlipClock Time class is used to manage all the time * calculations. * * @param object A FlipClock.Factory object * @param mixed This is the digit used to set the clock. If an * object is passed, 0 will be used. * @param object An object of properties to override the default */ FlipClock.Time = FlipClock.Base.extend({ /** * The time (in seconds) or a date object */ time: 0, /** * The parent FlipClock.Factory object */ factory: false, /** * The minimum number of digits the clock face must have */ minimumDigits: 0, /** * Constructor * * @param object A FlipClock.Factory object * @param int An integer use to select the correct digit * @param object An object to override the default properties */ constructor: function(factory, time, options) { if(typeof options != "object") { options = {}; } if(!options.minimumDigits) { options.minimumDigits = factory.minimumDigits; } this.base(options); this.factory = factory; if(time) { this.time = time; } }, /** * Convert a string or integer to an array of digits * * @param mixed String or Integer of digits * @return array An array of digits */ convertDigitsToArray: function(str) { var data = []; str = str.toString(); for(var x = 0;x < str.length; x++) { if(str[x].match(/^\d*$/g)) { data.push(str[x]); } } return data; }, /** * Get a specific digit from the time integer * * @param int The specific digit to select from the time * @return mixed Returns FALSE if no digit is found, otherwise * the method returns the defined digit */ digit: function(i) { var timeStr = this.toString(); var length = timeStr.length; if(timeStr[length - i]) { return timeStr[length - i]; } return false; }, /** * Formats any array of digits into a valid array of digits * * @param mixed An array of digits * @return array An array of digits */ digitize: function(obj) { var data = []; $.each(obj, function(i, value) { value = value.toString(); if(value.length == 1) { value = '0'+value; } for(var x = 0; x < value.length; x++) { data.push(value.charAt(x)); } }); if(data.length > this.minimumDigits) { this.minimumDigits = data.length; } if(this.minimumDigits > data.length) { for(var x = data.length; x < this.minimumDigits; x++) { data.unshift('0'); } } return data; }, /** * Gets a new Date object for the current time * * @return array Returns a Date object */ getDateObject: function() { if(this.time instanceof Date) { return this.time; } return new Date((new Date()).getTime() + this.getTimeSeconds() * 1000); }, /** * Gets a digitized daily counter * * @return object Returns a digitized object */ getDayCounter: function(includeSeconds) { var digits = [ this.getDays(), this.getHours(true), this.getMinutes(true) ]; if(includeSeconds) { digits.push(this.getSeconds(true)); } return this.digitize(digits); }, /** * Gets number of days * * @param bool Should perform a modulus? If not sent, then no. * @return int Retuns a floored integer */ getDays: function(mod) { var days = this.getTimeSeconds() / 60 / 60 / 24; if(mod) { days = days % 7; } return Math.floor(days); }, /** * Gets an hourly breakdown * * @return object Returns a digitized object */ getHourCounter: function() { var obj = this.digitize([ this.getHours(), this.getMinutes(true), this.getSeconds(true) ]); return obj; }, /** * Gets an hourly breakdown * * @return object Returns a digitized object */ getHourly: function() { return this.getHourCounter(); }, /** * Gets number of hours * * @param bool Should perform a modulus? If not sent, then no. * @return int Retuns a floored integer */ getHours: function(mod) { var hours = this.getTimeSeconds() / 60 / 60; if(mod) { hours = hours % 24; } return Math.floor(hours); }, /** * Gets the twenty-four hour time * * @return object returns a digitized object */ getMilitaryTime: function(date, showSeconds) { if(typeof showSeconds === "undefined") { showSeconds = true; } if(!date) { date = this.getDateObject(); } var data = [ date.getHours(), date.getMinutes() ]; if(showSeconds === true) { data.push(date.getSeconds()); } return this.digitize(data); }, /** * Gets number of minutes * * @param bool Should perform a modulus? If not sent, then no. * @return int Retuns a floored integer */ getMinutes: function(mod) { var minutes = this.getTimeSeconds() / 60; if(mod) { minutes = minutes % 60; } return Math.floor(minutes); }, /** * Gets a minute breakdown */ getMinuteCounter: function() { var obj = this.digitize([ this.getMinutes(), this.getSeconds(true) ]); return obj; }, /** * Gets time count in seconds regardless of if targetting date or not. * * @return int Returns a floored integer */ getTimeSeconds: function(date) { if(!date) { date = new Date(); } if (this.time instanceof Date) { if (this.factory.countdown) { return Math.max(this.time.getTime()/1000 - date.getTime()/1000,0); } else { return date.getTime()/1000 - this.time.getTime()/1000 ; } } else { return this.time; } }, /** * Gets the current twelve hour time * * @return object Returns a digitized object */ getTime: function(date, showSeconds) { if(typeof showSeconds === "undefined") { showSeconds = true; } if(!date) { date = this.getDateObject(); } console.log(date); var hours = date.getHours(); var merid = hours > 12 ? 'PM' : 'AM'; var data = [ hours > 12 ? hours - 12 : (hours === 0 ? 12 : hours), date.getMinutes() ]; if(showSeconds === true) { data.push(date.getSeconds()); } return this.digitize(data); }, /** * Gets number of seconds * * @param bool Should perform a modulus? If not sent, then no. * @return int Retuns a ceiled integer */ getSeconds: function(mod) { var seconds = this.getTimeSeconds(); if(mod) { if(seconds == 60) { seconds = 0; } else { seconds = seconds % 60; } } return Math.ceil(seconds); }, /** * Gets number of weeks * * @param bool Should perform a modulus? If not sent, then no. * @return int Retuns a floored integer */ getWeeks: function(mod) { var weeks = this.getTimeSeconds() / 60 / 60 / 24 / 7; if(mod) { weeks = weeks % 52; } return Math.floor(weeks); }, /** * Removes a specific number of leading zeros from the array. * This method prevents you from removing too many digits, even * if you try. * * @param int Total number of digits to remove * @return array An array of digits */ removeLeadingZeros: function(totalDigits, digits) { var total = 0; var newArray = []; $.each(digits, function(i, digit) { if(i < totalDigits) { total += parseInt(digits[i], 10); } else { newArray.push(digits[i]); } }); if(total === 0) { return newArray; } return digits; }, /** * Adds X second to the current time */ addSeconds: function(x) { if(this.time instanceof Date) { this.time.setSeconds(this.time.getSeconds() + x); } else { this.time += x; } }, /** * Adds 1 second to the current time */ addSecond: function() { this.addSeconds(1); }, /** * Substracts X seconds from the current time */ subSeconds: function(x) { if(this.time instanceof Date) { this.time.setSeconds(this.time.getSeconds() - x); } else { this.time -= x; } }, /** * Substracts 1 second from the current time */ subSecond: function() { this.subSeconds(1); }, /** * Converts the object to a human readable string */ toString: function() { return this.getTimeSeconds().toString(); } /* getYears: function() { return Math.floor(this.time / 60 / 60 / 24 / 7 / 52); }, getDecades: function() { return Math.floor(this.getWeeks() / 10); }*/ }); }(jQuery)); /*jshint smarttabs:true */ /** * FlipClock.js * * @author Justin Kimbrell * @copyright 2013 - Objective HTML, LLC * @licesnse http://www.opensource.org/licenses/mit-license.php */ (function($) { "use strict"; /** * The FlipClock.Timer object managers the JS timers * * @param object The parent FlipClock.Factory object * @param object Override the default options */ FlipClock.Timer = FlipClock.Base.extend({ /** * Callbacks */ callbacks: { destroy: false, create: false, init: false, interval: false, start: false, stop: false, reset: false }, /** * FlipClock timer count (how many intervals have passed) */ count: 0, /** * The parent FlipClock.Factory object */ factory: false, /** * Timer interval (1 second by default) */ interval: 1000, /** * The rate of the animation in milliseconds (not currently in use) */ animationRate: 1000, /** * Constructor * * @return void */ constructor: function(factory, options) { this.base(options); this.factory = factory; this.callback(this.callbacks.init); this.callback(this.callbacks.create); }, /** * This method gets the elapsed the time as an interger * * @return void */ getElapsed: function() { return this.count * this.interval; }, /** * This method gets the elapsed the time as a Date object * * @return void */ getElapsedTime: function() { return new Date(this.time + this.getElapsed()); }, /** * This method is resets the timer * * @param callback This method resets the timer back to 0 * @return void */ reset: function(callback) { clearInterval(this.timer); this.count = 0; this._setInterval(callback); this.callback(this.callbacks.reset); }, /** * This method is starts the timer * * @param callback A function that is called once the timer is destroyed * @return void */ start: function(callback) { this.factory.running = true; this._createTimer(callback); this.callback(this.callbacks.start); }, /** * This method is stops the timer * * @param callback A function that is called once the timer is destroyed * @return void */ stop: function(callback) { this.factory.running = false; this._clearInterval(callback); this.callback(this.callbacks.stop); this.callback(callback); }, /** * Clear the timer interval * * @return void */ _clearInterval: function() { clearInterval(this.timer); }, /** * Create the timer object * * @param callback A function that is called once the timer is created * @return void */ _createTimer: function(callback) { this._setInterval(callback); }, /** * Destroy the timer object * * @param callback A function that is called once the timer is destroyed * @return void */ _destroyTimer: function(callback) { this._clearInterval(); this.timer = false; this.callback(callback); this.callback(this.callbacks.destroy); }, /** * This method is called each time the timer interval is ran * * @param callback A function that is called once the timer is destroyed * @return void */ _interval: function(callback) { this.callback(this.callbacks.interval); this.callback(callback); this.count++; }, /** * This sets the timer interval * * @param callback A function that is called once the timer is destroyed * @return void */ _setInterval: function(callback) { var t = this; t._interval(callback); t.timer = setInterval(function() { t._interval(callback); }, this.interval); } }); }(jQuery)); (function($) { /** * Twenty-Four Hour Clock Face * * This class will generate a twenty-four our clock for FlipClock.js * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ FlipClock.TwentyFourHourClockFace = FlipClock.Face.extend({ /** * Constructor * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ constructor: function(factory, options) { this.base(factory, options); }, /** * Build the clock face * * @param object Pass the time that should be used to display on the clock. */ build: function(time) { var t = this; var children = this.factory.$el.find('ul'); if(!this.factory.time.time) { this.factory.original = new Date(); this.factory.time = new FlipClock.Time(this.factory, this.factory.original); } var time = time ? time : this.factory.time.getMilitaryTime(false, this.showSeconds); if(time.length > children.length) { $.each(time, function(i, digit) { t.createList(digit); }); } this.createDivider(); this.createDivider(); $(this.dividers[0]).insertBefore(this.lists[this.lists.length - 2].$el); $(this.dividers[1]).insertBefore(this.lists[this.lists.length - 4].$el); this.base(); }, /** * Flip the clock face */ flip: function(time, doNotAddPlayClass) { this.autoIncrement(); time = time ? time : this.factory.time.getMilitaryTime(false, this.showSeconds); this.base(time, doNotAddPlayClass); } }); }(jQuery)); (function($) { /** * Counter Clock Face * * This class will generate a generice flip counter. The timer has been * disabled. clock.increment() and clock.decrement() have been added. * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ FlipClock.CounterFace = FlipClock.Face.extend({ /** * Tells the counter clock face if it should auto-increment */ shouldAutoIncrement: false, /** * Constructor * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ constructor: function(factory, options) { if(typeof options != "object") { options = {}; } factory.autoStart = options.autoStart ? true : false; if(options.autoStart) { this.shouldAutoIncrement = true; } factory.increment = function() { factory.countdown = false; factory.setTime(factory.getTime().getTimeSeconds() + 1); }; factory.decrement = function() { factory.countdown = true; var time = factory.getTime().getTimeSeconds(); if(time > 0) { factory.setTime(time - 1); } }; factory.setValue = function(digits) { factory.setTime(digits); }; factory.setCounter = function(digits) { factory.setTime(digits); }; this.base(factory, options); }, /** * Build the clock face */ build: function() { var t = this; var children = this.factory.$el.find('ul'); var time = this.factory.getTime().digitize([this.factory.getTime().time]); if(time.length > children.length) { $.each(time, function(i, digit) { var list = t.createList(digit); list.select(digit); }); } $.each(this.lists, function(i, list) { list.play(); }); this.base(); }, /** * Flip the clock face */ flip: function(time, doNotAddPlayClass) { if(this.shouldAutoIncrement) { this.autoIncrement(); } if(!time) { time = this.factory.getTime().digitize([this.factory.getTime().time]); } this.base(time, doNotAddPlayClass); }, /** * Reset the clock face */ reset: function() { this.factory.time = new FlipClock.Time( this.factory, this.factory.original ? Math.round(this.factory.original) : 0 ); this.flip(); } }); }(jQuery)); (function($) { /** * Daily Counter Clock Face * * This class will generate a daily counter for FlipClock.js. A * daily counter will track days, hours, minutes, and seconds. If * the number of available digits is exceeded in the count, a new * digit will be created. * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ FlipClock.DailyCounterFace = FlipClock.Face.extend({ showSeconds: true, /** * Constructor * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ constructor: function(factory, options) { this.base(factory, options); }, /** * Build the clock face */ build: function(time) { var t = this; var children = this.factory.$el.find('ul'); var offset = 0; time = time ? time : this.factory.time.getDayCounter(this.showSeconds); if(time.length > children.length) { $.each(time, function(i, digit) { t.createList(digit); }); } if(this.showSeconds) { $(this.createDivider('Segundos')).insertBefore(this.lists[this.lists.length - 2].$el); } else { offset = 2; } $(this.createDivider('Minutos')).insertBefore(this.lists[this.lists.length - 4 + offset].$el); $(this.createDivider('Horas')).insertBefore(this.lists[this.lists.length - 6 + offset].$el); $(this.createDivider('Dias', true)).insertBefore(this.lists[0].$el); this.base(); }, /** * Flip the clock face */ flip: function(time, doNotAddPlayClass) { if(!time) { time = this.factory.time.getDayCounter(this.showSeconds); } this.autoIncrement(); this.base(time, doNotAddPlayClass); } }); }(jQuery)); (function($) { /** * Hourly Counter Clock Face * * This class will generate an hourly counter for FlipClock.js. An * hour counter will track hours, minutes, and seconds. If number of * available digits is exceeded in the count, a new digit will be * created. * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ FlipClock.HourlyCounterFace = FlipClock.Face.extend({ // clearExcessDigits: true, /** * Constructor * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ constructor: function(factory, options) { this.base(factory, options); }, /** * Build the clock face */ build: function(excludeHours, time) { var t = this; var children = this.factory.$el.find('ul'); time = time ? time : this.factory.time.getHourCounter(); if(time.length > children.length) { $.each(time, function(i, digit) { t.createList(digit); }); } $(this.createDivider('Segundos')).insertBefore(this.lists[this.lists.length - 2].$el); $(this.createDivider('Minutos')).insertBefore(this.lists[this.lists.length - 4].$el); if(!excludeHours) { $(this.createDivider('Horas', true)).insertBefore(this.lists[0].$el); } this.base(); }, /** * Flip the clock face */ flip: function(time, doNotAddPlayClass) { if(!time) { time = this.factory.time.getHourCounter(); } this.autoIncrement(); this.base(time, doNotAddPlayClass); }, /** * Append a newly created list to the clock */ appendDigitToClock: function(obj) { this.base(obj); this.dividers[0].insertAfter(this.dividers[0].next()); } }); }(jQuery)); (function($) { /** * Minute Counter Clock Face * * This class will generate a minute counter for FlipClock.js. A * minute counter will track minutes and seconds. If an hour is * reached, the counter will reset back to 0. (4 digits max) * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ FlipClock.MinuteCounterFace = FlipClock.HourlyCounterFace.extend({ clearExcessDigits: false, /** * Constructor * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ constructor: function(factory, options) { this.base(factory, options); }, /** * Build the clock face */ build: function() { this.base(true, this.factory.time.getMinuteCounter()); }, /** * Flip the clock face */ flip: function(time, doNotAddPlayClass) { if(!time) { time = this.factory.time.getMinuteCounter(); } this.base(time, doNotAddPlayClass); } }); }(jQuery)); (function($) { /** * Twelve Hour Clock Face * * This class will generate a twelve hour clock for FlipClock.js * * @param object The parent FlipClock.Factory object * @param object An object of properties to override the default */ FlipClock.TwelveHourClockFace = FlipClock.TwentyFourHourClockFace.extend({ /** * The meridium jQuery DOM object */ meridium: false, /** * The meridium text as string for easy access */ meridiumText: 'AM', /** * Build the clock face * * @param object Pass the time that should be used to display on the clock. */ build: function() { var t = this; var time = this.factory.time.getTime(false, this.showSeconds); this.base(time); this.meridiumText = this.getMeridium(); this.meridium = $([ '<ul class="flip-clock-meridium">', '<li>', '<a href="#">'+this.meridiumText+'</a>', '</li>', '</ul>' ].join('')); this.meridium.insertAfter(this.lists[this.lists.length-1].$el); }, /** * Flip the clock face */ flip: function(time, doNotAddPlayClass) { if(this.meridiumText != this.getMeridium()) { this.meridiumText = this.getMeridium(); this.meridium.find('a').html(this.meridiumText); } this.base(this.factory.time.getTime(false, this.showSeconds), doNotAddPlayClass); }, /** * Get the current meridium * * @return string Returns the meridium (AM|PM) */ getMeridium: function() { return new Date().getHours() >= 12 ? 'PM' : 'AM'; }, /** * Is it currently in the post-medirium? * * @return bool Returns true or false */ isPM: function() { return this.getMeridium() == 'PM' ? true : false; }, /** * Is it currently before the post-medirium? * * @return bool Returns true or false */ isAM: function() { return this.getMeridium() == 'AM' ? true : false; } }); }(jQuery)); (function($) { /** * FlipClock Arabic Language Pack * * This class will be used to translate tokens into the Arabic language. * */ FlipClock.Lang.Arabic = { 'years' : 'سنوات', 'months' : 'شهور', 'days' : 'أيام', 'hours' : 'ساعات', 'minutes' : 'دقائق', 'seconds' : 'ثواني' }; /* Create various aliases for convenience */ FlipClock.Lang['ar'] = FlipClock.Lang.Arabic; FlipClock.Lang['ar-ar'] = FlipClock.Lang.Arabic; FlipClock.Lang['arabic'] = FlipClock.Lang.Arabic; }(jQuery)); (function($) { /** * FlipClock Danish Language Pack * * This class will used to translate tokens into the Danish language. * */ FlipClock.Lang.Danish = { 'years' : 'År', 'months' : 'Måneder', 'days' : 'Dage', 'hours' : 'Timer', 'minutes' : 'Minutter', 'seconds' : 'Sekunder' }; /* Create various aliases for convenience */ FlipClock.Lang['da'] = FlipClock.Lang.Danish; FlipClock.Lang['da-dk'] = FlipClock.Lang.Danish; FlipClock.Lang['danish'] = FlipClock.Lang.Danish; }(jQuery)); (function($) { /** * FlipClock German Language Pack * * This class will used to translate tokens into the German language. * */ FlipClock.Lang.German = { 'years' : 'Jahre', 'months' : 'Monate', 'days' : 'Tage', 'hours' : 'Stunden', 'minutes' : 'Minuten', 'seconds' : 'Sekunden' }; /* Create various aliases for convenience */ FlipClock.Lang['de'] = FlipClock.Lang.German; FlipClock.Lang['de-de'] = FlipClock.Lang.German; FlipClock.Lang['german'] = FlipClock.Lang.German; }(jQuery)); (function($) { /** * FlipClock English Language Pack * * This class will used to translate tokens into the English language. * */ FlipClock.Lang.English = { 'years' : 'Years', 'months' : 'Months', 'days' : 'Days', 'hours' : 'Hours', 'minutes' : 'Minutos', 'seconds' : 'Segundos' }; /* Create various aliases for convenience */ FlipClock.Lang['en'] = FlipClock.Lang.English; FlipClock.Lang['en-us'] = FlipClock.Lang.English; FlipClock.Lang['english'] = FlipClock.Lang.English; }(jQuery)); (function($) { /** * FlipClock Spanish Language Pack * * This class will used to translate tokens into the Spanish language. * */ FlipClock.Lang.Spanish = { 'years' : 'Años', 'months' : 'Meses', 'days' : 'Días', 'hours' : 'Horas', 'minutes' : 'Minutos', 'seconds' : 'Segundos' }; /* Create various aliases for convenience */ FlipClock.Lang['es'] = FlipClock.Lang.Spanish; FlipClock.Lang['es-es'] = FlipClock.Lang.Spanish; FlipClock.Lang['spanish'] = FlipClock.Lang.Spanish; }(jQuery)); (function($) { /** * FlipClock Finnish Language Pack * * This class will used to translate tokens into the Finnish language. * */ FlipClock.Lang.Finnish = { 'years' : 'Vuotta', 'months' : 'Kuukautta', 'days' : 'Päivää', 'hours' : 'Tuntia', 'minutes' : 'Minuuttia', 'seconds' : 'Sekuntia' }; /* Create various aliases for convenience */ FlipClock.Lang['fi'] = FlipClock.Lang.Finnish; FlipClock.Lang['fi-fi'] = FlipClock.Lang.Finnish; FlipClock.Lang['finnish'] = FlipClock.Lang.Finnish; }(jQuery)); (function($) { /** * FlipClock Canadian French Language Pack * * This class will used to translate tokens into the Canadian French language. * */ FlipClock.Lang.French = { 'years' : 'Ans', 'months' : 'Mois', 'days' : 'Jours', 'hours' : 'Heures', 'minutes' : 'Minutes', 'seconds' : 'Secondes' }; /* Create various aliases for convenience */ FlipClock.Lang['fr'] = FlipClock.Lang.French; FlipClock.Lang['fr-ca'] = FlipClock.Lang.French; FlipClock.Lang['french'] = FlipClock.Lang.French; }(jQuery)); (function($) { /** * FlipClock Italian Language Pack * * This class will used to translate tokens into the Italian language. * */ FlipClock.Lang.Italian = { 'years' : 'Anni', 'months' : 'Mesi', 'days' : 'Giorni', 'hours' : 'Ore', 'minutes' : 'Minuti', 'seconds' : 'Secondi' }; /* Create various aliases for convenience */ FlipClock.Lang['it'] = FlipClock.Lang.Italian; FlipClock.Lang['it-it'] = FlipClock.Lang.Italian; FlipClock.Lang['italian'] = FlipClock.Lang.Italian; }(jQuery)); (function($) { /** * FlipClock Latvian Language Pack * * This class will used to translate tokens into the Latvian language. * */ FlipClock.Lang.Latvian = { 'years' : 'Gadi', 'months' : 'Mēneši', 'days' : 'Dienas', 'hours' : 'Stundas', 'minutes' : 'Minūtes', 'seconds' : 'Sekundes' }; /* Create various aliases for convenience */ FlipClock.Lang['lv'] = FlipClock.Lang.Latvian; FlipClock.Lang['lv-lv'] = FlipClock.Lang.Latvian; FlipClock.Lang['latvian'] = FlipClock.Lang.Latvian; }(jQuery)); (function($) { /** * FlipClock Dutch Language Pack * * This class will used to translate tokens into the Dutch language. */ FlipClock.Lang.Dutch = { 'years' : 'Jaren', 'months' : 'Maanden', 'days' : 'Dagen', 'hours' : 'Uren', 'minutes' : 'Minuten', 'seconds' : 'Seconden' }; /* Create various aliases for convenience */ FlipClock.Lang['nl'] = FlipClock.Lang.Dutch; FlipClock.Lang['nl-be'] = FlipClock.Lang.Dutch; FlipClock.Lang['dutch'] = FlipClock.Lang.Dutch; }(jQuery)); (function($) { /** * FlipClock Norwegian-Bokmål Language Pack * * This class will used to translate tokens into the Norwegian language. * */ FlipClock.Lang.Norwegian = { 'years' : 'År', 'months' : 'Måneder', 'days' : 'Dager', 'hours' : 'Timer', 'minutes' : 'Minutter', 'seconds' : 'Sekunder' }; /* Create various aliases for convenience */ FlipClock.Lang['no'] = FlipClock.Lang.Norwegian; FlipClock.Lang['nb'] = FlipClock.Lang.Norwegian; FlipClock.Lang['no-nb'] = FlipClock.Lang.Norwegian; FlipClock.Lang['norwegian'] = FlipClock.Lang.Norwegian; }(jQuery)); (function($) { /** * FlipClock Portuguese Language Pack * * This class will used to translate tokens into the Portuguese language. * */ FlipClock.Lang.Portuguese = { 'years' : 'Anos', 'months' : 'Meses', 'days' : 'Dias', 'hours' : 'Horas', 'minutes' : 'Minutos', 'seconds' : 'Segundos' }; /* Create various aliases for convenience */ FlipClock.Lang['pt'] = FlipClock.Lang.Portuguese; FlipClock.Lang['pt-br'] = FlipClock.Lang.Portuguese; FlipClock.Lang['portuguese'] = FlipClock.Lang.Portuguese; }(jQuery)); (function($) { /** * FlipClock Russian Language Pack * * This class will used to translate tokens into the Russian language. * */ FlipClock.Lang.Russian = { 'years' : 'лет', 'months' : 'месяцев', 'days' : 'дней', 'hours' : 'часов', 'minutes' : 'минут', 'seconds' : 'секунд' }; /* Create various aliases for convenience */ FlipClock.Lang['ru'] = FlipClock.Lang.Russian; FlipClock.Lang['ru-ru'] = FlipClock.Lang.Russian; FlipClock.Lang['russian'] = FlipClock.Lang.Russian; }(jQuery)); (function($) { /** * FlipClock Swedish Language Pack * * This class will used to translate tokens into the Swedish language. * */ FlipClock.Lang.Swedish = { 'years' : 'År', 'months' : 'Månader', 'days' : 'Dagar', 'hours' : 'Timmar', 'minutes' : 'Minuter', 'seconds' : 'Sekunder' }; /* Create various aliases for convenience */ FlipClock.Lang['sv'] = FlipClock.Lang.Swedish; FlipClock.Lang['sv-se'] = FlipClock.Lang.Swedish; FlipClock.Lang['swedish'] = FlipClock.Lang.Swedish; }(jQuery)); (function($) { /** * FlipClock Chinese Language Pack * * This class will used to translate tokens into the Chinese language. * */ FlipClock.Lang.Chinese = { 'years' : '年', 'months' : '月', 'days' : '日', 'hours' : '时', 'minutes' : '分', 'seconds' : '秒' }; /* Create various aliases for convenience */ FlipClock.Lang['zh'] = FlipClock.Lang.Chinese; FlipClock.Lang['zh-cn'] = FlipClock.Lang.Chinese; FlipClock.Lang['chinese'] = FlipClock.Lang.Chinese; }(jQuery));<|fim▁end|>
<|file_name|>creator.d.ts<|end_file_name|><|fim▁begin|>/** !#en The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace. !#zh Cocos 引擎的主要命名空间,引擎代码中所有的类,函数,属性和常量都在这个命名空间中定义。 */ declare module cc { /** !#en Init Debug setting. !#zh 设置调试模式。 */ export function _initDebugSetting(mode : DebugMode) : void; /** !#en Outputs an error message to the Cocos Creator Console (editor) or Web Console (runtime).<br/> - In Cocos Creator, error is red.<br/> - In Chrome, error have a red icon along with red message text.<br/> !#zh 输出错误消息到 Cocos Creator 编辑器的 Console 或运行时页面端的 Console 中。<br/> - 在 Cocos Creator 中,错误信息显示是红色的。<br/> - 在 Chrome 中,错误信息有红色的图标以及红色的消息文本。<br/> @param obj A JavaScript string containing zero or more substitution strings. @param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ export function error(obj : any, subst : any) : void; /** !#en Outputs a warning message to the Cocos Creator Console (editor) or Web Console (runtime). - In Cocos Creator, warning is yellow. - In Chrome, warning have a yellow warning icon with the message text. !#zh 输出警告消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。<br/> - 在 Cocos Creator 中,警告信息显示是黄色的。<br/> - 在 Chrome 中,警告信息有着黄色的图标以及黄色的消息文本。<br/> @param obj A JavaScript string containing zero or more substitution strings. @param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ export function warn(obj : any, subst : any) : void; /** !#en Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). !#zh 输出一条消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。 @param obj A JavaScript string containing zero or more substitution strings. @param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ export function log(obj : any, subst : any) : void; /** !#en Outputs an informational message to the Cocos Creator Console (editor) or Web Console (runtime). - In Cocos Creator, info is blue. - In Firefox and Chrome, a small "i" icon is displayed next to these items in the Web Console's log. !#zh 输出一条信息消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。 - 在 Cocos Creator 中,Info 信息显示是蓝色的。<br/> - 在 Firefox 和 Chrome 中,Info 信息有着小 “i” 图标。 @param obj A JavaScript string containing zero or more substitution strings.<|fim▁hole|> */ export function info(obj : any, subst : any) : void; /** !#en Creates the speed action which changes the speed of an action, making it take longer (speed > 1) or less (speed < 1) time. <br/> Useful to simulate 'slow motion' or 'fast forward' effect. !#zh 修改目标动作的速率。 @example ```js // change the target action speed; var action = cc.scaleTo(0.2, 1, 0.6); var newAction = cc.speed(action, 0.5); ``` */ export function speed(action : ActionInterval, speed : number) : Action; /** !#en Create a follow action which makes its target follows another node. !#zh 追踪目标节点的位置。 @example ```js // example // creates the action with a set boundary var followAction = cc.follow(targetNode, cc.rect(0, 0, screenWidth * 2 - 100, screenHeight)); node.runAction(followAction); // creates the action with no boundary set var followAction = cc.follow(targetNode); node.runAction(followAction); ``` */ export function follow(followedNode : Node, rect : Rect) : Action; /** Points setter */ export function setPoints(points : any[]) : void; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按基数样条曲线轨迹移动到目标位置。 @param points array of control points @example ```js //create a cc.CardinalSplineTo var action1 = cc.cardinalSplineTo(3, array, 0); ``` */ export function cardinalSplineTo(duration : number, points : any[], tension : number) : ActionInterval; /** update position of target */ export function updatePosition(newPos : Vec2) : void; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按基数样条曲线轨迹移动指定的距离。 */ export function cardinalSplineBy(duration : number, points : any[], tension : number) : ActionInterval; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按 Catmull Rom 样条曲线轨迹移动到目标位置。 @example ```js var action1 = cc.catmullRomTo(3, array); ``` */ export function catmullRomTo(dt : number, points : any[]) : ActionInterval; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按 Catmull Rom 样条曲线轨迹移动指定的距离。 @example ```js var action1 = cc.catmullRomBy(3, array); ``` */ export function catmullRomBy(dt : number, points : any[]) : ActionInterval; /** !#en Creates the action easing object with the rate parameter. <br /> From slow to fast. !#zh 创建 easeIn 缓动对象,由慢到快。 @example ```js // example action.easing(cc.easeIn(3.0)); ``` */ export function easeIn(rate : number) : any; /** !#en Creates the action easing object with the rate parameter. <br /> From fast to slow. !#zh 创建 easeOut 缓动对象,由快到慢。 @example ```js // example action.easing(cc.easeOut(3.0)); ``` */ export function easeOut(rate : number) : any; /** !#en Creates the action easing object with the rate parameter. <br /> Slow to fast then to slow. !#zh 创建 easeInOut 缓动对象,慢到快,然后慢。 @example ```js //The new usage action.easing(cc.easeInOut(3.0)); ``` */ export function easeInOut(rate : number) : any; /** !#en Creates the action easing object with the rate parameter. <br /> Reference easeInExpo: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeExponentialIn 缓动对象。<br /> EaseExponentialIn 是按指数函数缓动进入的动作。<br /> 参考 easeInExpo:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeExponentialIn()); ``` */ export function easeExponentialIn() : any; /** !#en Creates the action easing object. <br /> Reference easeOutExpo: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeExponentialOut 缓动对象。<br /> EaseExponentialOut 是按指数函数缓动退出的动作。<br /> 参考 easeOutExpo:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeExponentialOut()); ``` */ export function easeExponentialOut() : any; /** !#en Creates an EaseExponentialInOut action easing object. <br /> Reference easeInOutExpo: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeExponentialInOut 缓动对象。<br /> EaseExponentialInOut 是按指数函数缓动进入并退出的动作。<br /> 参考 easeInOutExpo:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeExponentialInOut()); ``` */ export function easeExponentialInOut() : any; /** !#en Creates an EaseSineIn action. <br /> Reference easeInSine: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 EaseSineIn 缓动对象。<br /> EaseSineIn 是按正弦函数缓动进入的动作。<br /> 参考 easeInSine:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeSineIn()); ``` */ export function easeSineIn() : any; /** !#en Creates an EaseSineOut action easing object. <br /> Reference easeOutSine: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 EaseSineOut 缓动对象。<br /> EaseSineIn 是按正弦函数缓动退出的动作。<br /> 参考 easeOutSine:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeSineOut()); ``` */ export function easeSineOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInOutSine: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeSineInOut 缓动对象。<br /> EaseSineIn 是按正弦函数缓动进入并退出的动作。<br /> 参考 easeInOutSine:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeSineInOut()); ``` */ export function easeSineInOut() : any; /** !#en Creates the action easing obejct with the period in radians (default is 0.3). <br /> Reference easeInElastic: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeElasticIn 缓动对象。<br /> EaseElasticIn 是按弹性曲线缓动进入的动作。<br /> 参数 easeInElastic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeElasticIn(3.0)); ``` */ export function easeElasticIn(period : number) : any; /** !#en Creates the action easing object with the period in radians (default is 0.3). <br /> Reference easeOutElastic: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeElasticOut 缓动对象。<br /> EaseElasticOut 是按弹性曲线缓动退出的动作。<br /> 参考 easeOutElastic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeElasticOut(3.0)); ``` */ export function easeElasticOut(period : number) : any; /** !#en Creates the action easing object with the period in radians (default is 0.3). <br /> Reference easeInOutElastic: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeElasticInOut 缓动对象。<br /> EaseElasticInOut 是按弹性曲线缓动进入并退出的动作。<br /> 参考 easeInOutElastic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeElasticInOut(3.0)); ``` */ export function easeElasticInOut(period : number) : any; /** !#en Creates the action easing object. <br /> Eased bounce effect at the beginning. !#zh 创建 easeBounceIn 缓动对象。<br /> EaseBounceIn 是按弹跳动作缓动进入的动作。 @example ```js // example action.easing(cc.easeBounceIn()); ``` */ export function easeBounceIn() : any; /** !#en Creates the action easing object. <br /> Eased bounce effect at the ending. !#zh 创建 easeBounceOut 缓动对象。<br /> EaseBounceOut 是按弹跳动作缓动退出的动作。 @example ```js // example action.easing(cc.easeBounceOut()); ``` */ export function easeBounceOut() : any; /** !#en Creates the action easing object. <br /> Eased bounce effect at the begining and ending. !#zh 创建 easeBounceInOut 缓动对象。<br /> EaseBounceInOut 是按弹跳动作缓动进入并退出的动作。 @example ```js // example action.easing(cc.easeBounceInOut()); ``` */ export function easeBounceInOut() : any; /** !#en Creates the action easing object. <br /> In the opposite direction to move slowly, and then accelerated to the right direction. !#zh 创建 easeBackIn 缓动对象。<br /> easeBackIn 是在相反的方向缓慢移动,然后加速到正确的方向。<br /> @example ```js // example action.easing(cc.easeBackIn()); ``` */ export function easeBackIn() : any; /** !#en Creates the action easing object. <br /> Fast moving more than the finish, and then slowly back to the finish. !#zh 创建 easeBackOut 缓动对象。<br /> easeBackOut 快速移动超出目标,然后慢慢回到目标点。 @example ```js // example action.easing(cc.easeBackOut()); ``` */ export function easeBackOut() : any; /** !#en Creates the action easing object. <br /> Begining of cc.EaseBackIn. Ending of cc.EaseBackOut. !#zh 创建 easeBackInOut 缓动对象。<br /> @example ```js // example action.easing(cc.easeBackInOut()); ``` */ export function easeBackInOut() : any; /** !#en Creates the action easing object. <br /> Into the 4 reference point. <br /> To calculate the motion curve. !#zh 创建 easeBezierAction 缓动对象。<br /> EaseBezierAction 是按贝塞尔曲线缓动的动作。 @param p0 The first bezier parameter @param p1 The second bezier parameter @param p2 The third bezier parameter @param p3 The fourth bezier parameter @example ```js // example action.easing(cc.easeBezierAction(0.5, 0.5, 1.0, 1.0)); ``` */ export function easeBezierAction(p0 : number, p1 : number, p2 : number, p3 : number) : any; /** !#en Creates the action easing object. <br /> Reference easeInQuad: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuadraticActionIn 缓动对象。<br /> EaseQuadraticIn是按二次函数缓动进入的动作。<br /> 参考 easeInQuad:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionIn()); ``` */ export function easeQuadraticActionIn() : any; /** !#en Creates the action easing object. <br /> Reference easeOutQuad: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuadraticActionOut 缓动对象。<br /> EaseQuadraticOut 是按二次函数缓动退出的动作。<br /> 参考 easeOutQuad:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionOut()); ``` */ export function easeQuadraticActionOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInOutQuad: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuadraticActionInOut 缓动对象。<br /> EaseQuadraticInOut 是按二次函数缓动进入并退出的动作。<br /> 参考 easeInOutQuad:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionInOut()); ``` */ export function easeQuadraticActionInOut() : any; /** !#en Creates the action easing object. <br /> Reference easeIntQuart: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuarticActionIn 缓动对象。<br /> EaseQuarticIn 是按四次函数缓动进入的动作。<br /> 参考 easeIntQuart:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuarticActionIn()); ``` */ export function easeQuarticActionIn() : any; /** !#en Creates the action easing object. <br /> Reference easeOutQuart: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuarticActionOut 缓动对象。<br /> EaseQuarticOut 是按四次函数缓动退出的动作。<br /> 参考 easeOutQuart:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.QuarticActionOut()); ``` */ export function easeQuarticActionOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInOutQuart: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuarticActionInOut 缓动对象。<br /> EaseQuarticInOut 是按四次函数缓动进入并退出的动作。<br /> 参考 easeInOutQuart:http://www.zhihu.com/question/21981571/answer/19925418 */ export function easeQuarticActionInOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInQuint: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuinticActionIn 缓动对象。<br /> EaseQuinticIn 是按五次函数缓动进的动作。<br /> 参考 easeInQuint:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuinticActionIn()); ``` */ export function easeQuinticActionIn() : any; /** !#en Creates the action easing object. <br /> Reference easeOutQuint: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuinticActionOut 缓动对象。<br /> EaseQuinticOut 是按五次函数缓动退出的动作 参考 easeOutQuint:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionOut()); ``` */ export function easeQuinticActionOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInOutQuint: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuinticActionInOut 缓动对象。<br /> EaseQuinticInOut是按五次函数缓动进入并退出的动作。<br /> 参考 easeInOutQuint:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuinticActionInOut()); ``` */ export function easeQuinticActionInOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInCirc: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCircleActionIn 缓动对象。<br /> EaseCircleIn是按圆形曲线缓动进入的动作。<br /> 参考 easeInCirc:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCircleActionIn()); ``` */ export function easeCircleActionIn() : any; /** !#en Creates the action easing object. <br /> Reference easeOutCirc: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCircleActionOut 缓动对象。<br /> EaseCircleOut是按圆形曲线缓动退出的动作。<br /> 参考 easeOutCirc:http://www.zhihu.com/question/21981571/answer/19925418 */ export function easeCircleActionOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInOutCirc: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCircleActionInOut 缓动对象。<br /> EaseCircleInOut 是按圆形曲线缓动进入并退出的动作。<br /> 参考 easeInOutCirc:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCircleActionInOut()); ``` */ export function easeCircleActionInOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInCubic: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCubicActionIn 缓动对象。<br /> EaseCubicIn 是按三次函数缓动进入的动作。<br /> 参考 easeInCubic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCubicActionIn()); ``` */ export function easeCubicActionIn() : any; /** !#en Creates the action easing object. <br /> Reference easeOutCubic: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCubicActionOut 缓动对象。<br /> EaseCubicOut 是按三次函数缓动退出的动作。<br /> 参考 easeOutCubic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCubicActionOut()); ``` */ export function easeCubicActionOut() : any; /** !#en Creates the action easing object. <br /> Reference easeInOutCubic: <br /> http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCubicActionInOut 缓动对象。<br /> EaseCubicInOut是按三次函数缓动进入并退出的动作。<br /> 参考 easeInOutCubic:http://www.zhihu.com/question/21981571/answer/19925418 */ export function easeCubicActionInOut() : any; /** !#en Show the Node. !#zh 立即显示。 @example ```js // example var showAction = cc.show(); ``` */ export function show() : ActionInstant; /** !#en Hide the node. !#zh 立即隐藏。 @example ```js // example var hideAction = cc.hide(); ``` */ export function hide() : ActionInstant; /** !#en Toggles the visibility of a node. !#zh 显隐状态切换。 @example ```js // example var toggleVisibilityAction = cc.toggleVisibility(); ``` */ export function toggleVisibility() : ActionInstant; /** !#en Create a RemoveSelf object with a flag indicate whether the target should be cleaned up while removing. !#zh 从父节点移除自身。 @example ```js // example var removeSelfAction = cc.removeSelf(); ``` */ export function removeSelf(isNeedCleanUp : boolean) : ActionInstant; /** !#en Create a FlipX action to flip or unflip the target. !#zh X轴翻转。 @param flip Indicate whether the target should be flipped or not @example ```js var flipXAction = cc.flipX(true); ``` */ export function flipX(flip : boolean) : ActionInstant; /** !#en Create a FlipY action to flip or unflip the target. !#zh Y轴翻转。 @example ```js var flipYAction = cc.flipY(true); ``` */ export function flipY(flip : boolean) : ActionInstant; /** !#en Creates a Place action with a position. !#zh 放置在目标位置。 @example ```js // example var placeAction = cc.place(cc.p(200, 200)); var placeAction = cc.place(200, 200); ``` */ export function place(pos : Vec2|number, y? : number) : ActionInstant; /** !#en Creates the action with the callback. !#zh 执行回调函数。 @param data data for function, it accepts all data types. @example ```js // example // CallFunc without data var finish = cc.callFunc(this.removeSprite, this); // CallFunc with data var finish = cc.callFunc(this.removeFromParentAndCleanup, this._grossini, true); ``` */ export function callFunc(selector : Function, selectorTarget? : any|void, data? : any|void) : ActionInstant; /** !#en Helper constructor to create an array of sequenceable actions The created action will run actions sequentially, one after another. !#zh 顺序执行动作,创建的动作将按顺序依次运行。 @example ```js // example // create sequence with actions var seq = cc.sequence(act1, act2); // create sequence with array var seq = cc.sequence(actArray); ``` */ export function sequence(tempArray : any[]|FiniteTimeAction) : ActionInterval; /** !#en Creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30) !#zh 重复动作,可以按一定次数重复一个动,如果想永远重复一个动作请使用 repeatForever 动作来完成。 @example ```js // example var rep = cc.repeat(cc.sequence(jump2, jump1), 5); ``` */ export function repeat(action : FiniteTimeAction, times : number) : ActionInterval; /** !#en Create a acton which repeat forever, as it runs forever, it can't be added into cc.sequence and cc.spawn. !#zh 永远地重复一个动作,有限次数内重复一个动作请使用 repeat 动作,由于这个动作不会停止,所以不能被添加到 cc.sequence 或 cc.spawn 中。 @example ```js // example var repeat = cc.repeatForever(cc.rotateBy(1.0, 360)); ``` */ export function repeatForever(action : FiniteTimeAction) : ActionInterval; /** !#en Create a spawn action which runs several actions in parallel. !#zh 同步执行动作,同步执行一组动作。 @example ```js // example var action = cc.spawn(cc.jumpBy(2, cc.p(300, 0), 50, 4), cc.rotateBy(2, 720)); todo:It should be the direct use new ``` */ export function spawn(tempArray : any[]|FiniteTimeAction) : FiniteTimeAction; /** !#en Rotates a Node object to a certain angle by modifying its rotation property. <br/> The direction will be decided by the shortest angle. !#zh 旋转到目标角度,通过逐帧修改它的 rotation 属性,旋转方向将由最短的角度决定。 @param duration duration in seconds @param deltaAngleX deltaAngleX in degrees. @param deltaAngleY deltaAngleY in degrees. @example ```js // example var rotateTo = cc.rotateTo(2, 61.0); ``` */ export function rotateTo(duration : number, deltaAngleX : number, deltaAngleY? : number) : ActionInterval; /** !#en Rotates a Node object clockwise a number of degrees by modifying its rotation property. Relative to its properties to modify. !#zh 旋转指定的角度。 @param duration duration in seconds @param deltaAngleX deltaAngleX in degrees @param deltaAngleY deltaAngleY in degrees @example ```js // example var actionBy = cc.rotateBy(2, 360); ``` */ export function rotateBy(duration : number, deltaAngleX : number, deltaAngleY? : number) : ActionInterval; /** !#en Moves a Node object x,y pixels by modifying its position property. <br/> x and y are relative to the position of the object. <br/> Several MoveBy actions can be concurrently called, and the resulting <br/> movement will be the sum of individual movements. !#zh 移动指定的距离。 @param duration duration in seconds @example ```js // example var actionTo = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40)); ``` */ export function moveBy(duration : number, deltaPos : Vec2|number, deltaY : number) : ActionInterval; /** !#en Moves a Node object to the position x,y. x and y are absolute coordinates by modifying its position property. <br/> Several MoveTo actions can be concurrently called, and the resulting <br/> movement will be the sum of individual movements. !#zh 移动到目标位置。 @param duration duration in seconds @example ```js // example var actionBy = cc.moveTo(2, cc.p(80, 80)); ``` */ export function moveTo(duration : number, position : Vec2, y : number) : ActionInterval; /** !#en Create a action which skews a Node object to given angles by modifying its skewX and skewY properties. Changes to the specified value. !#zh 偏斜到目标角度。 @param t time in seconds @example ```js // example var actionTo = cc.skewTo(2, 37.2, -37.2); ``` */ export function skewTo(t : number, sx : number, sy : number) : ActionInterval; /** !#en Skews a Node object by skewX and skewY degrees. <br /> Relative to its property modification. !#zh 偏斜指定的角度。 @param t time in seconds @param sx sx skew in degrees for X axis @param sy sy skew in degrees for Y axis @example ```js // example var actionBy = cc.skewBy(2, 0, -90); ``` */ export function skewBy(t : number, sx : number, sy : number) : ActionInterval; /** !#en Moves a Node object simulating a parabolic jump movement by modifying it's position property. Relative to its movement. !#zh 用跳跃的方式移动指定的距离。 @example ```js // example var actionBy = cc.jumpBy(2, cc.p(300, 0), 50, 4); var actionBy = cc.jumpBy(2, 300, 0, 50, 4); ``` */ export function jumpBy(duration : number, position : Vec2|number, y? : number, height : number, jumps : number) : ActionInterval; /** !#en Moves a Node object to a parabolic position simulating a jump movement by modifying its position property. <br /> Jump to the specified location. !#zh 用跳跃的方式移动到目标位置。 @example ```js // example var actionTo = cc.jumpTo(2, cc.p(300, 300), 50, 4); var actionTo = cc.jumpTo(2, 300, 300, 50, 4); ``` */ export function jumpTo(duration : number, position : Vec2|number, y? : number, height : number, jumps : number) : ActionInterval; /** !#en An action that moves the target with a cubic Bezier curve by a certain distance. Relative to its movement. !#zh 按贝赛尔曲线轨迹移动指定的距离。 @param t time in seconds @param c Array of points @example ```js // example var bezier = [cc.p(0, windowSize.height / 2), cc.p(300, -windowSize.height / 2), cc.p(300, 100)]; var bezierForward = cc.bezierBy(3, bezier); ``` */ export function bezierBy(t : number, c : any[]) : ActionInterval; /** !#en An action that moves the target with a cubic Bezier curve to a destination point. !#zh 按贝赛尔曲线轨迹移动到目标位置。 @param c array of points @example ```js // example var bezier = [cc.p(0, windowSize.height / 2), cc.p(300, -windowSize.height / 2), cc.p(300, 100)]; var bezierTo = cc.bezierTo(2, bezier); ``` */ export function bezierTo(t : number, c : any[]) : ActionInterval; /** !#en Scales a Node object to a zoom factor by modifying it's scale property. !#zh 将节点大小缩放到指定的倍数。 @param sx scale parameter in X @param sy scale parameter in Y, if Null equal to sx @example ```js // example // It scales to 0.5 in both X and Y. var actionTo = cc.scaleTo(2, 0.5); // It scales to 0.5 in x and 2 in Y var actionTo = cc.scaleTo(2, 0.5, 2); ``` */ export function scaleTo(duration : number, sx : number, sy? : number) : ActionInterval; /** !#en Scales a Node object a zoom factor by modifying it's scale property. Relative to its changes. !#zh 按指定的倍数缩放节点大小。 @param duration duration in seconds @param sx sx scale parameter in X @param sy sy scale parameter in Y, if Null equal to sx @example ```js // example without sy, it scales by 2 both in X and Y var actionBy = cc.scaleBy(2, 2); //example with sy, it scales by 0.25 in X and 4.5 in Y var actionBy2 = cc.scaleBy(2, 0.25, 4.5); ``` */ export function scaleBy(duration : number, sx : number, sy? : number|void) : ActionInterval; /** !#en Blinks a Node object by modifying it's visible property. !#zh 闪烁(基于透明度)。 @param duration duration in seconds @param blinks blinks in times @example ```js // example var action = cc.blink(2, 10); ``` */ export function blink(duration : number, blinks : number) : ActionInterval; /** !#en Fades an object that implements the cc.RGBAProtocol protocol. It modifies the opacity from the current value to a custom one. !#zh 修改透明度到指定值。 @param opacity 0-255, 0 is transparent @example ```js // example var action = cc.fadeTo(1.0, 0); ``` */ export function fadeTo(duration : number, opacity : number) : ActionInterval; /** !#en Fades In an object that implements the cc.RGBAProtocol protocol. It modifies the opacity from 0 to 255. !#zh 渐显效果。 @param duration duration in seconds @example ```js //example var action = cc.fadeIn(1.0); ``` */ export function fadeIn(duration : number) : ActionInterval; /** !#en Fades Out an object that implements the cc.RGBAProtocol protocol. It modifies the opacity from 255 to 0. !#zh 渐隐效果。 @param d duration in seconds @example ```js // example var action = cc.fadeOut(1.0); ``` */ export function fadeOut(d : number) : ActionInterval; /** !#en Tints a Node that implements the cc.NodeRGB protocol from current tint to a custom one. !#zh 修改颜色到指定值。 @param red 0-255 @param green 0-255 @param blue 0-255 @example ```js // example var action = cc.tintTo(2, 255, 0, 255); ``` */ export function tintTo(duration : number, red : number, green : number, blue : number) : ActionInterval; /** !#en Tints a Node that implements the cc.NodeRGB protocol from current tint to a custom one. Relative to their own color change. !#zh 按照指定的增量修改颜色。 @param duration duration in seconds @example ```js // example var action = cc.tintBy(2, -127, -255, -127); ``` */ export function tintBy(duration : number, deltaRed : number, deltaGreen : number, deltaBlue : number) : ActionInterval; /** !#en Delays the action a certain amount of seconds. !#en 延迟指定的时间量。 @param d duration in seconds @example ```js // example var delay = cc.delayTime(1); ``` */ export function delayTime(d : number) : ActionInterval; /** !#en Executes an action in reverse order, from time=duration to time=0. !#zh 反转目标动作的时间轴。 @example ```js // example var reverse = cc.reverseTime(this); ``` */ export function reverseTime(action : FiniteTimeAction) : ActionInterval; /** !#en Create an action with the specified action and forced target. !#zh 用已有动作和一个新的目标节点创建动作。 */ export function targetedAction(target : Node, action : FiniteTimeAction) : ActionInterval; /** Constructor */ export function HashElement() : void; /** !#en cc.view is the shared view object. !#zh cc.view 是全局的视图对象。 */ export var view : View; /** !#en Director !#zh 导演类。 */ export var director : Director; /** !#en cc.winSize is the alias object for the size of the current game window. !#zh cc.winSize 为当前的游戏窗口的大小。 */ export var winSize : Size; export var game : Game; /** !#en Defines a CCClass using the given specification, please see [Class](/en/scripting/class/) for details. !#zh 定义一个 CCClass,传入参数必须是一个包含类型参数的字面量对象,具体用法请查阅[类型定义](/zh/scripting/class/)。 @example ```js // define base class var Node = cc.Class(); // define sub class var Sprite = cc.Class({ name: 'Sprite', extends: Node, ctor: function () { this.url = ""; this.id = 0; }, properties { width: { default: 128, type: 'Integer', tooltip: 'The width of sprite' }, height: 128, size: { get: function () { return cc.v2(this.width, this.height); } } }, load: function () { // load this.url }; }); // instantiate var obj = new Sprite(); obj.url = 'sprite.png'; obj.load(); // define static member Sprite.count = 0; Sprite.getBounds = function (spriteList) { // ... }; ``` */ export function Class(options : { name?; extends?; ctor?; properties?; statics?; mixins?; editor? : { requireComponent? : Component; disallowMultiple? : Component; menu? : string; executeInEditMode? : boolean; playOnFocus? : boolean; inspector? : string; icon? : string; help? : string; } ; update?; lateUpdate?; onLoad?; start?; onEnable?; onDisable?; onDestroy?; onFocusInEditor?; onLostFocusInEditor?; resetInEditor?; onRestore?; _getLocalBounds?; }) : Function; /** Checks whether subclass is child of superclass or equals to superclass */ export function isChildClassOf(subclass : Function, superclass : Function) : boolean; /** Return all super classes */ export function getInheritanceChain(constructor : Function) : Function[]; /** whether enable accelerometer event */ export function setAccelerometerEnabled(isEnable : boolean) : void; /** set accelerometer interval value */ export function setAccelerometerInterval(interval : number) : void; /** default gl blend src function. Compatible with premultiplied alpha images. */ export var BLEND_SRC : number; /** <p> Linear interpolation between 2 numbers, the ratio sets how much it is biased to each end </p> @param a number A @param b number B @param r ratio between 0 and 1 @example ```js ---- lerp cc.lerp(2,10,0.5)//returns 6 cc.lerp(2,10,0.2)//returns 3.6 ``` */ export function lerp(a : number, b : number, r : number) : void; /** get a random number from 0 to 0xffffff */ export function rand() : number; /** returns a random float between -1 and 1 */ export function randomMinus1To1() : number; /** returns a random float between 0 and 1, use Math.random directly */ export function random0To1() : number; /** converts degrees to radians */ export function degreesToRadians(angle : number) : number; /** converts radians to degrees */ export function radiansToDegrees(angle : number) : number; /** Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix @param node setup node */ export function nodeDrawSetup(node : Node) : void; /** <p> Increments the GL Draws counts by one.<br/> The number of calls per frame are displayed on the screen when the CCDirector's stats are enabled.<br/> </p> */ export function incrementGLDraws(addNumber : number) : void; /** Check webgl error.Error will be shown in console if exists. */ export function checkGLErrorDebug() : void; /** !#en Checks whether the object is non-nil and not yet destroyed. !#zh 检查该对象是否不为 null 并且尚未销毁。 @example ```js cc.log(cc.isValid(target)); ``` */ export function isValid(value : any) : boolean; /** Specify that the input value must be integer in Inspector. Also used to indicates that the elements in array should be type integer. */ export var Integer : string; /** Indicates that the elements in array should be type double. */ export var Float : string; /** Indicates that the elements in array should be type boolean. */ export var Boolean : string; /** Indicates that the elements in array should be type string. */ export var String : string; /** !#en Deserialize json to cc.Asset !#zh 将 JSON 反序列化为对象实例。 当指定了 target 选项时,如果 target 引用的其它 asset 的 uuid 不变,则不会改变 target 对 asset 的引用, 也不会将 uuid 保存到 result 对象中。 @param data the serialized cc.Asset json string or json object. @param result additional loading result */ export function deserialize(data : string|any, result? : Details, options? : any) : any; /** !#en Clones the object original and returns the clone. See [Clone exists Entity](/en/scripting/create-destroy-entities/#instantiate) !#zh 复制给定的对象 详细用法可参考[复制已有Entity](/zh/scripting/create-destroy-entities/#instantiate) Instantiate 时,function 和 dom 等非可序列化对象会直接保留原有引用,Asset 会直接进行浅拷贝,可序列化类型会进行深拷贝。 <del>对于 Entity / Component 等 Scene Object,如果对方也会被一起 Instantiate,则重定向到新的引用,否则保留为原来的引用。</del> @param original An existing object that you want to make a copy of. */ export function instantiate(original : any) : any; /** Finds a node by hierarchy path, the path is case-sensitive. It will traverse the hierarchy by splitting the path using '/' character. This function will still returns the node even if it is inactive. It is recommended to not use this function every frame instead cache the result at startup. */ export function find(path : string, referenceNode? : Node) : Node; /** !#en The convenience method to create a new {{#crossLink "Color/Color:method"}}cc.Color{{/crossLink}} Alpha channel is optional. Default value is 255. !#zh 通过该方法来创建一个新的 {{#crossLink "Color/Color:method"}}cc.Color{{/crossLink}} 对象。 Alpha 通道是可选的。默认值是 255。 @example ```js ----------------------- // 1. All channels seperately as parameters var color1 = new cc.Color(255, 255, 255, 255); // 2. Convert a hex string to a color var color2 = new cc.Color("#000000"); // 3. An color object as parameter var color3 = new cc.Color({r: 255, g: 255, b: 255, a: 255}); ``` */ export function color(r? : number, g? : number, b? : number, a? : number) : Color; /** !#en returns true if both ccColor3B are equal. Otherwise it returns false. !#zh 判断两个颜色对象的 RGB 部分是否相等,不比较透明度。 @example ```js cc.log(cc.colorEqual(cc.Color.RED, new cc.Color(255, 0, 0))); // true ``` */ export function colorEqual(color1: (r: number, g: number, b: number, a: number) => void, color2: (r: number, g: number, b: number, a: number) => void) : boolean; /** !#en convert a string of color for style to Color. e.g. "#ff06ff" to : cc.color(255,6,255)。 !#zh 16 进制转换为 Color @example ```js cc.hexToColor("#FFFF33"); // Color {r: 255, g: 255, b: 51, a: 255}; ``` */ export function hexToColor(hex : string) : Color; /** !#en convert Color to a string of color for style. e.g. cc.color(255,6,255) to : "#ff06ff" !#zh Color 转换为 16进制。 @example ```js var color = new cc.Color(255, 6, 255) cc.colorToHex(color); // #ff06ff; ``` */ export function colorToHex(color: (r: number, g: number, b: number, a: number) => void) : string; /** !#en Define an enum type. <br/> If a enum item has a value of -1, it will be given an Integer number according to it's order in the list.<br/> Otherwise it will use the value specified by user who writes the enum definition. !#zh 定义一个枚举类型。<br/> 用户可以把枚举值设为任意的整数,如果设为 -1,系统将会分配为上一个枚举值 + 1。 @param obj a JavaScript literal object containing enum names and values @example ```js var WrapMode = cc.Enum({ Repeat: -1, Clamp: -1 }); // Texture.WrapMode.Repeat == 0 // Texture.WrapMode.Clamp == 1 // Texture.WrapMode[0] == "Repeat" // Texture.WrapMode[1] == "Clamp" var FlagType = cc.Enum({ Flag1: 1, Flag2: 2, Flag3: 4, Flag4: 8, }); var AtlasSizeList = cc.Enum({ 128: 128, 256: 256, 512: 512, 1024: 1024, }); ``` */ export function Enum(obj : any) : any; /** !#en Returns opposite of Vec2. !#zh 返回相反的向量。 @example ```js cc.pNeg(cc.v2(10, 10));// Vec2 {x: -10, y: -10}; ``` */ export function pNeg(point : Vec2) : Vec2; /** !#en Calculates sum of two points. !#zh 返回两个向量的和。 @example ```js cc.pAdd(cc.v2(1, 1), cc.v2(2, 2));// Vec2 {x: 3, y: 3}; ``` */ export function pAdd(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Calculates difference of two points. !#zh 返回两个向量的差。 @example ```js cc.pSub(cc.v2(20, 20), cc.v2(5, 5)); // Vec2 {x: 15, y: 15}; ``` */ export function pSub(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Returns point multiplied by given factor. !#zh 向量缩放。 @example ```js cc.pMult(cc.v2(5, 5), 4); // Vec2 {x: 20, y: 20}; ``` */ export function pMult(point : Vec2, floatVar : number) : Vec2; /** !#en Calculates midpoint between two points. !#zh 两个向量之间的中心点。 @example ```js cc.pMidpoint(cc.v2(10, 10), cc.v2(5, 5)); // Vec2 {x: 7.5, y: 7.5}; ``` */ export function pMidpoint(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Calculates dot product of two points. !#zh 两个向量之间进行点乘。 @example ```js cc.pDot(cc.v2(20, 20), cc.v2(5, 5)); // 200; ``` */ export function pDot(v1 : Vec2, v2 : Vec2) : number; /** !#en Calculates cross product of two points. !#zh 两个向量之间进行叉乘。 @example ```js cc.pCross(cc.v2(20, 20), cc.v2(5, 5)); // 0; ``` */ export function pCross(v1 : Vec2, v2 : Vec2) : number; /** !#en Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) greater than 0. !#zh 返回逆时针旋转 90 度后的新向量。 @example ```js cc.pPerp(cc.v2(20, 20)); // Vec2 {x: -20, y: 20}; ``` */ export function pPerp(point : Vec2) : Vec2; /** !#en Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) smaller than 0. !#zh 将指定向量顺时针旋转 90 度并返回。 @example ```js cc.pRPerp(cc.v2(20, 20)); // Vec2 {x: 20, y: -20}; ``` */ export function pRPerp(point : Vec2) : Vec2; /** !#en Calculates the projection of v1 over v2. !#zh 返回 v1 在 v2 上的投影向量。 @example ```js var v1 = cc.v2(20, 20); var v2 = cc.v2(5, 5); cc.pProject(v1, v2); // Vec2 {x: 20, y: 20}; ``` */ export function pProject(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Calculates the square length of a cc.Vec2 (not calling sqrt() ). !#zh 返回指定向量长度的平方。 @example ```js cc.pLengthSQ(cc.v2(20, 20)); // 800; ``` */ export function pLengthSQ(v : Vec2) : number; /** !#en Calculates the square distance between two points (not calling sqrt() ). !#zh 返回两个点之间距离的平方。 @example ```js var point1 = cc.v2(20, 20); var point2 = cc.v2(5, 5); cc.pDistanceSQ(point1, point2); // 450; ``` */ export function pDistanceSQ(point1 : Vec2, point2 : Vec2) : number; /** !#en Calculates distance between point an origin. !#zh 返回指定向量的长度. @example ```js cc.pLength(cc.v2(20, 20)); // 28.284271247461902; ``` */ export function pLength(v : Vec2) : number; /** !#en Calculates the distance between two points. !#zh 返回指定 2 个向量之间的距离。 @example ```js var v1 = cc.v2(20, 20); var v2 = cc.v2(5, 5); cc.pDistance(v1, v2); // 21.213203435596427; ``` */ export function pDistance(v1 : Vec2, v2 : Vec2) : number; /** !#en Returns this vector with a magnitude of 1. !#zh 返回一个长度为 1 的标准化过后的向量。 @example ```js cc.pNormalize(cc.v2(20, 20)); // Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; ``` */ export function pNormalize(v : Vec2) : Vec2; /** !#en Converts radians to a normalized vector. !#zh 将弧度转换为一个标准化后的向量,返回坐标 x = cos(a) , y = sin(a)。 @example ```js cc.pForAngle(20); // Vec2 {x: 0.40808206181339196, y: 0.9129452507276277}; ``` */ export function pForAngle(a : number) : Vec2; /** !#en Converts a vector to radians. !#zh 返回指定向量的弧度。 @example ```js cc.pToAngle(cc.v2(20, 20)); // 0.7853981633974483; ``` */ export function pToAngle(v : Vec2) : number; /** !#en Clamp a value between from and to. !#zh 限定浮点数的最大最小值。<br/> 数值大于 max_inclusive 则返回 max_inclusive。<br/> 数值小于 min_inclusive 则返回 min_inclusive。<br/> 否则返回自身。 @example ```js var v1 = cc.clampf(20, 0, 20); // 20; var v2 = cc.clampf(-1, 0, 20); // 0; var v3 = cc.clampf(10, 0, 20); // 10; ``` */ export function clampf(value : number, min_inclusive : number, max_inclusive : number) : number; /** !#en Clamp a value between 0 and 1. !#zh 限定浮点数的取值范围为 0 ~ 1 之间。 @example ```js var v1 = cc.clampf(20); // 1; var v2 = cc.clampf(-1); // 0; var v3 = cc.clampf(0.5); // 0.5; ``` */ export function clamp01(value : number) : number; /** !#en Clamp a point between from and to. !#zh 返回指定限制区域后的向量。<br/> 向量大于 max_inclusive 则返回 max_inclusive。<br/> 向量小于 min_inclusive 则返回 min_inclusive。<br/> 否则返回自身。 @example ```js var min_inclusive = cc.v2(0, 0); var max_inclusive = cc.v2(20, 20); var v1 = cc.pClamp(cc.v2(20, 20), min_inclusive, max_inclusive); // Vec2 {x: 20, y: 20}; var v2 = cc.pClamp(cc.v2(0, 0), min_inclusive, max_inclusive); // Vec2 {x: 0, y: 0}; var v3 = cc.pClamp(cc.v2(10, 10), min_inclusive, max_inclusive); // Vec2 {x: 10, y: 10}; ``` */ export function pClamp(p : Vec2, min_inclusive : Vec2, max_inclusive : Vec2) : Vec2; /** !#en Quickly convert cc.Size to a cc.Vec2. !#zh 快速转换 cc.Size 为 cc.Vec2。 @example ```js cc.pFromSize(new cc.size(20, 20)); // Vec2 {x: 20, y: 20}; ``` */ export function pFromSize(s : Size) : Vec2; /** !#en Run a math operation function on each point component <br /> Math.abs, Math.fllor, Math.ceil, Math.round. !#zh 通过运行指定的数学运算函数来计算指定的向量。 @example ```js cc.pCompOp(cc.p(-10, -10), Math.abs); // Vec2 {x: 10, y: 10}; ``` */ export function pCompOp(p : Vec2, opFunc : Function) : Vec2; /** !#en Linear Interpolation between two points a and b.<br /> alpha == 0 ? a <br /> alpha == 1 ? b <br /> otherwise a value between a..b. !#zh 两个点 A 和 B 之间的线性插值。 <br /> alpha == 0 ? a <br /> alpha == 1 ? b <br /> 否则这个数值在 a ~ b 之间。 @example ```js cc.pLerp(cc.v2(20, 20), cc.v2(5, 5), 0.5); // Vec2 {x: 12.5, y: 12.5}; ``` */ export function pLerp(a : Vec2, b : Vec2, alpha : number) : Vec2; /** !#en TODO !#zh 近似判断两个点是否相等。<br/> 判断 2 个向量是否在指定数值的范围之内,如果在则返回 true,反之则返回 false。 @example ```js var a = cc.v2(20, 20); var b = cc.v2(5, 5); var b1 = cc.pFuzzyEqual(a, b, 10); // false; var b2 = cc.pFuzzyEqual(a, b, 18); // true; ``` */ export function pFuzzyEqual(a : Vec2, b : Vec2, variance : number) : boolean; /** !#en Multiplies a nd b components, a.x*b.x, a.y*b.y. !#zh 计算两个向量的每个分量的乘积, a.x * b.x, a.y * b.y。 @example ```js cc.pCompMult(acc.v2(20, 20), cc.v2(5, 5)); // Vec2 {x: 100, y: 100}; ``` */ export function pCompMult(a : Vec2, b : Vec2) : Vec2; /** !#en TODO !#zh 返回两个向量之间带正负号的弧度。 */ export function pAngleSigned(a : Vec2, b : Vec2) : number; /** !#en TODO !#zh 获取当前向量与指定向量之间的弧度角。 */ export function pAngle(a : Vec2, b : Vec2) : number; /** !#en Rotates a point counter clockwise by the angle around a pivot. !#zh 返回给定向量围绕指定轴心顺时针旋转一定弧度后的结果。 @param v v is the point to rotate @param pivot pivot is the pivot, naturally @param angle angle is the angle of rotation cw in radians */ export function pRotateByAngle(v : Vec2, pivot : Vec2, angle : number) : Vec2; /** !#en A general line-line intersection test indicating successful intersection of a line<br /> note that to truly test intersection for segments we have to make<br /> sure that s & t lie within [0..1] and for rays, make sure s & t > 0<br /> the hit point is p3 + t * (p4 - p3);<br /> the hit point also is p1 + s * (p2 - p1); !#zh 返回 A 为起点 B 为终点线段 1 所在直线和 C 为起点 D 为终点线段 2 所在的直线是否相交,<br /> 如果相交返回 true,反之则为 false,参数 retP 是返回交点在线段 1、线段 2 上的比例。 @param A A is the startpoint for the first line P1 = (p1 - p2). @param B B is the endpoint for the first line P1 = (p1 - p2). @param C C is the startpoint for the second line P2 = (p3 - p4). @param D D is the endpoint for the second line P2 = (p3 - p4). @param retP retP.x is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)), <br /> retP.y is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)). */ export function pLineIntersect(A : Vec2, B : Vec2, C : Vec2, D : Vec2, retP : Vec2) : boolean; /** !#en ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D. !#zh 返回线段 A - B 和线段 C - D 是否相交。 */ export function pSegmentIntersect(A : Vec2, B : Vec2, C : Vec2, D : Vec2) : boolean; /** !#en ccpIntersectPoint return the intersection point of line A-B, C-D. !#zh 返回线段 A - B 和线段 C - D 的交点。 */ export function pIntersectPoint(A : Vec2, B : Vec2, C : Vec2, D : Vec2) : Vec2; /** !#en check to see if both points are equal. !#zh 检查指定的 2 个向量是否相等。 @param A A ccp a @param B B ccp b to be compared */ export function pSameAs(A : Vec2, B : Vec2) : boolean; /** !#en sets the position of the point to 0. !#zh 设置指定向量归 0。 */ export function pZeroIn(v : Vec2) : void; /** !#en copies the position of one point to another. !#zh 令 v1 向量等同于 v2。 */ export function pIn(v1 : Vec2, v2 : Vec2) : void; /** !#en multiplies the point with the given factor (inplace). !#zh 向量缩放,结果保存到第一个向量。 */ export function pMultIn(point : Vec2, floatVar : number) : void; /** !#en subtracts one point from another (inplace). !#zh 向量减法,结果保存到第一个向量。 */ export function pSubIn(v1 : Vec2, v2 : Vec2) : void; /** !#en adds one point to another (inplace). !#zh 向量加法,结果保存到第一个向量。 */ export function pAddIn(v1 : Vec2, v2 : Vec2) : void; /** !#en normalizes the point (inplace). !#zh 规范化 v 向量,设置 v 向量长度为 1。 */ export function pNormalizeIn(v : Vec2) : void; /** !#en The convenience method to create a new Rect. see {{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} !#zh 该方法用来快速创建一个新的矩形。{{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} @example ```js var a = new cc.rect(0 , 0, 10, 0); ``` */ export function rect(x? : Number[]|number, y? : number, w? : number, h? : number) : Rect; /** !#en Check whether a rect's value equals to another. !#zh 判断两个矩形是否相等。 @param rect1 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rect2 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 5, 5); cc.rectEqualToRect(a, b); // false; var c = new cc.rect(0, 0, 5, 5); cc.rectEqualToRect(b, c); // true; ``` */ export function rectEqualToRect(rect1: (x: number, y: number, w: number, h: number) => void, rect2: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Check whether the rect1 contains rect2. !#zh 检查 rect1 矩形是否包含 rect2 矩形。 <br/> 注意:如果要允许 rect1 和 rect2 的边界重合,应该用 cc.rectOverlapsRect @param rect1 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rect2 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 20, 20); var b = new cc.rect(10, 10, 20, 20); cc.rectContainsRect(a, b); // true; ``` */ export function rectContainsRect(rect1: (x: number, y: number, w: number, h: number) => void, rect2: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Returns the rightmost x-value of a rect. !#zh 返回矩形在 x 轴上的最大值 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(10, 0, 20, 20); cc.rectGetMaxX(a); // 30; ``` */ export function rectGetMaxX(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the midpoint x-value of a rect. !#zh 返回矩形在 x 轴上的中点。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(10, 0, 20, 20); cc.rectGetMidX(a); // 20; ``` */ export function rectGetMidX(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Returns the leftmost x-value of a rect. !#zh 返回矩形在 x 轴上的最小值。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(10, 0, 20, 20); cc.rectGetMinX(a); // 10; ``` */ export function rectGetMinX(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the topmost y-value of a rect. !#zh 返回矩形在 y 轴上的最大值。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); cc.rectGetMaxY(a); // 30; ``` */ export function rectGetMaxY(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the midpoint y-value of `rect'. !#zh 返回矩形在 y 轴上的中点。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); cc.rectGetMidY(a); // 20; ``` */ export function rectGetMidY(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the bottommost y-value of a rect. !#zh 返回矩形在 y 轴上的最小值。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); cc.rectGetMinY(a); // 10; ``` */ export function rectGetMinY(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Check whether a rect contains a point. !#zh 检查一个矩形是否包含某个坐标点。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = cc.v2(0, 10, 10, 10); cc.rectContainsPoint(a, b); // true; ``` */ export function rectContainsPoint(rect: (x: number, y: number, w: number, h: number) => void, point : Vec2) : boolean; /** !#en Check whether a rect intersect with another. !#zh 检查一个矩形是否与另一个相交。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectIntersectsRect(a, b); // true; ``` */ export function rectIntersectsRect(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Check whether a rect overlaps another. !#zh 检查一个矩形是否重叠另一个。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectOverlapsRect(a, b); // true; ``` */ export function rectOverlapsRect(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Returns the smallest rectangle that contains the two source rectangles. !#zh 返回一个包含两个指定矩形的最小矩形。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectUnion(a, b); // Rect {x: 0, y: 10, width: 20, height: 20}; ``` */ export function rectUnion(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : Rect; /** !#en Returns the overlapping portion of 2 rectangles. !#zh 返回 2 个矩形重叠的部分。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectIntersection(a, b); // Rect {x: 0, y: 10, width: 10, height: 10}; ``` */ export function rectIntersection(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : Rect; export function V3F_C4B_T2F_QuadZero() : V3F_C4B_T2F_Quad; /** */ export function V3F_C4B_T2F_QuadCopy(sourceQuad: (tl: V3F_C4B_T2F, bl: V3F_C4B_T2F, tr: V3F_C4B_T2F, br: V3F_C4B_T2F, arrayBuffer: any[], offset: number) => void) : V3F_C4B_T2F_Quad; /** */ export function V3F_C4B_T2F_QuadsCopy(sourceQuads : any[]) : any[]; /** !#en The convenience method to create a new {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}}. !#zh 通过该简便的函数进行创建 {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}} 对象。 @example ```js var v1 = cc.v2(); var v2 = cc.v2(0, 0); var v3 = cc.v2(v2); var v4 = cc.v2({x: 100, y: 100}); ``` */ export function v2(x? : number|any, y? : number) : Vec2; /** !#en The convenience method to creates a new {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}}. !#zh 通过该简便的函数进行创建 {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}} 对象。 @param x a Number or a size object @example ```js var point1 = cc.p(); var point2 = cc.p(100, 100); var point3 = cc.p(point2); var point4 = cc.p({x: 100, y: 100}); ``` */ export function p(x? : number|any, y? : number) : Vec2; /** !#en Check whether a point's value equals to another. !#zh 判断两个向量是否相等。 @param point1 !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param point2 !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ export function pointEqualToPoint(point1: (x: number, y: number) => void, point2: (x: number, y: number) => void) : boolean; /** !#en Enum for debug modes. !#zh 调试模式 */ export enum DebugMode { NONE = 0, INFO = 0, WARN = 0, ERROR = 0, INFO_FOR_WEB_PAGE = 0, WARN_FOR_WEB_PAGE = 0, ERROR_FOR_WEB_PAGE = 0, } /** !#en Class for animation data handling. !#zh 动画剪辑,用于存储动画数据。 */ export class AnimationClip extends Asset { /** !#en Duration of this animation. !#zh 动画的持续时间。 */ duration : number; /** !#en FrameRate of this animation. !#zh 动画的帧速率。 */ sample : number; /** !#en Speed of this animation. !#zh 动画的播放速度。 */ speed : number; /** !#en WrapMode of this animation. !#zh 动画的循环模式。 */ wrapMode : WrapMode; /** !#en Curve data. !#zh 曲线数据。 */ curveData : any; /** !#en Event data. !#zh 事件数据。 */ events : any[]; /** !#en Crate clip with a set of sprite frames !#zh 使用一组序列帧图片来创建动画剪辑 @example ```js var clip = cc.AnimationClip.createWithSpriteFrames(spriteFrames, 10); ``` */ createWithSpriteFrames(spriteFrames : [SpriteFrame], sample : number) : AnimationClip; } /** !#en The AnimationState gives full control over animation playback process. In most cases the Animation Component is sufficient and easier to use. Use the AnimationState if you need full control. !#zh AnimationState 完全控制动画播放过程。<br/> 大多数情况下 动画组件 是足够和易于使用的。如果您需要更多的动画控制接口,请使用 AnimationState。 */ export class AnimationState extends AnimationNode { /** */ AnimationState(clip : AnimationClip, name? : string) : AnimationState; /** !#en The clip that is being played by this animation state. !#zh 此动画状态正在播放的剪辑。 */ clip : AnimationClip; /** !#en The name of the playing animation. !#zh 动画的名字 */ name : string; } /** undefined */ export class Playable { /** !#en Is playing or paused in play mode? !#zh 当前是否正在播放。 */ isPlaying : boolean; /** !#en Is currently paused? This can be true even if in edit mode(isPlaying == false). !#zh 当前是否正在暂停 */ isPaused : boolean; /** !#en Play this animation. !#zh 播放动画。 */ play() : void; /** !#en Stop this animation. !#zh 停止动画播放。 */ stop() : void; /** !#en Pause this animation. !#zh 暂停动画。 */ pause() : void; /** !#en Resume this animation. !#zh 重新播放动画。 */ resume() : void; /** !#en Perform a single frame step. !#zh 执行一帧动画。 */ step() : void; } /** !#en Specifies how time is treated when it is outside of the keyframe range of an Animation. !#zh 动画使用的循环模式。 */ export enum WrapMode { Default = 0, Normal = 0, Reverse = 0, Loop = 0, LoopReverse = 0, PingPong = 0, PingPongReverse = 0, } /** !#en The abstract interface for all playing animation. !#zh 所有播放动画的抽象接口。 */ export class AnimationNodeBase extends Playable { } /** !#en The collection and instance of playing animations. !#zh 动画曲线的集合,根据当前时间计算出每条曲线的状态。 */ export class AnimationNode extends AnimationNodeBase { /** !#en The curves list. !#zh 曲线列表。 */ curves : AnimCurve[]; /** !#en The start delay which represents the number of seconds from an animation's start time to the start of the active interval. !#zh 延迟多少秒播放。 */ delay : number; /** !#en The animation's iteration count property. A real number greater than or equal to zero (including positive infinity) representing the number of times to repeat the animation node. Values less than zero and NaN values are treated as the value 1.0 for the purpose of timing model calculations. !#zh 迭代次数,指动画播放多少次后结束, normalize time。 如 2.5(2次半) */ repeatCount : number; /** !#en The iteration duration of this animation in seconds. (length) !#zh 单次动画的持续时间,秒。 */ duration : number; /** !#en The animation's playback speed. 1 is normal playback speed. !#zh 播放速率。 */ speed : number; /** !#en Wrapping mode of the playing animation. Notice : dynamic change wrapMode will reset time and repeatCount property !#zh 动画循环方式。 需要注意的是,动态修改 wrapMode 时,会重置 time 以及 repeatCount */ wrapMode : WrapMode; /** !#en The current time of this animation in seconds. !#zh 动画当前的时间,秒。 */ time : number; } /** !#en Base class cc.Action for action classes. !#zh Action 类是所有动作类型的基类。 */ export class Action { /** !#en to copy object with deep copy. returns a clone of action. !#zh 返回一个克隆的动作。 */ clone() : Action; /** !#en return true if the action has finished. !#zh 如果动作已完成就返回 true。 */ isDone() : boolean; /** !#en get the target. !#zh 获取当前目标节点。 */ getTarget() : Node; /** !#en The action will modify the target properties. !#zh 设置目标节点。 */ setTarget(target : Node) : void; /** !#en get the original target. !#zh 获取原始目标节点。 */ getOriginalTarget() : Node; /** !#en get tag number. !#zh 获取用于识别动作的标签。 */ getTag() : number; /** !#en set tag number. !#zh 设置标签,用于识别动作。 */ setTag(tag : number) : void; /** !#en Default Action tag. !#zh 默认动作标签。 */ TAG_INVALID : number; } /** !#en Base class actions that do have a finite time duration. <br/> Possible actions: <br/> - An action with a duration of 0 seconds. <br/> - An action with a duration of 35.5 seconds. Infinite time actions are valid !#zh 有限时间动作,这种动作拥有时长 duration 属性。 */ export class FiniteTimeAction extends Action { /** !#en get duration of the action. (seconds). !#zh 获取动作以秒为单位的持续时间。 */ getDuration() : number; /** !#en set duration of the action. (seconds). !#zh 设置动作以秒为单位的持续时间。 */ setDuration(duration : number) : void; /** !#en Returns a reversed action. <br /> For example: <br /> - The action will be x coordinates of 0 move to 100. <br /> - The reversed action will be x of 100 move to 0. - Will be rewritten !#zh 返回一个新的动作,执行与原动作完全相反的动作。 */ reverse() : void; /** !#en to copy object with deep copy. returns a clone of action. !#zh 返回一个克隆的动作。 */ clone() : FiniteTimeAction; } /** !#en Base class for Easing actions. !#zh 所有缓动动作基类,用于修饰 ActionInterval。 */ export class ActionEase extends ActionInterval { } /** !#en Base class for Easing actions with rate parameters !#zh 拥有速率属性的缓动动作基类。 */ export class EaseRateAction extends ActionEase { } /** !#en Ease Elastic abstract class. !#zh 弹性缓动动作基类。 */ export class EaseElastic extends ActionEase { } /** !#en cc.EaseBounce abstract class. !#zh 反弹缓动动作基类。 */ export class EaseBounce extends ActionEase { } /** !#en Instant actions are immediate actions. They don't have a duration like the ActionInterval actions. !#zh 即时动作,这种动作立即就会执行,继承自 FiniteTimeAction。 */ export class ActionInstant extends FiniteTimeAction { } /** !#en <p> An interval action is an action that takes place within a certain period of time. <br/> It has an start time, and a finish time. The finish time is the parameter<br/> duration plus the start time.</p> <p>These CCActionInterval actions have some interesting properties, like:<br/> - They can run normally (default) <br/> - They can run reversed with the reverse method <br/> - They can run with the time altered with the Accelerate, AccelDeccel and Speed actions. </p> <p>For example, you can simulate a Ping Pong effect running the action normally and<br/> then running it again in Reverse mode. </p> !#zh 时间间隔动作,这种动作在已定时间内完成,继承 FiniteTimeAction。 */ export class ActionInterval extends FiniteTimeAction { /** !#en Implementation of ease motion. !#zh 缓动运动。 @example action.easing(cc.easeIn(3.0));,```js action.easing(cc.easeIn(3.0)); ``` */ easing(easeObj : any) : ActionInterval; /** !#en Repeats an action a number of times. To repeat an action forever use the CCRepeatForever action. !#zh 重复动作可以按一定次数重复一个动作,使用 RepeatForever 动作来永远重复一个动作。 */ repeat(times : void) : ActionInterval; /** !#en Repeats an action for ever. <br/> To repeat the an action for a limited number of times use the Repeat action. <br/> !#zh 永远地重复一个动作,有限次数内重复一个动作请使用 Repeat 动作。 */ repeatForever() : ActionInterval; } /** !#en cc.MotionStreak manages a Ribbon based on it's motion in absolute space. <br/> You construct it with a fadeTime, minimum segment size, texture path, texture <br/> length and color. The fadeTime controls how long it takes each vertex in <br/> the streak to fade out, the minimum segment size it how many pixels the <br/> streak will move before adding a new ribbon segment, and the texture <br/> length is the how many pixels the texture is stretched across. The texture <br/> is vertically aligned along the streak segment. !#zh 运动轨迹,用于游戏对象的运动轨迹上实现拖尾渐隐效果。 */ export class MotionStreak extends Component { /** !#en !#zh 在编辑器模式下预览拖尾效果。 */ preview : boolean; /** !#en The fade time to fade. !#zh 拖尾的渐隐时间,以秒为单位。 */ fadeTime : number; /** !#en The minimum segment size. !#zh 拖尾之间最小距离。 */ minSeg : number; /** !#en The stroke's width. !#zh 拖尾的宽度。 */ stroke : number; /** !#en The texture of the MotionStreak. !#zh 拖尾的贴图。 */ texture : Texture2D; /** !#en The color of the MotionStreak. !#zh 拖尾的颜色 */ color : Color; /** !#en The fast Mode. !#zh 是否启用了快速模式。当启用快速模式,新的点会被更快地添加,但精度较低。 */ fastMode : boolean; /** !#en Remove all living segments of the ribbon. !#zh 删除当前所有的拖尾片段。 @example ```js // stop particle system. myParticleSystem.stopSystem(); ``` */ reset() : void; } /** !#en cc.audioEngine is the singleton object, it provide simple audio APIs. !#zh cc.audioengine是单例对象。<br/> 主要用来播放音频,播放的时候会返回一个 audioID,之后都可以通过这个 audioID 来操作这个音频对象。<br/> 不使用的时候,请使用 cc.audioEngine.uncache(filePath); 进行资源释放 <br/> 注意:<br/> 在 Android 系统浏览器上,不同浏览器,不同版本的效果不尽相同。<br/> 比如说:大多数浏览器都需要用户物理交互才可以开始播放音效,有一些不支持 WebAudio,<br/> 有一些不支持多音轨播放。总之如果对音乐依赖比较强,请做尽可能多的测试。 */ export class audioEngine { /** !#en Play audio. !#zh 播放音频 @param filePath The path of the audio file without filename extension. @param loop Whether the music loop or not. @param volume Volume size. @example ```js //example var audioID = cc.audioEngine.play(path, false, 0.5); ``` */ play(filePath : string, loop : boolean, volume : number) : number; /** !#en Set audio loop. !#zh 设置音频是否循环。 @param audioID audio id. @param loop Whether cycle. @example ```js //example cc.audioEngine.setLoop(id, true); ``` */ setLoop(audioID : number, loop : boolean) : void; /** !#en Get audio cycle state. !#zh 获取音频的循环状态。 @param audioID audio id. @example ```js //example cc.audioEngine.isLoop(id); ``` */ isLoop(audioID : number) : boolean; /** !#en Set the volume of audio. !#zh 设置音量(0.0 ~ 1.0)。 @param audioID audio id. @param volume Volume must be in 0.0~1.0 . @example ```js //example cc.audioEngine.setVolume(id, 0.5); ``` */ setVolume(audioID : number, volume : number) : void; /** !#en The volume of the music max value is 1.0,the min value is 0.0 . !#zh 获取音量(0.0 ~ 1.0)。 @param audioID audio id. @example ```js //example var volume = cc.audioEngine.getVolume(id); ``` */ getVolume(audioID : number) : boolean; /** !#en Set current time !#zh 设置当前的音频时间。 @param audioID audio id. @param sec current time. @example ```js //example cc.audioEngine.setCurrentTime(id, 2); ``` */ setCurrentTime(audioID : number, sec : number) : boolean; /** !#en Get current time !#zh 获取当前的音频播放时间。 @param audioID audio id. @example ```js //example var time = cc.audioEngine.getCurrentTime(id); ``` */ getCurrentTime(audioID : number) : number; /** !#en Get audio duration !#zh 获取音频总时长。 @param audioID audio id. @example ```js //example var time = cc.audioEngine.getDuration(id); ``` */ getDuration(audioID : number) : number; /** !#en Get audio state !#zh 获取音频状态。 @param audioID audio id. @example ```js //example var state = cc.audioEngine.getState(id); ``` */ getState(audioID : number) : audioEngine.AudioState; /** !#en Set Audio finish callback !#zh 设置一个音频结束后的回调 @param audioID audio id. @param callback loaded callback. @example ```js //example cc.audioEngine.setFinishCallback(id, function () {}); ``` */ setFinishCallback(audioID : number, callback : Function) : void; /** !#en Pause playing audio. !#zh 暂停正在播放音频。 @param audioID The return value of function play. @example ```js //example cc.audioEngine.pause(audioID); ``` */ pause(audioID : number) : void; /** !#en Pause all playing audio !#zh 暂停现在正在播放的所有音频。 @example ```js //example cc.audioEngine.pauseAll(); ``` */ pauseAll() : void; /** !#en Resume playing audio. !#zh 恢复播放指定的音频。 @param audioID The return value of function play. //example cc.audioEngine.resume(audioID); */ resume(audioID : number) : void; /** !#en Resume all playing audio. !#zh 恢复播放所有之前暂停的所有音频。 @example ```js //example cc.audioEngine.resumeAll(); ``` */ resumeAll() : void; /** !#en Stop playing audio. !#zh 停止播放指定音频。 @param audioID The return value of function play. @example ```js //example cc.audioEngine.stop(audioID); ``` */ stop(audioID : number) : void; /** !#en Stop all playing audio. !#zh 停止正在播放的所有音频。 @example ```js //example cc.audioEngine.stopAll(); ``` */ stopAll() : void; /** !#en Set up an audio can generate a few examples. !#zh 设置一个音频可以设置几个实例 @param num a number of instances to be created from within an audio @example ```js //example cc.audioEngine.setMaxAudioInstance(20); ``` */ setMaxAudioInstance(num : number) : void; /** !#en Getting audio can produce several examples. !#zh 获取一个音频可以设置几个实例 @example ```js //example cc.audioEngine.getMaxAudioInstance(); ``` */ getMaxAudioInstance() : number; /** !#en Unload the preloaded audio from internal buffer. !#zh 卸载预加载的音频。 @example ```js //example cc.audioEngine.uncache(filePath); ``` */ uncache(filePath : string) : void; /** !#en Unload all audio from internal buffer. !#zh 卸载所有音频。 @example ```js //example cc.audioEngine.uncacheAll(); ``` */ uncacheAll() : void; /** !#en Preload audio file. !#zh 预加载一个音频 @param filePath The file path of an audio. @param callback The callback of an audio. @example ```js //example cc.audioEngine.preload(path); ``` */ preload(filePath : void, callback : void) : void; /** !#en Set a size, the unit is KB,Over this size is directly resolved into DOM nodes !#zh 设置一个以kb为单位的尺寸,大于这个尺寸的音频在加载的时候会强制使用 dom 方式加载 @param kb The file path of an audio. @example ```js //example cc.audioEngine.setMaxWebAudioSize(300); ``` */ setMaxWebAudioSize(kb : void) : void; } /** Particle System base class. <br/> Attributes of a Particle System:<br/> - emmision rate of the particles<br/> - Gravity Mode (Mode A): <br/> - gravity <br/> - direction <br/> - speed +- variance <br/> - tangential acceleration +- variance<br/> - radial acceleration +- variance<br/> - Radius Mode (Mode B): <br/> - startRadius +- variance <br/> - endRadius +- variance <br/> - rotate +- variance <br/> - Properties common to all modes: <br/> - life +- life variance <br/> - start spin +- variance <br/> - end spin +- variance <br/> - start size +- variance <br/> - end size +- variance <br/> - start color +- variance <br/> - end color +- variance <br/> - life +- variance <br/> - blending function <br/> - texture <br/> <br/> cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).<br/> 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, <br/> cocos2d uses a another approach, but the results are almost identical.<br/> cocos2d supports all the variables used by Particle Designer plus a bit more: <br/> - spinning particles (supported when using ParticleSystem) <br/> - tangential acceleration (Gravity mode) <br/> - radial acceleration (Gravity mode) <br/> - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) <br/> It is possible to customize any of the above mentioned properties in runtime. Example: <br/> */ export class ParticleSystem extends _RendererUnderSG { /** !#en Play particle in edit mode. !#zh 在编辑器模式下预览粒子,启用后选中粒子时,粒子将自动播放。 */ preview : boolean; /** !#en If set custom to true, then use custom properties insteadof read particle file. !#zh 是否自定义粒子属性。 */ custom : boolean; /** !#en The plist file. !#zh plist 格式的粒子配置文件。 */ file : string; /** . */ texture : Texture2D; /** !#en Current quantity of particles that are being simulated. !#zh 当前播放的粒子数量。 */ particleCount : number; /** !#en Specify the source Blend Factor. !#zh 指定原图混合模式。 */ srcBlendFactor : BlendFactor; /** !#en Specify the destination Blend Factor. !#zh 指定目标的混合模式。 */ dstBlendFactor : BlendFactor; /** !#en If set to true, the particle system will automatically start playing on onLoad. !#zh 如果设置为 true 运行时会自动发射粒子。 */ playOnLoad : boolean; /** !#en Indicate whether the owner node will be auto-removed when it has no particles left. !#zh 粒子播放完毕后自动销毁所在的节点。 */ autoRemoveOnFinish : boolean; /** !#en Indicate whether the particle system is activated. !#zh 是否激活粒子。 */ active : boolean; /** !#en Maximum particles of the system. !#zh 粒子最大数量。 */ totalParticles : number; /** !#en How many seconds the emitter wil run. -1 means 'forever'. !#zh 发射器生存时间,单位秒,-1表示持续发射。 */ duration : number; /** !#en Emission rate of the particles. !#zh 每秒发射的粒子数目。 */ emissionRate : number; /** !#en Life of each particle setter. !#zh 粒子的运行时间。 */ life : number; /** !#en Variation of life. !#zh 粒子的运行时间变化范围。 */ lifeVar : number; /** !#en Start color of each particle. !#zh 粒子初始颜色。 */ startColor : Color; /** !#en Variation of the start color. !#zh 粒子初始颜色变化范围。 */ startColorVar : Color; /** !#en Ending color of each particle. !#zh 粒子结束颜色。 */ endColor : Color; /** !#en Variation of the end color. !#zh 粒子结束颜色变化范围。 */ endColorVar : Color; /** !#en Angle of each particle setter. !#zh 粒子角度。 */ angle : number; /** !#en Variation of angle of each particle setter. !#zh 粒子角度变化范围。 */ angleVar : number; /** !#en Start size in pixels of each particle. !#zh 粒子的初始大小。 */ startSize : number; /** !#en Variation of start size in pixels. !#zh 粒子初始大小的变化范围。 */ startSizeVar : number; /** !#en End size in pixels of each particle. !#zh 粒子结束时的大小。 */ endSize : number; /** !#en Variation of end size in pixels. !#zh 粒子结束大小的变化范围。 */ endSizeVar : number; /** !#en Start angle of each particle. !#zh 粒子开始自旋角度。 */ startSpin : number; /** !#en Variation of start angle. !#zh 粒子开始自旋角度变化范围。 */ startSpinVar : number; /** !#en End angle of each particle. !#zh 粒子结束自旋角度。 */ endSpin : number; /** !#en Variation of end angle. !#zh 粒子结束自旋角度变化范围。 */ endSpinVar : number; /** !#en Source position of the emitter. !#zh 发射器位置。 */ sourcePos : Vec2; /** !#en Variation of source position. !#zh 发射器位置的变化范围。(横向和纵向) */ posVar : Vec2; /** !#en Particles movement type. !#zh 粒子位置类型。 */ positionType : ParticleSystem.PositionType; /** !#en Particles emitter modes. !#zh 发射器类型。 */ emitterMode : ParticleSystem.EmitterMode; /** !#en Gravity of the emitter. !#zh 重力。 */ gravity : Vec2; /** !#en Speed of the emitter. !#zh 速度。 */ speed : number; /** !#en Variation of the speed. !#zh 速度变化范围。 */ speedVar : number; /** !#en Tangential acceleration of each particle. Only available in 'Gravity' mode. !#zh 每个粒子的切向加速度,即垂直于重力方向的加速度,只有在重力模式下可用。 */ tangentialAccel : number; /** !#en Variation of the tangential acceleration. !#zh 每个粒子的切向加速度变化范围。 */ tangentialAccelVar : number; /** !#en Acceleration of each particle. Only available in 'Gravity' mode. !#zh 粒子径向加速度,即平行于重力方向的加速度,只有在重力模式下可用。 */ radialAccel : number; /** !#en Variation of the radial acceleration. !#zh 粒子径向加速度变化范围。 */ radialAccelVar : number; /** !#en Indicate whether the rotation of each particle equals to its direction. Only available in 'Gravity' mode. !#zh 每个粒子的旋转是否等于其方向,只有在重力模式下可用。 */ rotationIsDir : boolean; /** !#en Starting radius of the particles. Only available in 'Radius' mode. !#zh 初始半径,表示粒子出生时相对发射器的距离,只有在半径模式下可用。 */ startRadius : number; /** !#en Variation of the starting radius. !#zh 初始半径变化范围。 */ startRadiusVar : number; /** !#en Ending radius of the particles. Only available in 'Radius' mode. !#zh 结束半径,只有在半径模式下可用。 */ endRadius : number; /** !#en Variation of the ending radius. !#zh 结束半径变化范围。 */ endRadiusVar : number; /** !#en Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. !#zh 粒子每秒围绕起始点的旋转角度,只有在半径模式下可用。 */ rotatePerS : number; /** !#en Variation of the degress to rotate a particle around the source pos per second. !#zh 粒子每秒围绕起始点的旋转角度变化范围。 */ rotatePerSVar : number; /** !#en The Particle emitter lives forever. !#zh 表示发射器永久存在 */ DURATION_INFINITY : number; /** !#en The starting size of the particle is equal to the ending size. !#zh 表示粒子的起始大小等于结束大小。 */ START_SIZE_EQUAL_TO_END_SIZE : number; /** !#en The starting radius of the particle is equal to the ending radius. !#zh 表示粒子的起始半径等于结束半径。 */ START_RADIUS_EQUAL_TO_END_RADIUS : number; /** !#en Add a particle to the emitter. !#zh 添加一个粒子到发射器中。 */ addParticle() : boolean; /** !#en Stop emitting particles. Running particles will continue to run until they die. !#zh 停止发射器发射粒子,发射出去的粒子将继续运行,直至粒子生命结束。 @example ```js // stop particle system. myParticleSystem.stopSystem(); ``` */ stopSystem() : void; /** !#en Kill all living particles. !#zh 杀死所有存在的粒子,然后重新启动粒子发射器。 @example ```js // play particle system. myParticleSystem.resetSystem(); ``` */ resetSystem() : void; /** !#en Whether or not the system is full. !#zh 发射器中粒子是否大于等于设置的总粒子数量。 */ isFull() : boolean; /** !#en <p> Sets a new CCSpriteFrame as particle.</br> WARNING: this method is experimental. Use setTextureWithRect instead. </p> !#zh <p> 设置一个新的精灵帧为粒子。</br> 警告:这个函数只是试验,请使用 setTextureWithRect 实现。 </p> */ setDisplayFrame(spriteFrame : SpriteFrame) : void; /** !#en Sets a new texture with a rect. The rect is in texture position and size. !#zh 设置一张新贴图和关联的矩形。 */ setTextureWithRect(texture : Texture2D, rect : Rect) : void; } /** !#en cc.ActionManager is a class that can manage actions.<br/> Normally you won't need to use this class directly. 99% of the cases you will use the CCNode interface, which uses this class's singleton object. But there are some cases where you might need to use this class. <br/> Examples:<br/> - When you want to run an action where the target is different from a CCNode.<br/> - When you want to pause / resume the actions<br/> !#zh cc.ActionManager 是可以管理动作的单例类。<br/> 通常你并不需要直接使用这个类,99%的情况您将使用 CCNode 的接口。<br/> 但也有一些情况下,您可能需要使用这个类。 <br/> 例如: - 当你想要运行一个动作,但目标不是 CCNode 类型时。 <br/> - 当你想要暂停/恢复动作时。 <br/> */ export class ActionManager { /** !#en Adds an action with a target.<br/> If the target is already present, then the action will be added to the existing target. If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target. When the target is paused, the queued actions won't be 'ticked'. !#zh 增加一个动作,同时还需要提供动作的目标对象,目标对象是否暂停作为参数。<br/> 如果目标已存在,动作将会被直接添加到现有的节点中。<br/> 如果目标不存在,将为这一目标创建一个新的实例,并将动作添加进去。<br/> 当目标状态的 paused 为 true,动作将不会被执行 */ addAction(action : Action, target : Node, paused : boolean) : void; /** !#en Removes all actions from all the targets. !#zh 移除所有对象的所有动作。 */ removeAllActions() : void; /** !#en Removes all actions from a certain target. <br/> All the actions that belongs to the target will be removed. !#zh 移除指定对象上的所有动作。<br/> 属于该目标的所有的动作将被删除。 */ removeAllActionsFromTarget(target : any, forceDelete : boolean) : void; /** !#en Removes an action given an action reference. !#zh 移除指定的动作。 */ removeAction(action : Action) : void; /** !#en Removes an action given its tag and the target. !#zh 删除指定对象下特定标签的一个动作,将删除首个匹配到的动作。 */ removeActionByTag(tag : number, target : any) : void; /** !#en Gets an action given its tag an a target. !#zh 通过目标对象和标签获取一个动作。 */ getActionByTag(tag : number, target : any) : Action; /** !#en Returns the numbers of actions that are running in a certain target. <br/> Composable actions are counted as 1 action. <br/> Example: <br/> - If you are running 1 Sequence of 7 actions, it will return 1. <br/> - If you are running 7 Sequences of 2 actions, it will return 7. !#zh 返回指定对象下所有正在运行的动作数量。 <br/> 组合动作被算作一个动作。<br/> 例如:<br/> - 如果您正在运行 7 个动作组成的序列动作(Sequence),这个函数将返回 1。<br/> - 如果你正在运行 2 个序列动作(Sequence)和 5 个普通动作,这个函数将返回 7。<br/> */ getNumberOfRunningActionsInTarget(target : any) : number; /** !#en Pauses the target: all running actions and newly added actions will be paused. !#zh 暂停指定对象:所有正在运行的动作和新添加的动作都将会暂停。 */ pauseTarget(target : any) : void; /** !#en Resumes the target. All queued actions will be resumed. !#zh 让指定目标恢复运行。在执行序列中所有被暂停的动作将重新恢复运行。 */ resumeTarget(target : any) : void; /** !#en Pauses all running actions, returning a list of targets whose actions were paused. !#zh 暂停所有正在运行的动作,返回一个包含了那些动作被暂停了的目标对象的列表。 */ pauseAllRunningActions() : any[]; /** !#en Resume a set of targets (convenience function to reverse a pauseAllRunningActions or pauseTargets call). !#zh 让一组指定对象恢复运行(用来逆转 pauseAllRunningActions 效果的便捷函数)。 */ resumeTargets(targetsToResume : any[]) : void; /** !#en Pause a set of targets. !#zh 暂停一组指定对象。 */ pauseTargets(targetsToPause : any[]) : void; /** !#en purges the shared action manager. It releases the retained instance. <br/> because it uses this, so it can not be static. !#zh 清除共用的动作管理器。它释放了持有的实例。 <br/> 因为它使用 this,因此它不能是静态的。 */ purgeSharedManager() : void; /** !#en The ActionManager update。 !#zh ActionManager 主循环。 @param dt delta time in seconds */ update(dt : number) : void; } /** !#en <p> ATTENTION: USE cc.director INSTEAD OF cc.Director.<br/> cc.director is a singleton object which manage your game's logic flow.<br/> Since the cc.director is a singleton, you don't need to call any constructor or create functions,<br/> the standard way to use it is by calling:<br/> - cc.director.methodName(); <br/> It creates and handle the main Window and manages how and when to execute the Scenes.<br/> <br/> The cc.director is also responsible for:<br/> - initializing the OpenGL context<br/> - setting the OpenGL pixel format (default on is RGB565)<br/> - setting the OpenGL buffer depth (default on is 0-bit)<br/> - setting the color for clear screen (default one is BLACK)<br/> - setting the projection (default one is 3D)<br/> - setting the orientation (default one is Portrait)<br/> <br/> <br/> The cc.director also sets the default OpenGL context:<br/> - GL_TEXTURE_2D is enabled<br/> - GL_VERTEX_ARRAY is enabled<br/> - GL_COLOR_ARRAY is enabled<br/> - GL_TEXTURE_COORD_ARRAY is enabled<br/> </p> <p> cc.director also synchronizes timers with the refresh rate of the display.<br/> Features and Limitations:<br/> - Scheduled timers & drawing are synchronizes with the refresh rate of the display<br/> - Only supports animation intervals of 1/60 1/30 & 1/15<br/> </p> !#zh <p> 注意:用 cc.director 代替 cc.Director。<br/> cc.director 一个管理你的游戏的逻辑流程的单例对象。<br/> 由于 cc.director 是一个单例,你不需要调用任何构造函数或创建函数,<br/> 使用它的标准方法是通过调用:<br/> - cc.director.methodName(); <br/> 它创建和处理主窗口并且管理什么时候执行场景。<br/> <br/> cc.director 还负责:<br/> - 初始化 OpenGL 环境。<br/> - 设置OpenGL像素格式。(默认是 RGB565)<br/> - 设置OpenGL缓冲区深度 (默认是 0-bit)<br/> - 设置空白场景的颜色 (默认是 黑色)<br/> - 设置投影 (默认是 3D)<br/> - 设置方向 (默认是 Portrait)<br/> <br/> cc.director 设置了 OpenGL 默认环境 <br/> - GL_TEXTURE_2D 启用。<br/> - GL_VERTEX_ARRAY 启用。<br/> - GL_COLOR_ARRAY 启用。<br/> - GL_TEXTURE_COORD_ARRAY 启用。<br/> </p> <p> cc.director 也同步定时器与显示器的刷新速率。 <br/> 特点和局限性: <br/> - 将计时器 & 渲染与显示器的刷新频率同步。<br/> - 只支持动画的间隔 1/60 1/30 & 1/15。<br/> </p> */ export class Director { /** !#en Converts an OpenGL coordinate to a view coordinate<br/> Useful to convert node points to window points for calls such as glScissor<br/> Implementation can be found in CCDirectorWebGL. !#zh 将触摸点的 WebGL View 坐标转换为屏幕坐标。 */ convertToUI(glPoint : Vec2) : Vec2; /** !#en Returns the size of the WebGL view in points.<br/> It takes into account any possible rotation (device orientation) of the window. !#zh 获取视图的大小,以点为单位。 */ getWinSize() : Size; /** !#en Returns the size of the OpenGL view in pixels.<br/> It takes into account any possible rotation (device orientation) of the window.<br/> On Mac winSize and winSizeInPixels return the same value. !#zh 获取视图大小,以像素为单位。 */ getWinSizeInPixels() : Size; /** !#en Returns the visible size of the running scene. !#zh 获取运行场景的可见大小。 */ getVisibleSize() : Size; /** !#en Returns the visible origin of the running scene. !#zh 获取视图在游戏内容中的坐标原点。 */ getVisibleOrigin() : Vec2; /** !#en Pause the director's ticker, only involve the game logic execution. It won't pause the rendering process nor the event manager. If you want to pause the entier game including rendering, audio and event, please use {{#crossLink "Game.pause"}}cc.game.pause{{/crossLink}} !#zh 暂停正在运行的场景,该暂停只会停止游戏逻辑执行,但是不会停止渲染和 UI 响应。 如果想要更彻底得暂停游戏,包含渲染,音频和事件,请使用 {{#crossLink "Game.pause"}}cc.game.pause{{/crossLink}}。 */ pause() : void; /** !#en Run a scene. Replaces the running scene with a new one or enter the first scene.<br/> The new scene will be launched immediately. !#zh 立刻切换指定场景。 @param scene The need run scene. @param onBeforeLoadScene The function invoked at the scene before loading. @param onLaunched The function invoked at the scene after launch. */ runSceneImmediate(scene : Scene, onBeforeLoadScene? : Function, onLaunched? : Function) : void; /** !#en Loads the scene by its name. !#zh 通过场景名称进行加载场景。 @param sceneName The name of the scene to load. @param onLaunched callback, will be called after scene launched. */ loadScene(sceneName : string, onLaunched? : Function) : boolean; /** !#en Preloads the scene to reduces loading time. You can call this method at any time you want. After calling this method, you still need to launch the scene by `cc.director.loadScene`. It will be totally fine to call `cc.director.loadScene` at any time even if the preloading is not yet finished, the scene will be launched after loaded automatically. !#zh 预加载场景,你可以在任何时候调用这个方法。 调用完后,你仍然需要通过 `cc.director.loadScene` 来启动场景,因为这个方法不会执行场景加载操作。 就算预加载还没完成,你也可以直接调用 `cc.director.loadScene`,加载完成后场景就会启动。 @param sceneName The name of the scene to preload. @param onLoaded callback, will be called after scene loaded. */ preloadScene(sceneName : string, onLoaded: (error: Error) => void) : void; /** !#en Resume game logic execution after pause, if the current scene is not paused, nothing will happen. !#zh 恢复暂停场景的游戏逻辑,如果当前场景没有暂停将没任何事情发生。 */ resume() : void; /** !#en Enables or disables WebGL depth test.<br/> Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js !#zh 启用/禁用深度测试(在 Canvas 渲染模式下不会生效)。 */ setDepthTest(on : boolean) : void; /** !#en set color for clear screen.<br/> Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js !#zh 设置场景的默认擦除颜色(支持白色全透明,但不支持透明度为中间值)。 */ setClearColor(clearColor : Color) : void; /** !#en Sets an OpenGL projection.<br/> Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 设置 OpenGL 投影。 */ setProjection(projection : number) : void; /** !#en Update the view port.<br/> Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 设置视窗(请不要主动调用这个接口,除非你知道你在做什么)。 */ setViewport() : void; /** !#en Sets an OpenGL projection.<br/> Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 获取 OpenGL 投影。 */ getProjection() : number; /** !#en Enables/disables OpenGL alpha blending.<br/> Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 启用/禁用 透明度融合。 */ setAlphaBlending(on : boolean) : void; /** !#en Returns whether or not the replaced scene will receive the cleanup message.<br/> If the new scene is pushed, then the old scene won't receive the "cleanup" message.<br/> If the new scene replaces the old one, the it will receive the "cleanup" message. !#zh 更换场景时是否接收清理消息。<br> 如果新场景是采用 push 方式进入的,那么旧的场景将不会接收到 “cleanup” 消息。<br/> 如果新场景取代旧的场景,它将会接收到 “cleanup” 消息。</br> */ isSendCleanupToScene() : boolean; /** !#en Returns current logic Scene. !#zh 获取当前逻辑场景。 @example ```js // This will help you to get the Canvas node in scene cc.director.getScene().getChildByName('Canvas'); ``` */ getScene() : Scene; /** !#en Returns the FPS value. !#zh 获取单位帧执行时间。 */ getAnimationInterval() : number; /** !#en Returns whether or not to display the FPS informations. !#zh 获取是否显示 FPS 信息。 */ isDisplayStats() : boolean; /** !#en Sets whether display the FPS on the bottom-left corner. !#zh 设置是否在左下角显示 FPS。 */ setDisplayStats(displayStats : boolean) : void; /** !#en Returns seconds per frame. !#zh 获取实际记录的上一帧执行时间,可能与单位帧执行时间(AnimationInterval)有出入。 */ getSecondsPerFrame() : number; /** !#en Returns whether next delta time equals to zero. !#zh 返回下一个 “delta time” 是否等于零。 */ isNextDeltaTimeZero() : boolean; /** !#en Returns whether or not the Director is paused. !#zh 是否处于暂停状态。 */ isPaused() : boolean; /** !#en Returns how many frames were called since the director started. !#zh 获取 director 启动以来游戏运行的总帧数。 */ getTotalFrames() : number; /** !#en Returns the cc.Scheduler associated with this director. !#zh 获取和 director 相关联的 cc.Scheduler。 */ getScheduler() : Scheduler; /** !#en Sets the cc.Scheduler associated with this director. !#zh 设置和 director 相关联的 cc.Scheduler。 */ setScheduler(scheduler : Scheduler) : void; /** !#en Returns the cc.ActionManager associated with this director. !#zh 获取和 director 相关联的 cc.ActionManager(动作管理器)。 */ getActionManager() : ActionManager; /** !#en Sets the cc.ActionManager associated with this director. !#zh 设置和 director 相关联的 cc.ActionManager(动作管理器)。 */ setActionManager(actionManager : ActionManager) : void; /** Returns the cc.CollisionManager associated with this director. */ getCollisionManager() : CollisionManager; /** !#en Returns the delta time since last frame. !#zh 获取上一帧的 “delta time”。 */ getDeltaTime() : number; } /** !#en cc.game is the singleton object for game related functions. !#zh cc.game 是 Game 的实例,用来驱动整个游戏。 */ export class Game { /** Event triggered when game hide to background. Please note that this event is not 100% guaranteed to be fired. */ EVENT_HIDE : string; /** Event triggered when game back to foreground Please note that this event is not 100% guaranteed to be fired. */ EVENT_SHOW : string; /** Event triggered after game inited, at this point all engine objects and game scripts are loaded */ EVENT_GAME_INITED : string; /** Event triggered after renderer inited, at this point you will be able to use the render context */ EVENT_RENDERER_INITED : string; /** Key of config */ CONFIG_KEY : any; /** !#en The outer frame of the game canvas, parent of cc.container. !#zh 游戏画布的外框,cc.container 的父类。 */ frame : any; /** !#en The container of game canvas, equals to cc.container. !#zh 游戏画布的容器。 */ container : any; /** !#en The canvas of the game, equals to cc._canvas. !#zh 游戏的画布。 */ canvas : any; /** !#en The current game configuration, including:<br/> 1. debugMode<br/> "debugMode" possible values :<br/> 0 - No message will be printed. <br/> 1 - cc.error, cc.assert, cc.warn, cc.log will print in console. <br/> 2 - cc.error, cc.assert, cc.warn will print in console. <br/> 3 - cc.error, cc.assert will print in console. <br/> 4 - cc.error, cc.assert, cc.warn, cc.log will print on canvas, available only on web.<br/> 5 - cc.error, cc.assert, cc.warn will print on canvas, available only on web. <br/> 6 - cc.error, cc.assert will print on canvas, available only on web. <br/> 2. showFPS<br/> Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide.<br/> 3. exposeClassName<br/> Expose class name to chrome debug tools, the class intantiate performance is a little bit slower when exposed.<br/> 4. frameRate<br/> "frameRate" set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment.<br/> 5. id<br/> "gameCanvas" sets the id of your canvas element on the web page, it's useful only on web.<br/> 6. renderMode<br/> "renderMode" sets the renderer type, only useful on web :<br/> 0 - Automatically chosen by engine<br/> 1 - Forced to use canvas renderer<br/> 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers<br/> 7. scenes<br/> "scenes" include available scenes in the current bundle.<br/> <br/> Please DO NOT modify this object directly, it won't have any effect.<br/> !#zh 当前的游戏配置,包括: <br/> 1. debugMode(debug 模式,但是在浏览器中这个选项会被忽略) <br/> "debugMode" 各种设置选项的意义。 <br/> 0 - 没有消息被打印出来。 <br/> 1 - cc.error,cc.assert,cc.warn,cc.log 将打印在 console 中。 <br/> 2 - cc.error,cc.assert,cc.warn 将打印在 console 中。 <br/> 3 - cc.error,cc.assert 将打印在 console 中。 <br/> 4 - cc.error,cc.assert,cc.warn,cc.log 将打印在 canvas 中(仅适用于 web 端)。 <br/> 5 - cc.error,cc.assert,cc.warn 将打印在 canvas 中(仅适用于 web 端)。 <br/> 6 - cc.error,cc.assert 将打印在 canvas 中(仅适用于 web 端)。 <br/> 2. showFPS(显示 FPS) <br/> 当 showFPS 为 true 的时候界面的左下角将显示 fps 的信息,否则被隐藏。 <br/> 3. exposeClassName <br/> 暴露类名让 Chrome DevTools 可以识别,如果开启会稍稍降低类的创建过程的性能,但对对象构造没有影响。 <br/> 4. frameRate (帧率) <br/> “frameRate” 设置想要的帧率你的游戏,但真正的FPS取决于你的游戏实现和运行环境。 <br/> 5. id <br/> "gameCanvas" Web 页面上的 Canvas Element ID,仅适用于 web 端。 <br/> 6. renderMode(渲染模式) <br/> “renderMode” 设置渲染器类型,仅适用于 web 端: <br/> 0 - 通过引擎自动选择。 <br/> 1 - 强制使用 canvas 渲染。 2 - 强制使用 WebGL 渲染,但是在部分 Android 浏览器中这个选项会被忽略。 <br/> 7. scenes <br/> “scenes” 当前包中可用场景。 <br/> <br/> 注意:请不要直接修改这个对象,它不会有任何效果。 */ config : any; /** !#en Callback when the scripts of engine have been load. !#zh 当引擎完成启动后的回调函数。 */ onStart() : void; /** !#en Set frameRate of game. !#zh 设置游戏帧率。 */ setFrameRate(frameRate : number) : void; /** !#en Run the game frame by frame. !#zh 执行一帧游戏循环。 */ step() : void; /** !#en Pause the game main loop. This will pause: game logic execution, rendering process, event manager, background music and all audio effects. This is different with cc.director.pause which only pause the game logic execution. !#zh 暂停游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。这点和只暂停游戏逻辑的 cc.director.pause 不同。 */ pause() : void; /** !#en Resume the game from pause. This will resume: game logic execution, rendering process, event manager, background music and all audio effects. !#zh 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。 */ resume() : void; /** !#en Check whether the game is paused. !#zh 判断游戏是否暂停。 */ isPaused() : boolean; /** !#en Restart game. !#zh 重新开始游戏 */ restart() : void; /** !#en End game, it will close the game window !#zh 退出游戏 */ end() : void; /** !#en Prepare game. !#zh 准备引擎,请不要直接调用这个函数。 */ prepare(cb : Function) : void; /** !#en Run game with configuration object and onStart function. !#zh 运行游戏,并且指定引擎配置和 onStart 的回调。 @param config Pass configuration object or onStart function @param onStart function to be executed after game initialized */ run(config? : any|Function, onStart? : Function) : void; /** !#en Add a persistent root node to the game, the persistent node won't be destroyed during scene transition.<br/> The target node must be placed in the root level of hierarchy, otherwise this API won't have any effect. !#zh 声明常驻根节点,该节点不会被在场景切换中被销毁。<br/> 目标节点必须位于为层级的根节点,否则无效。 @param node The node to be made persistent */ addPersistRootNode(node : Node) : void; /** !#en Remove a persistent root node. !#zh 取消常驻根节点。 @param node The node to be removed from persistent node list */ removePersistRootNode(node : Node) : void; /** !#en Check whether the node is a persistent root node. !#zh 检查节点是否是常驻根节点。 @param node The node to be checked */ isPersistRootNode(node : Node) : boolean; } /** !#en cc.Scene is a subclass of cc.Node that is used only as an abstract concept.<br/> cc.Scene and cc.Node are almost identical with the difference that users can not modify cc.Scene manually. !#zh cc.Scene 是 cc.Node 的子类,仅作为一个抽象的概念。<br/> cc.Scene 和 cc.Node 有点不同,用户不应直接修改 cc.Scene。 */ export class Scene extends _BaseNode { /** !#en Indicates whether all (directly or indirectly) static referenced assets of this scene are releasable by default after scene unloading. !#zh 指示该场景中直接或间接静态引用到的所有资源是否默认在场景切换后自动释放。 */ autoReleaseAssets : boolean; } /** !#en Class of all entities in Cocos Creator scenes.<br/> Node also inherits from {{#crossLink "EventTarget"}}Event Target{{/crossLink}}, it permits Node to dispatch events. For events supported by Node, please refer to {{#crossLink "Node.EventType"}}{{/crossLink}} !#zh Cocos Creator 场景中的所有节点类。节点也继承了 {{#crossLink "EventTarget"}}EventTarget{{/crossLink}},它允许节点发送事件。<br/> 支持的节点事件,请参阅 {{#crossLink "Node.EventType"}}{{/crossLink}}。 */ export class Node extends _BaseNode { /** !#en The local active state of this node.<br/> Note that a Node may be inactive because a parent is not active, even if this returns true.<br/> Use {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}} if you want to check if the Node is actually treated as active in the scene. !#zh 当前节点的自身激活状态。<br/> 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。<br/> 如果你想检查节点在场景中实际的激活状态可以使用 {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}}。 */ active : boolean; /** !#en Indicates whether this node is active in the scene. !#zh 表示此节点是否在场景中激活。 */ activeInHierarchy : boolean; /** !#en Group index of node.<br/> Which Group this node belongs to will resolve that this node's collision components can collide with which other collision componentns.<br/> !#zh 节点的分组索引。<br/> 节点的分组将关系到节点的碰撞组件可以与哪些碰撞组件相碰撞。<br/> */ groupIndex : Integer; /** !#en Group of node.<br/> Which Group this node belongs to will resolve that this node's collision components can collide with which other collision componentns.<br/> !#zh 节点的分组。<br/> 节点的分组将关系到节点的碰撞组件可以与哪些碰撞组件相碰撞。<br/> */ group : string; /** !#en Returns the component of supplied type if the node has one attached, null if it doesn't.<br/> You can also get component in the node by passing in the name of the script. !#zh 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。<br/> 传入参数也可以是脚本的名称。 @example ```js // get sprite component. var sprite = node.getComponent(cc.Sprite); // get custom test calss. var test = node.getComponent("Test"); ``` */ getComponent(typeOrClassName : Function|string) : Component; /** !#en Returns all components of supplied type in the node. !#zh 返回节点上指定类型的所有组件。 @example ```js var sprites = node.getComponents(cc.Sprite); var tests = node.getComponents("Test"); ``` */ getComponents(typeOrClassName : Function|string) : Component[]; /** !#en Returns the component of supplied type in any of its children using depth first search. !#zh 递归查找所有子节点中第一个匹配指定类型的组件。 @example ```js var sprite = node.getComponentInChildren(cc.Sprite); var Test = node.getComponentInChildren("Test"); ``` */ getComponentInChildren(typeOrClassName : Function|string) : Component; /** !#en Returns all components of supplied type in self or any of its children. !#zh 递归查找自身或所有子节点中指定类型的组件 @example ```js var sprites = node.getComponentsInChildren(cc.Sprite); var tests = node.getComponentsInChildren("Test"); ``` */ getComponentsInChildren(typeOrClassName : Function|string) : Component[]; /** !#en Adds a component class to the node. You can also add component to node by passing in the name of the script. !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 @param typeOrClassName The constructor or the class name of the component to add @example ```js var sprite = node.addComponent(cc.Sprite); var test = node.addComponent("Test"); ``` */ addComponent(typeOrClassName : Function|string) : Component; /** !#en Removes a component identified by the given name or removes the component object given. You can also use component.destroy() if you already have the reference. !#zh 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 如果你已经获得组件引用,你也可以直接调用 component.destroy() @param component The need remove component. @example ```js node.removeComponent(cc.Sprite); var Test = require("Test"); node.removeComponent(Test); ``` */ removeComponent(component : string|Function|Component) : void; /** !#en Register a callback of a specific event type on Node.<br/> Use this method to register touch or mouse event permit propagation based on scene graph, you can propagate the event to the parents or swallow it by calling stopPropagation on the event.<br/> It's the recommended way to register touch/mouse event for Node, please do not use cc.eventManager directly for Node. !#zh 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的调用者。<br/> 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。<br/> 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。 @param type A string representing the event type to listen for.<br> See {{#crossLink "Node/position-changed:event"}}Node Events{{/crossLink}} for all builtin events. @param callback The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). @param target The target to invoke the callback, can be null @param useCapture When set to true, the capture argument prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. @example ```js this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. node.on(cc.Node.EventType.TOUCH_START, callback, this.node); node.on(cc.Node.EventType.TOUCH_MOVE, callback, this.node); node.on(cc.Node.EventType.TOUCH_END, callback, this.node); node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this.node); node.on("anchor-changed", callback, this); ``` */ on(type : string, callback: (param: Event) => void, target? : any, useCapture : boolean) : Function; /** !#en Removes the callback previously registered with the same type, callback, target and or useCapture. This method is merely an alias to removeEventListener. !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。 @param type A string representing the event type being removed. @param callback The callback to remove. @param target The target to invoke the callback, if it's not given, only callback without target will be removed @param useCapture Specifies whether the callback being removed was registered as a capturing callback or not. If not specified, useCapture defaults to false. If a callback was registered twice, one with capture and one without, each must be removed separately. Removal of a capturing callback does not affect a non-capturing version of the same listener, and vice versa. @example ```js this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this); node.off(cc.Node.EventType.TOUCH_START, callback, this.node); node.off("anchor-changed", callback, this); ``` */ off(type : string, callback : Function, target? : any, useCapture : boolean) : void; /** !#en Removes all callbacks previously registered with the same target. !#zh 移除目标上的所有注册事件。 @param target The target to be searched for all related callbacks @example ```js node.targetOff(target); ``` */ targetOff(target : any) : void; /** !#en Executes an action, and returns the action that is executed.<br/> The node becomes the action's target. Refer to cc.Action's getTarget() <br/> Calling runAction while the node is not active won't have any effect. <br/> Note:You shouldn't modify the action after runAction, that won't take any effect.<br/> if you want to modify, when you define action plus. !#zh 执行并返回该执行的动作。该节点将会变成动作的目标。<br/> 调用 runAction 时,节点自身处于不激活状态将不会有任何效果。<br/> 注意:你不应该修改 runAction 后的动作,将无法发挥作用,如果想进行修改,请在定义 action 时加入。 @example ```js var action = cc.scaleTo(0.2, 1, 0.6); node.runAction(action); node.runAction(action).repeatForever(); // fail node.runAction(action.repeatForever()); // right ``` */ runAction(action : Action) : Action; /** !#en Stops and removes all actions from the running action list . !#zh 停止并且移除所有正在运行的动作列表。 @example ```js node.stopAllActions(); ``` */ stopAllActions() : void; /** !#en Stops and removes an action from the running action list. !#zh 停止并移除指定的动作。 @param action An action object to be removed. @example ```js var action = cc.scaleTo(0.2, 1, 0.6); node.stopAction(action); ``` */ stopAction(action : Action) : void; /** !#en Removes an action from the running action list by its tag. !#zh 停止并且移除指定标签的动作。 @param tag A tag that indicates the action to be removed. @example ```js node.stopAction(1); ``` */ stopActionByTag(tag : number) : void; /** !#en Returns an action from the running action list by its tag. !#zh 通过标签获取指定动作。 @example ```js var action = node.getActionByTag(1); ``` */ getActionByTag(tag : number) : Action; /** !#en Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays).<br/> Composable actions are counted as 1 action. Example:<br/> If you are running 1 Sequence of 7 actions, it will return 1. <br/> If you are running 7 Sequences of 2 actions, it will return 7.</p> !#zh 获取运行着的动作加上正在调度运行的动作的总数。<br/> 例如:<br/> - 如果你正在运行 7 个动作中的 1 个 Sequence,它将返回 1。<br/> - 如果你正在运行 2 个动作中的 7 个 Sequence,它将返回 7。<br/> @example ```js var count = node.getNumberOfRunningActions(); cc.log("Running Action Count: " + count); ``` */ getNumberOfRunningActions() : number; } /** !#en Scheduler is responsible of triggering the scheduled callbacks.<br/> You should not use NSTimer. Instead use this class.<br/> <br/> There are 2 different types of callbacks (selectors):<br/> - update callback: the 'update' callback will be called every frame. You can customize the priority.<br/> - custom callback: A custom callback will be called every frame, or with a custom interval of time<br/> <br/> The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update callback'. * !#zh Scheduler 是负责触发回调函数的类。<br/> 通常情况下,建议使用 cc.director.getScheduler() 来获取系统定时器。<br/> 有两种不同类型的定时器:<br/> - update 定时器:每一帧都会触发。您可以自定义优先级。<br/> - 自定义定时器:自定义定时器可以每一帧或者自定义的时间间隔触发。<br/> 如果希望每帧都触发,应该使用 update 定时器,使用 update 定时器更快,而且消耗更少的内存。 */ export class Scheduler { /** !#en Modifies the time of all scheduled callbacks.<br/> You can use this property to create a 'slow motion' or 'fast forward' effect.<br/> Default is 1.0. To create a 'slow motion' effect, use values below 1.0.<br/> To create a 'fast forward' effect, use values higher than 1.0.<br/> Note:It will affect EVERY scheduled selector / action. !#zh 设置时间间隔的缩放比例。<br/> 您可以使用这个方法来创建一个 “slow motion(慢动作)” 或 “fast forward(快进)” 的效果。<br/> 默认是 1.0。要创建一个 “slow motion(慢动作)” 效果,使用值低于 1.0。<br/> 要使用 “fast forward(快进)” 效果,使用值大于 1.0。<br/> 注意:它影响该 Scheduler 下管理的所有定时器。 */ setTimeScale(timeScale : number) : void; /** !#en Returns time scale of scheduler. !#zh 获取时间间隔的缩放比例。 */ getTimeScale() : number; /** !#en 'update' the scheduler. (You should NEVER call this method, unless you know what you are doing.) !#zh update 调度函数。(不应该直接调用这个方法,除非完全了解这么做的结果) @param dt delta time */ update(dt : number) : void; /** !#en <p> The scheduled method will be called every 'interval' seconds.</br> If paused is YES, then it won't be called until it is resumed.<br/> If 'interval' is 0, it will be called every frame, but if so, it recommended to use 'scheduleUpdateForTarget:' instead.<br/> If the callback function is already scheduled, then only the interval parameter will be updated without re-scheduling it again.<br/> repeat let the action be repeated repeat + 1 times, use cc.macro.REPEAT_FOREVER to let the action run continuously<br/> delay is the amount of time the action will wait before it'll start<br/> </p> !#zh 指定回调函数,调用对象等信息来添加一个新的定时器。</br> 当时间间隔达到指定值时,设置的回调函数将会被调用。</br> 如果 paused 值为 true,那么直到 resume 被调用才开始计时。</br> 如果 interval 值为 0,那么回调函数每一帧都会被调用,但如果是这样, 建议使用 scheduleUpdateForTarget 代替。</br> 如果回调函数已经被定时器使用,那么只会更新之前定时器的时间间隔参数,不会设置新的定时器。<br/> repeat 值可以让定时器触发 repeat + 1 次,使用 cc.macro.REPEAT_FOREVER 可以让定时器一直循环触发。<br/> delay 值指定延迟时间,定时器会在延迟指定的时间之后开始计时。 @example ```js //register a schedule to scheduler var scheduler = cc.director.getScheduler(); scheduler.scheduleCallbackForTarget(this, function, interval, repeat, delay, !this._isRunning); ``` */ scheduleCallbackForTarget(target : any, callback_fn : Function, interval : number, repeat : number, delay : number, paused : boolean) : void; /** !#en The schedule !#zh 定时器 @example ```js //register a schedule to scheduler cc.director.getScheduler().schedule(callback, this, interval, !this._isRunning); ``` */ schedule(callback : Function, target : any, interval : number, repeat : number, delay : number, paused : boolean) : void; /** !#en Schedules the update callback for a given target, the callback will be invoked every frame after schedule started. !#zh 使用指定的优先级为指定的对象设置 update 定时器。 update 定时器每一帧都会被触发。优先级的值越低,定时器被触发的越早。 */ scheduleUpdate(target : any, priority : number, paused : boolean, updateFunc : Function) : void; /** !#en Unschedules a callback for a callback and a given target. If you want to unschedule the "update", use `unscheduleUpdate()` !#zh 根据指定的回调函数和调用对象。 如果需要取消 update 定时器,请使用 unscheduleUpdate()。 @param callback The callback to be unscheduled @param target The target bound to the callback. */ unschedule(callback : Function, target : any) : void; /** !#en Unschedules the update callback for a given target. !#zh 取消指定对象的 update 定时器。 @param target The target to be unscheduled. */ unscheduleUpdate(target : any) : void; /** !#en Unschedules all scheduled callbacks for a given target. This also includes the "update" callback. !#zh 取消指定对象的所有定时器,包括 update 定时器。 @param target The target to be unscheduled. */ unscheduleAllForTarget(target : any) : void; /** !#en Unschedules all scheduled callbacks from all targets including the system callbacks.<br/> You should NEVER call this method, unless you know what you are doing. !#zh 取消所有对象的所有定时器,包括系统定时器。<br/> 不用调用此函数,除非你确定你在做什么。 */ unscheduleAll() : void; /** !#en Unschedules all callbacks from all targets with a minimum priority.<br/> You should only call this with `PRIORITY_NON_SYSTEM_MIN` or higher. !#zh 取消所有优先级的值大于指定优先级的定时器。<br/> 你应该只取消优先级的值大于 PRIORITY_NON_SYSTEM_MIN 的定时器。 @param minPriority The minimum priority of selector to be unscheduled. Which means, all selectors which priority is higher than minPriority will be unscheduled. */ unscheduleAllWithMinPriority(minPriority : number) : void; /** !#en Checks whether a callback for a given target is scheduled. !#zh 检查指定的回调函数和回调对象组合是否存在定时器。 @param callback The callback to check. @param target The target of the callback. */ isScheduled(callback : Function, target : any) : boolean; /** !#en Pause all selectors from all targets.<br/> You should NEVER call this method, unless you know what you are doing. !#zh 暂停所有对象的所有定时器。<br/> 不要调用这个方法,除非你知道你正在做什么。 */ pauseAllTargets() : void; /** !#en Pause all selectors from all targets with a minimum priority. <br/> You should only call this with kCCPriorityNonSystemMin or higher. !#zh 暂停所有优先级的值大于指定优先级的定时器。<br/> 你应该只暂停优先级的值大于 PRIORITY_NON_SYSTEM_MIN 的定时器。 */ pauseAllTargetsWithMinPriority(minPriority : number) : void; /** !#en Resume selectors on a set of targets.<br/> This can be useful for undoing a call to pauseAllCallbacks. !#zh 恢复指定数组中所有对象的定时器。<br/> 这个函数是 pauseAllCallbacks 的逆操作。 */ resumeTargets(targetsToResume : any[]) : void; /** !#en Pauses the target.<br/> All scheduled selectors/update for a given target won't be 'ticked' until the target is resumed.<br/> If the target is not present, nothing happens. !#zh 暂停指定对象的定时器。<br/> 指定对象的所有定时器都会被暂停。<br/> 如果指定的对象没有定时器,什么也不会发生。 */ pauseTarget(target : any) : void; /** !#en Resumes the target.<br/> The 'target' will be unpaused, so all schedule selectors/update will be 'ticked' again.<br/> If the target is not present, nothing happens. !#zh 恢复指定对象的所有定时器。<br/> 指定对象的所有定时器将继续工作。<br/> 如果指定的对象没有定时器,什么也不会发生。 */ resumeTarget(target : any) : void; /** !#en Returns whether or not the target is paused. !#zh 返回指定对象的定时器是否暂停了。 */ isTargetPaused(target : any) : boolean; /** !#en Schedules the 'update' callback_fn for a given target with a given priority.<br/> The 'update' callback_fn will be called every frame.<br/> The lower the priority, the earlier it is called. !#zh 为指定对象设置 update 定时器。<br/> update 定时器每一帧都会被调用。<br/> 优先级的值越低,越早被调用。 @example ```js //register this object to scheduler var scheduler = cc.director.getScheduler(); scheduler.scheduleUpdateForTarget(this, priority, !this._isRunning ); ``` */ scheduleUpdateForTarget(target : any, priority : number, paused : boolean) : void; /** !#en Unschedule a callback function for a given target.<br/> If you want to unschedule the "update", use unscheduleUpdateForTarget. !#zh 根据指定的回调函数和调用对象对象取消相应的定时器。<br/> 如果需要取消 update 定时器,请使用 unscheduleUpdateForTarget()。 @param callback callback[Function] or key[String] @example ```js //unschedule a callback of target var scheduler = cc.director.getScheduler(); scheduler.unscheduleCallbackForTarget(this, callback); ``` */ unscheduleCallbackForTarget(target : any, callback : Function) : void; /** !#en Unschedules the update callback function for a given target. !#zh 取消指定对象的所有定时器。 @example ```js //unschedules the "update" method. var scheduler = cc.director.getScheduler(); scheduler.unscheduleUpdateForTarget(this); ``` */ unscheduleUpdateForTarget(target : any) : void; /** !#en Unschedules all function callbacks for a given target.<br/> This also includes the "update" callback function. !#zh 取消指定对象的所有定时器,包括 update 定时器。 */ unscheduleAllCallbacksForTarget(target : any) : void; /** !#en Unschedules all function callbacks from all targets. <br/> You should NEVER call this method, unless you know what you are doing. !#zh 取消所有对象的所有定时器。<br/> 不要调用这个方法,除非你知道你正在做什么。 */ unscheduleAllCallbacks() : void; /** !#en Unschedules all function callbacks from all targets with a minimum priority.<br/> You should only call this with kCCPriorityNonSystemMin or higher. !#zh 取消所有优先级的值大于指定优先级的所有对象的所有定时器。<br/> 你应该只暂停优先级的值大于 PRIORITY_NON_SYSTEM_MIN 的定时器。 */ unscheduleAllCallbacksWithMinPriority(minPriority : number) : void; /** !#en Priority level reserved for system services. !#zh 系统服务的优先级。 */ PRIORITY_SYSTEM : number; /** !#en Minimum priority level for user scheduling. !#zh 用户调度最低优先级。 */ PRIORITY_NON_SYSTEM : number; } /** !#en Renders the TMX object. !#zh 渲染 tmx object。 */ export class TMXObject { /** !#en Get the name of object !#zh 获取对象的名称 */ getObjectName() : string; /** !#en Get the property of object !#zh 获取对象的属性 */ getProperty() : any; /** !#en Get the properties of object !#zh 获取对象的属性 */ getProperties() : any; /** !#en Set the object name !#zh 设置对象名称 */ setObjectName(name : string) : void; /** !#en Set the properties of the object !#zh 设置对象的属性 */ setProperties(props : any) : void; } /** !#en Render the TMX layer. !#zh 渲染 TMX layer。 */ export class TiledLayer extends _SGComponent { /** !#en Gets the layer name. !#zh 获取层的名称。 @example ```js var layerName = tiledLayer.getLayerName(); cc.log(layerName); ``` */ getLayerName() : string; /** !#en Set the layer name. !#zh 设置层的名称 @example ```js tiledLayer.setLayerName("New Layer"); ``` */ SetLayerName(layerName : string) : void; /** !#en Return the value for the specific property name. !#zh 获取指定属性名的值。 @example ```js var property = tiledLayer.getProperty("info"); cc.log(property); ``` */ getProperty(propertyName : string) : any; /** !#en Returns the position in pixels of a given tile coordinate. !#zh 获取指定 tile 的像素坐标。 @param pos position or x @example ```js var pos = tiledLayer.getPositionAt(cc.v2(0, 0)); cc.log("Pos: " + pos); var pos = tiledLayer.getPositionAt(0, 0); cc.log("Pos: " + pos); ``` */ getPositionAt(pos : Vec2|number, y? : number) : Vec2; /** !#en Removes a tile at given tile coordinate. !#zh 删除指定坐标上的 tile。 @param pos position or x @example ```js tiledLayer.removeTileAt(cc.v2(0, 0)); tiledLayer.removeTileAt(0, 0); ``` */ removeTileAt(pos : Vec2|number, y? : number) : void; /** !#en Sets the tile gid (gid = tile global id) at a given tile coordinate.<br /> The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.<br /> If a tile is already placed at that position, then it will be removed. !#zh 设置给定坐标的 tile 的 gid (gid = tile 全局 id), tile 的 GID 可以使用方法 “tileGIDAt” 来获得。<br /> 如果一个 tile 已经放在那个位置,那么它将被删除。 @param posOrX position or x @param flagsOrY flags or y @example ```js tiledLayer.setTileGID(1001, 10, 10, 1) ``` */ setTileGID(gid : number, posOrX : Vec2|number, flagsOrY : number, flags? : number) : void; /** !#en Returns the tile gid at a given tile coordinate. <br /> if it returns 0, it means that the tile is empty. <br /> This method requires the the tile map has not been previously released (eg. don't call layer.releaseMap())<br /> !#zh 通过给定的 tile 坐标、flags(可选)返回 tile 的 GID. <br /> 如果它返回 0,则表示该 tile 为空。<br /> 该方法要求 tile 地图之前没有被释放过(如:没有调用过layer.releaseMap()). @param pos or x @example ```js var tileGid = tiledLayer.getTileGIDAt(0, 0); ``` */ getTileGIDAt(pos : Vec2|number, y? : number) : number; /** !#en Returns the tile (_ccsg.Sprite) at a given a tile coordinate. <br/> The returned _ccsg.Sprite will be already added to the _ccsg.TMXLayer. Don't add it again.<br/> The _ccsg.Sprite can be treated like any other _ccsg.Sprite: rotated, scaled, translated, opacity, color, etc. <br/> You can remove either by calling: <br/> - layer.removeChild(sprite, cleanup); <br/> - or layer.removeTileAt(ccp(x,y)); !#zh 通过指定的 tile 坐标获取对应的 tile(Sprite)。 返回的 tile(Sprite) 应是已经添加到 TMXLayer,请不要重复添加。<br/> 这个 tile(Sprite) 如同其他的 Sprite 一样,可以旋转、缩放、翻转、透明化、设置颜色等。<br/> 你可以通过调用以下方法来对它进行删除:<br/> 1. layer.removeChild(sprite, cleanup);<br/> 2. 或 layer.removeTileAt(cc.v2(x,y)); @param pos or x @example ```js var title = tiledLayer.getTileAt(100, 100); cc.log(title); ``` */ getTileAt(pos : Vec2|number, y? : number) : _ccsg.Sprite; /** !#en Dealloc the map that contains the tile position from memory. <br /> Unless you want to know at runtime the tiles positions, you can safely call this method. <br /> If you are going to call layer.getTileGIDAt() then, don't release the map. !#zh 从内存中释放包含 tile 位置信息的地图。<br /> 除了在运行时想要知道 tiles 的位置信息外,你都可安全的调用此方法。<br /> 如果你之后还要调用 layer.tileGIDAt(), 请不要释放地图. @example ```js tiledLayer.releaseMap(); ``` */ releaseMap() : void; /** !#en Sets the untransformed size of the _ccsg.TMXLayer. !#zh 设置未转换的 layer 大小。 @param size The untransformed size of the _ccsg.TMXLayer or The untransformed size's width of the TMXLayer. @param height The untransformed size's height of the _ccsg.TMXLayer. @example ```js tiledLayer.setContentSize(100, 100); ``` */ setContentSize(size : Size|number, height? : number) : void; /** !#en Return texture of cc.SpriteBatchNode. !#zh 获取纹理。 @example ```js var texture = tiledLayer.getTexture(); cc.log("Texture: " + texture); ``` */ getTexture() : Texture2D; /** !#en Set the texture of cc.SpriteBatchNode. !#zh 设置纹理。 @example ```js tiledLayer.setTexture(texture); ``` */ setTexture(texture : Texture2D) : void; /** !#en Set the opacity of all tiles !#zh 设置所有 Tile 的透明度 @example ```js tiledLayer.setTileOpacity(128); ``` */ setTileOpacity(opacity : number) : void; /** !#en Gets layer size. !#zh 获得层大小。 @example ```js var size = tiledLayer.getLayerSize(); cc.log("layer size: " + size); ``` */ getLayerSize() : Size; /** !#en Set layer size. !#zh 设置层大小。 @example ```js tiledLayer.setLayerSize(new cc.size(5, 5)); ``` */ setLayerSize(layerSize : Size) : void; /** !#en Size of the map's tile (could be different from the tile's size). !#zh 获取 tile 的大小( tile 的大小可能会有所不同)。 @example ```js var mapTileSize = tiledLayer.getMapTileSize(); cc.log("MapTile size: " + mapTileSize); ``` */ getMapTileSize() : Size; /** !#en Set the map tile size. !#zh 设置 tile 的大小。 @example ```js tiledLayer.setMapTileSize(new cc.size(10, 10)); ``` */ setMapTileSize(tileSize : Size) : void; /** !#en Pointer to the map of tiles. !#zh 获取地图 tiles。 @example ```js var tiles = tiledLayer.getTiles(); ``` */ getTiles() : any[]; /** !#en Pointer to the map of tiles. !#zh 设置地图 tiles @example ```js tiledLayer.setTiles(tiles); ``` */ setTiles(tiles : any[]) : void; /** !#en Tile set information for the layer. !#zh 获取 layer 的 Tileset 信息。 @example ```js var tileset = tiledLayer.getTileSet(); ``` */ getTileSet() : TMXTilesetInfo; /** !#en Tile set information for the layer. !#zh 设置 layer 的 Tileset 信息。 @example ```js tiledLayer.setTileSet(tileset); ``` */ setTileSet(tileset : TMXTilesetInfo) : void; /** !#en Layer orientation, which is the same as the map orientation. !#zh 获取 Layer 方向(同地图方向)。 @example ```js var orientation = tiledLayer.getLayerOrientation(); cc.log("Layer Orientation: " + orientation); ``` */ getLayerOrientation() : number; /** !#en Layer orientation, which is the same as the map orientation. !#zh 设置 Layer 方向(同地图方向)。 @example ```js tiledLayer.setLayerOrientation(TiledMap.Orientation.ORTHO); ``` */ setLayerOrientation(orientation : TiledMap.Orientation) : void; /** !#en properties from the layer. They can be added using Tiled. !#zh 获取 layer 的属性,可以使用 Tiled 编辑器添加属性。 @example ```js var properties = tiledLayer.getProperties(); cc.log("Properties: " + properties); ``` */ getProperties() : any[]; /** !#en properties from the layer. They can be added using Tiled. !#zh 设置层属性。 @example ```js tiledLayer.setLayerOrientation(properties); ``` */ setProperties(properties : any[]) : void; } /** !#en Renders a TMX Tile Map in the scene. !#zh 在场景中渲染一个 tmx 格式的 Tile Map。 */ export class TiledMap extends Component { /** !#en The TiledMap Asset. !#zh TiledMap 资源。 */ tmxAsset : TiledMapAsset; /** !#en Gets the map size. !#zh 获取地图大小。 @example ```js var mapSize = tiledMap.getMapSize(); cc.log("Map Size: " + mapSize); ``` */ getMapSize() : Size; /** !#en Set the map size. !#zh 设置地图大小。 @example ```js tiledMap.setMapSize(new cc.size(960, 640)); ``` */ setMapSize(mapSize : Size) : void; /** !#en Gets the tile size. !#zh 获取地图背景中 tile 元素的大小。 @example ```js var tileSize = tiledMap.getTileSize(); cc.log("Tile Size: " + tileSize); ``` */ getTileSize() : Size; /** !#en Set the tile size. !#zh 设置地图背景中 tile 元素的大小。 @example ```js tiledMap.setTileSize(new cc.size(10, 10)); ``` */ setTileSize(tileSize : Size) : void; /** !#en map orientation. !#zh 获取地图方向。 @example ```js var mapOrientation = tiledMap.getMapOrientation(); cc.log("Map Orientation: " + mapOrientation); ``` */ getMapOrientation() : number; /** !#en map orientation. !#zh 设置地图方向。 @example ```js tiledMap.setMapOrientation(TiledMap.Orientation.ORTHO); ``` */ setMapOrientation(orientation : TiledMap.Orientation) : void; /** !#en object groups. !#zh 获取所有的对象层。 @example ```js var objGroups = titledMap.getObjectGroups(); for (var i = 0; i < objGroups.length; ++i) { cc.log("obj: " + objGroups[i]); } ``` */ getObjectGroups() : TiledObjectGroup[]; /** !#en Gets the map properties. !#zh 获取地图的属性。 @example ```js var properties = titledMap.getProperties(); for (var i = 0; i < properties.length; ++i) { cc.log("Properties: " + properties[i]); } ``` */ getProperties() : any[]; /** !#en Set the map properties. !#zh 设置地图的属性。 @example ```js titledMap.setProperties(properties); ``` */ setProperties(properties : any[]) : void; /** !#en Return All layers array. !#zh 返回包含所有 layer 的数组。 @example ```js var layers = titledMap.allLayers(); for (var i = 0; i < layers.length; ++i) { cc.log("Layers: " + layers[i]); } ``` */ allLayers() : TiledLayer[]; /** !#en return the cc.TiledLayer for the specific layer. !#zh 获取指定名称的 layer。 @example ```js var layer = titledMap.getLayer("Player"); cc.log(layer); ``` */ getLayer(layerName : string) : TiledLayer; /** !#en Return the TMXObjectGroup for the specific group. !#zh 获取指定的 TMXObjectGroup。 @example ```js var group = titledMap.getObjectGroup("Players"); cc.log("ObjectGroup: " + group); ``` */ getObjectGroup(groupName : string) : TiledObjectGroup; /** !#en Return the value for the specific property name. !#zh 通过属性名称,获取指定的属性。 @example ```js var property = titledMap.getProperty("info"); cc.log("Property: " + property); ``` */ getProperty(propertyName : string) : string; /** !#en Return properties dictionary for tile GID. !#zh 通过 GID ,获取指定的属性。 @example ```js var properties = titledMap.getPropertiesForGID(GID); cc.log("Properties: " + properties); ``` */ getPropertiesForGID(GID : number) : any; } /** Class for tiled map asset handling. */ export class TiledMapAsset extends Asset { } /** !#en Renders the TMX object group. !#zh 渲染 tmx object group。 */ export class TiledObjectGroup extends _SGComponent { /** !#en Offset position of child objects. !#zh 获取子对象的偏移位置。 @example ```js var offset = tMXObjectGroup.getPositionOffset(); ``` */ getPositionOffset() : Vec2; /** !#en Offset position of child objects. !#zh 设置子对象的偏移位置。 @example ```js tMXObjectGroup.setPositionOffset(cc.v2(5, 5)); ``` */ setPositionOffset(offset : Vec2) : void; /** !#en List of properties stored in a dictionary. !#zh 以映射的形式获取属性列表。 @example ```js var offset = tMXObjectGroup.getProperties(); ``` */ getProperties() : any; /** !#en Set the properties of the object group. !#zh 设置属性列表。 @example ```js tMXObjectGroup.setProperties(obj); ``` */ setProperties(Var : any) : void; /** !#en Gets the Group name. !#zh 获取组名称。 @example ```js var groupName = tMXObjectGroup.getGroupName; ``` */ getGroupName() : string; /** !#en Set the Group name. !#zh 设置组名称。 @example ```js tMXObjectGroup.setGroupName("New Group"); ``` */ setGroupName(groupName : string) : void; /** !#en Return the object for the specific object name. <br /> It will return the 1st object found on the array for the given name. !#zh 获取指定的对象。 @example ```js var object = tMXObjectGroup.getObject("Group"); ``` */ getObject(objectName : string) : any; /** !#en Gets the objects. !#zh 获取对象数组。 @example ```js var objects = tMXObjectGroup.getObjects(); ``` */ getObjects() : any[]; } /** !#en cc.NodePool is the cache pool designed for node type.<br/> It can helps you to improve your game performance for objects which need frequent release and recreate operations<br/> It's recommended to create cc.NodePool instances by node type, the type corresponds to node type in game design, not the class, for example, a prefab is a specific node type. <br/> When you create a node pool, you can pass a Component which contains `unuse`, `reuse` functions to control the content of node.<br/> Some common use case is :<br/> 1. Bullets in game (die very soon, massive creation and recreation, no side effect on other objects)<br/> 2. Blocks in candy crash (massive creation and recreation)<br/> etc... !#zh cc.NodePool 是用于管理节点对象的对象缓存池。<br/> 它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁<br/> 以前 cocos2d-x 中的 cc.pool 和新的节点事件注册系统不兼容,因此请使用 cc.NodePool 来代替。 新的 NodePool 需要实例化之后才能使用,每种不同的节点对象池需要一个不同的对象池实例,这里的种类对应于游戏中的节点设计,一个 prefab 相当于一个种类的节点。<br/> 在创建缓冲池时,可以传入一个包含 unuse, reuse 函数的组件类型用于节点的回收和复用逻辑。<br/> 一些常见的用例是:<br/> 1.在游戏中的子弹(死亡很快,频繁创建,对其他对象无副作用)<br/> 2.糖果粉碎传奇中的木块(频繁创建)。 等等.... */ export class NodePool { /** !#en Constructor for creating a pool for a specific node template (usually a prefab). You can pass a component (type or name) argument for handling event for reusing and recycling node. !#zh 使用构造函数来创建一个节点专用的对象池,您可以传递一个组件类型或名称,用于处理节点回收和复用时的事件逻辑。 @param poolHandlerComp !#en The constructor or the class name of the component to control the unuse/reuse logic. !#zh 处理节点回收和复用事件逻辑的组件类型或名称。 @example ```js properties: { template: cc.Prefab }, onLoad () { // MyTemplateHandler is a component with 'unuse' and 'reuse' to handle events when node is reused or recycled. this.myPool = new cc.NodePool('MyTemplateHandler'); } ``` */ NodePool(poolHandlerComp : [Function|String]) : void; /** !#en The pool handler component, it could be the class name or the constructor. !#zh 缓冲池处理组件,用于节点的回收和复用逻辑,这个属性可以是组件类名或组件的构造函数。 */ poolHandlerComp : Function|string; /** !#en The current available size in the pool !#zh 获取当前缓冲池的可用对象数量 */ size() : void; /** !#en Destroy all cached nodes in the pool !#zh 销毁对象池中缓存的所有节点 */ clear() : void; /** !#en Put a new Node into the pool. It will automatically remove the node from its parent without cleanup. It will also invoke unuse method of the poolHandlerComp if exist. !#zh 向缓冲池中存入一个不再需要的节点对象。 这个函数会自动将目标节点从父节点上移除,但是不会进行 cleanup 操作。 这个函数会调用 poolHandlerComp 的 unuse 函数,如果组件和函数都存在的话。 @example ```js let myNode = cc.instantiate(this.template); this.myPool.put(myNode); ``` */ put() : void; /** !#en Get a obj from pool, if no available object in pool, null will be returned. This function will invoke the reuse function of poolHandlerComp if exist. !#zh 获取对象池中的对象,如果对象池没有可用对象,则返回空。 这个函数会调用 poolHandlerComp 的 reuse 函数,如果组件和函数都存在的话。 @param params !#en Params to pass to 'reuse' method in poolHandlerComp !#zh 向 poolHandlerComp 中的 'reuse' 函数传递的参数 @example ```js let newNode = this.myPool.get(); ``` */ get(params : any) : any; } /** !#en Attention: In creator, it's strongly not recommended to use cc.pool to manager cc.Node. We provided {{#crossLink "NodePool"}}cc.NodePool{{/crossLink}} instead. cc.pool is a singleton object serves as an object cache pool.<br/> It can helps you to improve your game performance for objects which need frequent release and recreate operations<br/> !#zh 首先请注意,在 Creator 中我们强烈不建议使用 cc.pool 来管理 cc.Node 节点对象,请使用 {{#crossLink "NodePool"}}cc.NodePool{{/crossLink}} 代替 因为 cc.pool 是面向类来设计的,而 cc.Node 中使用 Component 来进行组合,它的类永远都一样,实际却千差万别。 cc.pool 是一个单例对象,用作为对象缓存池。<br/> 它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁<br/> */ export class pool { /** !#en Put the obj in pool. !#zh 加入对象到对象池中。 @param obj The need put in pool object. @example ```js --------------------------------- var sp = new _ccsg.Sprite("a.png"); this.addChild(sp); cc.pool.putInPool(sp); cc.pool.getFromPool(_ccsg.Sprite, "a.png"); ``` */ putInPool(obj : any) : void; /** !#en Check if this kind of obj has already in pool. !#zh 检查对象池中是否有指定对象的存在。 @param objClass The check object class. */ hasObject(objClass : any) : boolean; /** !#en Remove the obj if you want to delete it. !#zh 移除在对象池中指定的对象。 */ removeObject() : void; /** !#en Get the obj from pool. !#zh 获取对象池中的指定对象。 */ getFromPool() : any; /** !#en Remove all objs in pool and reset the pool. !#zh 移除对象池中的所有对象,并且重置对象池。 */ drainAllPools() : void; } /** !#en Box Collider. !#zh 包围盒碰撞组件 */ export class BoxCollider extends Component { /** !#en Position offset !#zh 位置偏移量 */ offset : Vec2; /** !#en Box size !#zh 包围盒大小 */ size : Size; } /** !#en Circle Collider. !#zh 圆形碰撞组件 */ export class CircleCollider extends Component { /** !#en Position offset !#zh 位置偏移量 */ offset : Vec2; /** !#en Circle radius !#zh 圆形半径 */ radius : number; } /** !#en Collider component base class. !#zh 碰撞组件基类 */ export class Collider extends Component { /** !#en Tag. If a node has several collider components, you can judge which type of collider is collided according to the tag. !#zh 标签。当一个节点上有多个碰撞组件时,在发生碰撞后,可以使用此标签来判断是节点上的哪个碰撞组件被碰撞了。 */ tag : Integer; } /** !#en A simple collision manager class. It will calculate whether the collider collides other colliders, if collides then call the callbacks. !#zh 一个简单的碰撞组件管理类,用于处理节点之间的碰撞组件是否产生了碰撞,并调用相应回调函数。 */ export class CollisionManager { /** !#en !#zh 是否开启碰撞管理,默认为不开启 */ enabled : boolean; /** !#en !#zh 是否绘制碰撞组件的包围盒,默认为不绘制 */ enabledDrawBoundingBox : boolean; /** !#en !#zh 是否绘制碰撞组件的形状,默认为不绘制 */ enabledDebugDraw : boolean; } /** !#en Intersection helper class !#zh 辅助类,用于测试形状与形状是否相交 */ export class Intersection { /** !#en Test line and line !#zh 测试线段与线段是否相交 @param a1 The start point of the first line @param a2 The end point of the first line @param b1 The start point of the second line @param b2 The end point of the second line */ lineLine(a1 : Vec2, a2 : Vec2, b1 : Vec2, b2 : Vec2) : boolean; /** !#en Test line and rect !#zh 测试线段与矩形是否相交 @param a1 The start point of the line @param a2 The end point of the line @param b The rect */ lineRect(a1 : Vec2, a2 : Vec2, b : Rect) : boolean; /** !#en Test line and polygon !#zh 测试线段与多边形是否相交 @param a1 The start point of the line @param a2 The end point of the line @param b The polygon, a set of points */ linePolygon(a1 : Vec2, a2 : Vec2, b : [Vec2]) : boolean; /** !#en Test rect and rect !#zh 测试矩形与矩形是否相交 @param a The first rect @param b The second rect */ rectRect(a : Rect, b : Rect) : boolean; /** !#en Test rect and polygon !#zh 测试矩形与多边形是否相交 @param a The rect @param b The polygon, a set of points */ rectPolygon(a : Rect, b : [Vec2]) : boolean; /** !#en Test polygon and polygon !#zh 测试多边形与多边形是否相交 @param a The first polygon, a set of points @param b The second polygon, a set of points */ polygonPolygon(a : [Vec2], b : [Vec2]) : boolean; /** !#en Test circle and circle !#zh 测试圆形与圆形是否相交 @param a Object contains position and radius @param b Object contains position and radius */ circleCircle(a : any, b : any) : boolean; /** !#en Test polygon and circle !#zh 测试矩形与圆形是否相交 @param polygon The Polygon, a set of points @param circle Object contains position and radius */ polygonCircle(polygon : [Vec2], circle : any) : boolean; /** !#en Test whether the point is in the polygon !#zh 测试一个点是否在一个多边形中 @param point The point @param polygon The polygon, a set of points */ pointInPolygon(point : Vec2, polygon : [Vec2]) : boolean; /** !#en Calculate the distance of point to line. !#zh 计算点到直线的距离。如果这是一条线段并且垂足不在线段内,则会计算点到线段端点的距离。 @param point The point @param start The start point of line @param end The end point of line @param isSegment whether this line is a segment */ pointLineDistance(point : Vec2, start : Vec2, end : Vec2, isSegment : boolean) : boolean; } /** !#en Polygon Collider. !#zh 多边形碰撞组件 */ export class PolygonCollider extends Component { /** !#en Position offset !#zh 位置偏移量 */ offset : Vec2; /** !#en Polygon points !#zh 多边形顶点数组 */ points : [Vec2]; } /** !#en EventTarget is an object to which an event is dispatched when something has occurred. Entity are the most common event targets, but other objects can be event targets too. Event targets are an important part of the Fireball event model. The event target serves as the focal point for how events flow through the scene graph. When an event such as a mouse click or a keypress occurs, Fireball dispatches an event object into the event flow from the root of the hierarchy. The event object then makes its way through the scene graph until it reaches the event target, at which point it begins its return trip through the scene graph. This round-trip journey to the event target is conceptually divided into three phases: - The capture phase comprises the journey from the root to the last node before the event target's node - The target phase comprises only the event target node - The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the tree See also: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow Event targets can implement the following methods: - _getCapturingTargets - _getBubblingTargets !#zh 事件目标是事件触发时,分派的事件对象,Node 是最常见的事件目标, 但是其他对象也可以是事件目标。<br/> */ export class EventTarget { /** !#en Register an callback of a specific event type on the EventTarget. !#zh 注册事件目标的特定事件类型回调。 @param type A string representing the event type to listen for. @param callback The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). @param target The target to invoke the callback, can be null @param useCapture When set to true, the capture argument prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. @example ```js node.on(cc.Node.EventType.TOUCH_END, function (event) { cc.log("this is callback"); }, node); ``` */ on(type : string, callback: (param: Event) => void, target : any, useCapture : boolean) : Function; /** !#en Removes the callback previously registered with the same type, callback, target and or useCapture. !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。 @param type A string representing the event type being removed. @param callback The callback to remove. @param target The target to invoke the callback, if it's not given, only callback without target will be removed @param useCapture Specifies whether the callback being removed was registered as a capturing callback or not. If not specified, useCapture defaults to false. If a callback was registered twice, one with capture and one without, each must be removed separately. Removal of a capturing callback does not affect a non-capturing version of the same listener, and vice versa. @example ```js // register touchEnd eventListener var touchEnd = node.on(cc.Node.EventType.TOUCH_END, function (event) { cc.log("this is callback"); }, node); // remove touchEnd eventListener node.off(cc.Node.EventType.TOUCH_END, touchEnd, node); ``` */ off(type : string, callback : Function, target : any, useCapture : boolean) : void; /** !#en Removes all callbacks previously registered with the same target (passed as parameter). This is not for removing all listeners in the current event target, and this is not for removing all listeners the target parameter have registered. It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 @param target The target to be searched for all related listeners */ targetOff(target : any) : void; /** !#en Register an callback of a specific event type on the EventTarget, the callback will remove itself after the first time it is triggered. !#zh 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 @param type A string representing the event type to listen for. @param callback The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). @param target The target to invoke the callback, can be null @param useCapture When set to true, the capture argument prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. @example ```js node.once(cc.Node.EventType.TOUCH_END, function (event) { cc.log("this is callback"); }, node); ``` */ once(type : string, callback: (param: Event) => void, target : any, useCapture : boolean) : void; /** !#en Dispatches an event into the event flow. The event target is the EventTarget object upon which the dispatchEvent() method is called. !#zh 分发事件到事件流中。 @param event The Event object that is dispatched into the event flow */ dispatchEvent(event : Event) : void; /** !#en Send an event to this object directly, this method will not propagate the event to any other objects. The event will be created from the supplied message, you can get the "detail" argument from event.detail. !#zh 该对象直接发送事件, 这种方法不会对事件传播到任何其他对象。 @param message the message to send @param detail whatever argument the message needs */ emit(message : string, detail? : any) : void; } /** !#en Base class of all kinds of events. !#zh 包含事件相关信息的对象。 */ export class Event { /** @param type The name of the event (case-sensitive), e.g. "click", "fire", or "submit" @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ Event(type : string, bubbles : boolean) : Event; /** !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". !#zh 事件类型。 */ type : string; /** !#en Indicate whether the event bubbles up through the tree or not. !#zh 表示该事件是否进行冒泡。 */ bubbles : boolean; /** !#en A reference to the target to which the event was originally dispatched. !#zh 最初事件触发的目标 */ target : any; /** !#en A reference to the currently registered target for the event. !#zh 当前目标 */ currentTarget : any; /** !#en Indicates which phase of the event flow is currently being evaluated. Returns an integer value represented by 4 constants: - Event.NONE = 0 - Event.CAPTURING_PHASE = 1 - Event.AT_TARGET = 2 - Event.BUBBLING_PHASE = 3 The phases are explained in the [section 3.1, Event dispatch and DOM event flow] (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. !#zh 事件阶段 */ eventPhase : number; /** !#en Reset the event for being stored in the object pool. !#zh 重置对象池中存储的事件。 */ unuse() : string; /** !#en Reuse the event for being used again by the object pool. !#zh 用于对象池再次使用的事件。 */ reuse() : string; /** !#en Stops propagation for current event. !#zh 停止传递当前事件。 */ stopPropagation() : void; /** !#en Stops propagation for current event immediately, the event won't even be dispatched to the listeners attached in the current target. !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 */ stopPropagationImmediate() : void; /** !#en Checks whether the event has been stopped. !#zh 检查该事件是否已经停止传递. */ isStopped() : boolean; /** !#en <p> Gets current target of the event <br/> note: It only be available when the event listener is associated with node. <br/> It returns 0 when the listener is associated with fixed priority. </p> !#zh 获取当前目标节点 */ getCurrentTarget() : Node; /** !#en Gets the event type. !#zh 获取事件类型 */ getType() : string; /** !#en Code for event without type. !#zh 没有类型的事件 */ NO_TYPE : string; /** !#en Events not currently dispatched are in this phase !#zh 尚未派发事件阶段 */ NONE : number; /** !#en The capturing phase comprises the journey from the root to the last node before the event target's node see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 */ CAPTURING_PHASE : number; /** !#en The target phase comprises only the event target node see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow !#zh 目标阶段仅包括事件目标节点。 */ AT_TARGET : number; /** !#en The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 */ BUBBLING_PHASE : number; } /** !#en The animation component is used to play back animations. Animation provide several events to register: - play : Emit when begin playing animation - stop : Emit when stop playing animation - pause : Emit when pause animation - resume : Emit when resume animation - lastframe : If animation repeat count is larger than 1, emit when animation play to the last frame - finished : Emit when finish playing animation !#zh Animation 组件用于播放动画。 Animation 提供了一系列可注册的事件: - play : 开始播放时 - stop : 停止播放时 - pause : 暂停播放时 - resume : 恢复播放时 - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时 - finished : 动画播放完成时 */ export class Animation extends CCComponent { /** !#en Animation will play the default clip when start game. !#zh 在勾选自动播放或调用 play() 时默认播放的动画剪辑。 */ defaultClip : AnimationClip; /** !#en Current played clip. !#zh 当前播放的动画剪辑。 */ currentClip : AnimationClip; /** !#en Whether the animation should auto play the default clip when start game. !#zh 是否在运行游戏后自动播放默认动画剪辑。 */ playOnLoad : boolean; /** !#en Get all the clips used in this animation. !#zh 获取动画组件上的所有动画剪辑。 */ getClips() : AnimationClip[]; /** !#en Plays an animation and stop other animations. !#zh 播放指定的动画,并且停止当前正在播放动画。如果没有指定动画,则播放默认动画。 @param name The name of animation to play. If no name is supplied then the default animation will be played. @param startTime play an animation from startTime @example ```js var animCtrl = this.node.getComponent(cc.Animation); animCtrl.play("linear"); ``` */ play(name? : string, startTime? : number) : AnimationState; /** !#en Plays an additive animation, it will not stop other animations. If there are other animations playing, then will play several animations at the same time. !#zh 播放指定的动画(将不会停止当前播放的动画)。如果没有指定动画,则播放默认动画。 @param name The name of animation to play. If no name is supplied then the default animation will be played. @param startTime play an animation from startTime @example ```js // linear_1 and linear_2 at the same time playing. var animCtrl = this.node.getComponent(cc.Animation); animCtrl.playAdditive("linear_1"); animCtrl.playAdditive("linear_2"); ``` */ playAdditive(name? : string, startTime? : number) : AnimationState; /** !#en Stops an animation named name. If no name is supplied then stops all playing animations that were started with this Animation. <br/> Stopping an animation also Rewinds it to the Start. !#zh 停止指定的动画。如果没有指定名字,则停止当前正在播放的动画。 @param name The animation to stop, if not supplied then stops all playing animations. */ stop(name? : string) : void; /** !#en Pauses an animation named name. If no name is supplied then pauses all playing animations that were started with this Animation. !#zh 暂停当前或者指定的动画。如果没有指定名字,则暂停当前正在播放的动画。 @param name The animation to pauses, if not supplied then pauses all playing animations. */ pause(name? : string) : void; /** !#en Resumes an animation named name. If no name is supplied then resumes all paused animations that were started with this Animation. !#zh 重新播放指定的动画,如果没有指定名字,则重新播放当前正在播放的动画。 @param name The animation to resumes, if not supplied then resumes all paused animations. */ resume(name? : string) : void; /** !#en Make an animation named name go to the specified time. If no name is supplied then make all animations go to the specified time. !#zh 设置指定动画的播放时间。如果没有指定名字,则设置当前播放动画的播放时间。 @param time The time to go to @param name Specified animation name, if not supplied then make all animations go to the time. */ setCurrentTime(time? : number, name? : string) : void; /** !#en Returns the animation state named name. If no animation with the specified name, the function will return null. !#zh 获取当前或者指定的动画状态,如果未找到指定动画剪辑则返回 null。 */ getAnimationState(name : string) : AnimationState; /** !#en Adds a clip to the animation with name newName. If a clip with that name already exists it will be replaced with the new clip. !#zh 添加动画剪辑,并且可以重新设置该动画剪辑的名称。 @param clip the clip to add */ addClip(clip : AnimationClip, newName? : string) : AnimationState; /** !#en Remove clip from the animation list. This will remove the clip and any animation states based on it. If there are animation states depand on the clip are playing or clip is defaultClip, it will not delete the clip. But if force is true, then will always remove the clip and any animation states based on it. If clip is defaultClip, defaultClip will be reset to null !#zh 从动画列表中移除指定的动画剪辑,<br/> 如果依赖于 clip 的 AnimationState 正在播放或者 clip 是 defaultClip 的话,默认是不会删除 clip 的。 但是如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。这时候如果 clip 是 defaultClip,defaultClip 将会被重置为 null。 @param force If force is true, then will always remove the clip and any animation states based on it. */ removeClip(clip : AnimationClip, force : boolean) : void; /** !#en Samples animations at the current state.<br/> This is useful when you explicitly want to set up some animation state, and sample it once. !#zh 对指定或当前动画进行采样。你可以手动将动画设置到某一个状态,然后采样一次。 */ sample(name : string) : void; /** !#en Register animation event callback. The event arguments will provide the AnimationState which emit the event. When play an animation, will auto register the event callback to the AnimationState, and unregister the event callback from the AnimationState when animation stopped. !#zh 注册动画事件回调。 回调的事件里将会附上发送事件的 AnimationState。 当播放一个动画时,会自动将事件注册到对应的 AnimationState 上,停止播放时会将事件从这个 AnimationState 上取消注册。 @param type A string representing the event type to listen for. @param callback The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). @param target The target to invoke the callback, can be null @param useCapture When set to true, the capture argument prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. @example ```js onPlay: function (event) { var state = event.detail; // state instanceof cc.AnimationState var type = event.type; // type === 'play'; } // register event to all animation animation.on('', 'play', this.onPlay, this); ``` */ on(type : string, callback: (param: Event) => void, target : any, useCapture : boolean) : void; /** !#en Unregister animation event callback. !#zh 取消注册动画事件回调。 @param type A string representing the event type being removed. @param callback The callback to remove. @param target The target to invoke the callback, if it's not given, only callback without target will be removed @param useCapture Specifies whether the callback being removed was registered as a capturing callback or not. If not specified, useCapture defaults to false. If a callback was registered twice, one with capture and one without, each must be removed separately. Removal of a capturing callback does not affect a non-capturing version of the same listener, and vice versa. @example ```js // unregister event to all animation animation.off('', 'play', this.onPlay, this); ``` */ off(type : string, callback : Function, target : any, useCapture : boolean) : void; } /** !#en Audio Source. !#zh 音频源组件,能对音频剪辑。 */ export class AudioSource extends Component { /** !#en Is the audio source playing (Read Only). <br/> Note: isPlaying is not supported for Native platforms. !#zh 该音频剪辑是否正播放(只读)。<br/> 注意:Native 平台暂时不支持 isPlaying。 */ isPlaying : boolean; /** !#en The clip of the audio source. !#zh 默认要播放的音频剪辑。 */ clip : AudioClip; /** !#en The volume of the audio source. !#zh 音频源的音量(0.0 ~ 1.0)。 */ volume : number; /** !#en Is the audio source mute? !#zh 是否静音音频源。Mute 是设置音量为 0,取消静音是恢复原来的音量。 */ mute : boolean; /** !#en Is the audio source looping? !#zh 音频源是否循环播放? */ loop : boolean; /** !#en If set to true, the audio source will automatically start playing on onLoad. !#zh 如果设置为true,音频源将在 onLoad 时自动播放。 */ playOnLoad : boolean; /** !#en Plays the clip. !#zh 播放音频剪辑。 */ play() : void; /** !#en Stops the clip. !#zh 停止当前音频剪辑。 */ stop() : void; /** !#en Pause the clip. !#zh 暂停当前音频剪辑。 */ pause() : void; /** !#en Resume the clip. !#zh 恢复播放。 */ resume() : void; /** !#en Rewind playing music. !#zh 从头开始播放。 */ rewind() : void; /** !#en Get current time !#zh 获取当前的播放时间 */ getCurrentTime() : void; /** !#en Set current time !#zh 设置当前的播放时间 */ setCurrentTime(time : number) : void; /** !#en Get audio duration !#zh 获取当前音频的长度 */ getDuration() : void; } /** !#en Button has 4 Transition types When Button state changed: If Transition type is Button.Transition.NONE, Button will do nothing If Transition type is Button.Transition.COLOR, Button will change target's color If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite If Transition type is Button.Transition.SCALE, Button will change target node's scale Button will trigger 5 events: Button.EVENT_TOUCH_DOWN Button.EVENT_TOUCH_UP Button.EVENT_HOVER_IN Button.EVENT_HOVER_MOVE Button.EVENT_HOVER_OUT !#zh 按钮组件。可以被按下,或者点击。</br> 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:</br> -Button.Transition.NONE // 不做任何过渡</br> -Button.Transition.COLOR // 进行颜色之间过渡</br> -Button.Transition.SPRITE // 进行精灵之间过渡</br> -Button.Transition.SCALE // 进行缩放过渡</br> 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):</br> // 以下事件可以在全平台上都触发</br> -cc.Node.EventType.TOUCH_START // 按下时事件</br> -cc.Node.EventType.TOUCH_Move // 按住移动后事件</br> -cc.Node.EventType.TOUCH_END // 按下后松开后事件</br> -cc.Node.EventType.TOUCH_CANCEL // 按下取消事件</br> // 以下事件只在 PC 平台上触发</br> -cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件</br> -cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件</br> -cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件</br> -cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件</br> -cc.Node.EventType.MOUSE_UP // 鼠标松开事件</br> -cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件</br> */ export class Button extends Component { /** !#en Whether the Button is disabled. If true, the Button will trigger event and do transition. !#zh 按钮事件是否被响应,如果为 false,则按钮将被禁用。 */ interactable : boolean; /** !#en When this flag is true, Button target sprite will turn gray when interactable is false. !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰 */ enableAutoGrayEffect : boolean; /** !#en Transition type !#zh 按钮状态改变时过渡方式。 */ transition : Button.Transition; /** !#en Normal state color. !#zh 普通状态下按钮所显示的颜色。 */ normalColor : Color; /** !#en Pressed state color !#zh 按下状态时按钮所显示的颜色。 */ pressedColor : Color; /** !#en Hover state color !#zh 悬停状态下按钮所显示的颜色。 */ hoverColor : Color; /** !#en Disabled state color !#zh 禁用状态下按钮所显示的颜色。 */ disabledColor : Color; /** !#en Color and Scale transition duration !#zh 颜色过渡和缩放过渡时所需时间 */ duration : number; /** !#en When user press the button, the button will zoom to a scale. The final scale of the button equals (button original scale * zoomScale) !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale */ zoomScale : number; /** !#en Normal state sprite !#zh 普通状态下按钮所显示的 Sprite 。 */ normalSprite : SpriteFrame; /** !#en Pressed state sprite !#zh 按下状态时按钮所显示的 Sprite 。 */ pressedSprite : SpriteFrame; /** !#en Hover state sprite !#zh 悬停状态下按钮所显示的 Sprite 。 */ hoverSprite : SpriteFrame; /** !#en Disabled state sprite !#zh 禁用状态下按钮所显示的 Sprite 。 */ disabledSprite : SpriteFrame; /** !#en Transition target. When Button state changed: If Transition type is Button.Transition.NONE, Button will do nothing If Transition type is Button.Transition.COLOR, Button will change target's color If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite !#zh 需要过渡的目标。 当前按钮状态改变规则: -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。 -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。 -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 */ target : Node; /** !#en If Button is clicked, it will trigger event's handler !#zh 按钮的点击事件列表。 */ clickEvents : Component.EventHandler[]; } /** !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。 */ export class Canvas extends Component { /** !#en Current active canvas, the scene should only have one active canvas at the same time. !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。 */ instance : Canvas; /** !#en The desigin resolution for current scene. !#zh 当前场景设计分辨率。 */ designResolution : Size; /** !#en TODO !#zh: 是否优先将设计分辨率高度撑满视图高度。 */ fitHeight : boolean; /** !#en TODO !#zh: 是否优先将设计分辨率宽度撑满视图宽度。 */ fitWidth : boolean; } /** !#en Base class for everything attached to Node(Entity).<br/> <br/> NOTE: Not allowed to use construction parameters for Component's subclasses, because Component is created by the engine. !#zh 所有附加到节点的基类。<br/> <br/> 注意:不允许使用组件的子类构造参数,因为组件是由引擎创建的。 */ export class Component extends Object { /** !#en The node this component is attached to. A component is always attached to a node. !#zh 该组件被附加到的节点。组件总会附加到一个节点。 */ node : Node; /** !#en The uuid for editor. !#zh 组件的 uuid,用于编辑器。 */ uuid : string; /** !#en indicates whether this component is enabled or not. !#zh 表示该组件自身是否启用。 */ enabled : boolean; /** !#en indicates whether this component is enabled and its node is also active in the hierarchy. !#zh 表示该组件是否被启用并且所在的节点也处于激活状态。。 */ enabledInHierarchy : boolean; /** !#en TODO !#zh onLoad 是否被调用。 */ _isOnLoadCalled : boolean; /** !#en Update is called every frame, if the Component is enabled. !#zh 如果该组件启用,则每帧调用 update。 */ update() : void; /** !#en LateUpdate is called every frame, if the Component is enabled. !#zh 如果该组件启用,则每帧调用 LateUpdate。 */ lateUpdate() : void; /** !#en When attaching to an active node or its node first activated. !#zh 当附加到一个激活的节点上或者其节点第一次激活时候调用。 */ onLoad() : void; /** !#en Called before all scripts' update if the Component is enabled the first time. !#zh 如果该组件第一次启用,则在所有组件的 update 之前调用。 */ start() : void; /** !#en Called when this component becomes enabled and its node is active. !#zh 当该组件被启用,并且它的节点也激活时。 */ onEnable() : void; /** !#en Called when this component becomes disabled or its node becomes inactive. !#zh 当该组件被禁用或节点变为无效时调用。 */ onDisable() : void; /** !#en Called when this component will be destroyed. !#zh 当该组件被销毁时调用 */ onDestroy() : void; onFocusInEditor() : void; onLostFocusInEditor() : void; /** !#en Called to initialize the component or node’s properties when adding the component the first time or when the Reset command is used. This function is only called in editor. !#zh 用来初始化组件或节点的一些属性,当该组件被第一次添加到节点上或用户点击了它的 Reset 菜单时调用。这个回调只会在编辑器下调用。 */ resetInEditor() : void; /** !#en Adds a component class to the node. You can also add component to node by passing in the name of the script. !#zh 向节点添加一个组件类,你还可以通过传入脚本的名称来添加组件。 @param typeOrTypename the constructor or the class name of the component to add @example ```js var sprite = node.addComponent(cc.Sprite); var test = node.addComponent("Test"); ``` */ addComponent(typeOrTypename : Function|string) : Component; /** !#en Returns the component of supplied type if the node has one attached, null if it doesn't.<br/> You can also get component in the node by passing in the name of the script. !#zh 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。<br/> 传入参数也可以是脚本的名称。 @example ```js // get sprite component. var sprite = node.getComponent(cc.Sprite); // get custom test calss. var test = node.getComponent("Test"); ``` */ getComponent(typeOrClassName : Function|string) : Component; /** !#en Returns all components of supplied Type in the node. !#zh 返回节点上指定类型的所有组件。 @example ```js var sprites = node.getComponents(cc.Sprite); var tests = node.getComponents("Test"); ``` */ getComponents(typeOrClassName : Function|string) : Component[]; /** !#en Returns the component of supplied type in any of its children using depth first search. !#zh 递归查找所有子节点中第一个匹配指定类型的组件。 @example ```js var sprite = node.getComponentInChildren(cc.Sprite); var Test = node.getComponentInChildren("Test"); ``` */ getComponentInChildren(typeOrClassName : Function|string) : Component; /** !#en Returns the components of supplied type in self or any of its children using depth first search. !#zh 递归查找自身或所有子节点中指定类型的组件 @example ```js var sprites = node.getComponentsInChildren(cc.Sprite); var tests = node.getComponentsInChildren("Test"); ``` */ getComponentsInChildren(typeOrClassName : Function|string) : Component[]; /** !#en If the component's bounding box is different from the node's, you can implement this method to supply a custom axis aligned bounding box (AABB), so the editor's scene view can perform hit test properly. !#zh 如果组件的包围盒与节点不同,您可以实现该方法以提供自定义的轴向对齐的包围盒(AABB), 以便编辑器的场景视图可以正确地执行点选测试。 @param out_rect the Rect to receive the bounding box */ _getLocalBounds(out_rect : Rect) : void; /** !#en onRestore is called after the user clicks the Reset item in the Inspector's context menu or performs an undo operation on this component.<br/> <br/> If the component contains the "internal state", short for "temporary member variables which not included<br/> in its CCClass properties", then you may need to implement this function.<br/> <br/> The editor will call the getset accessors of your component to record/restore the component's state<br/> for undo/redo operation. However, in extreme cases, it may not works well. Then you should implement<br/> this function to manually synchronize your component's "internal states" with its public properties.<br/> Once you implement this function, all the getset accessors of your component will not be called when<br/> the user performs an undo/redo operation. Which means that only the properties with default value<br/> will be recorded or restored by editor.<br/> <br/> Similarly, the editor may failed to reset your component correctly in extreme cases. Then if you need<br/> to support the reset menu, you should manually synchronize your component's "internal states" with its<br/> properties in this function. Once you implement this function, all the getset accessors of your component<br/> will not be called during reset operation. Which means that only the properties with default value<br/> will be reset by editor. This function is only called in editor mode. !#zh onRestore 是用户在检查器菜单点击 Reset 时,对此组件执行撤消操作后调用的。<br/> <br/> 如果组件包含了“内部状态”(不在 CCClass 属性中定义的临时成员变量),那么你可能需要实现该方法。<br/> <br/> 编辑器执行撤销/重做操作时,将调用组件的 get set 来录制和还原组件的状态。 然而,在极端的情况下,它可能无法良好运作。<br/> 那么你就应该实现这个方法,手动根据组件的属性同步“内部状态”。 一旦你实现这个方法,当用户撤销或重做时,组件的所有 get set 都不会再被调用。 这意味着仅仅指定了默认值的属性将被编辑器记录和还原。<br/> <br/> 同样的,编辑可能无法在极端情况下正确地重置您的组件。<br/> 于是如果你需要支持组件重置菜单,你需要在该方法中手工同步组件属性到“内部状态”。<br/> 一旦你实现这个方法,组件的所有 get set 都不会在重置操作时被调用。 这意味着仅仅指定了默认值的属性将被编辑器重置。 <br/> 此方法仅在编辑器下会被调用。 */ onRestore() : void; /** !#en Schedules a custom selector.<br/> If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. !#zh 调度一个自定义的回调函数。<br/> 如果回调函数已调度,那么将不会重复调度它,只会更新时间间隔参数。 @param callback The callback function @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. @param repeat The selector will be executed (repeat + 1) times, you can use kCCRepeatForever for tick infinitely. @param delay The amount of time that the first tick will wait before execution. @example ```js var timeCallback = function (dt) { cc.log("time: " + dt); } this.schedule(timeCallback, 1); ``` */ schedule(callback : Function, interval? : number, repeat? : number, delay? : number) : void; /** !#en Schedules a callback function that runs only once, with a delay of 0 or larger. !#zh 调度一个只运行一次的回调函数,可以指定 0 让回调函数在下一帧立即执行或者在一定的延时之后执行。 @param callback A function wrapped as a selector @param delay The amount of time that the first tick will wait before execution. @example ```js var timeCallback = function (dt) { cc.log("time: " + dt); } this.scheduleOnce(timeCallback, 2); ``` */ scheduleOnce(callback : Function, delay? : number) : void; /** !#en Unschedules a custom callback function. !#zh 取消调度一个自定义的回调函数。 @param callback_fn A function wrapped as a selector @example ```js this.unschedule(_callback); ``` */ unschedule(callback_fn : Function) : void; /** !#en unschedule all scheduled callback functions: custom callback functions, and the 'update' callback function.<br/> Actions are not affected by this method. !#zh 取消调度所有已调度的回调函数:定制的回调函数以及 'update' 回调函数。动作不受此方法影响。 @example ```js this.unscheduleAllCallbacks(); ``` */ unscheduleAllCallbacks() : void; } /** !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users. !#zh EditBox 组件,用于获取用户的输入文本。 */ export class EditBox extends _RendererUnderSG { /** !#en Input string of EditBox. !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。 */ string : string; /** !#en The background image of EditBox. !#zh 输入框的背景图片 */ backgroundImage : SpriteFrame; /** !#en The return key type of EditBox. Note: it is meaningless for web platforms and desktop platforms. !#zh 指定移动设备上面回车按钮的样式。 注意:这个选项对 web 平台与 desktop 平台无效。 */ returnType : EditBox.KeyboardReturnType; /** !#en Set the input flags that are to be applied to the EditBox. !#zh 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。 */ inputFlag : EditBox.InputFlag; /** !#en Set the input mode of the edit box. If you pass ANY, it will create a multiline EditBox. !#zh 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。 */ inputMode : EditBox.InputMode; /** !#en Font size of the input text. !#zh 输入框文本的字体大小 */ fontSize : number; /** !#en Change the lineHeight of displayed text. !#zh 输入框文本的行高。 */ lineHeight : number; /** !#en Font color of the input text. !#zh 输入框文本的颜色。 */ fontColor : Color; /** !#en The display text of placeholder. !#zh 输入框占位符的文本内容。 */ placeholder : string; /** !#en The font size of placeholder. !#zh 输入框占位符的字体大小。 */ placeholderFontSize : number; /** !#en The font color of placeholder. !#zh 输入框最大允许输入的字符个数。 */ placeholderFontColor : Color; /** !#en The maximize input length of EditBox. - If pass a value less than 0, it won't limit the input number of characters. - If pass 0, it doesn't allow input any characters. !#zh 输入框最大允许输入的字符个数。 - 如果值为小于 0 的值,则不会限制输入字符个数。 - 如果值为 0,则不允许用户进行任何输入。 */ maxLength : number; /** !#en The input is always visible and be on top of the game view. !zh 输入框总是可见,并且永远在游戏视图的上面 Note: only available on Web at the moment. */ stayOnTop : boolean; /** !#en Set the tabIndex of the DOM input element, only useful on Web. !#zh 修改 DOM 输入元素的 tabIndex,这个属性只有在 Web 上面修改有意义。 */ tabIndex : number; /** !#en The event handler to be called when EditBox began to edit text. !#zh 开始编辑文本输入框触发的事件回调。 */ editingDidBegin : Component.EventHandler; /** !#en The event handler to be called when EditBox text changes. !#zh 编辑文本输入框时触发的事件回调。 */ textChanged : Component.EventHandler; /** !#en The event handler to be called when EditBox edit ends. !#zh 结束编辑文本输入框时触发的事件回调。 */ editingDidEnded : Component.EventHandler; /** !#en The event handler to be called when return key is pressed. Windows is not supported. !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台 */ editingReturn : Component.EventHandler; /** !#en Let the EditBox get focus, only valid when stayOnTop is true. !#zh 让当前 EditBox 获得焦点,只有在 stayOnTop 为 true 的时候设置有效 Note: only available on Web at the moment. */ setFocus() : void; /** !#en Determine whether EditBox is getting focus or not. !#zh 判断 EditBox 是否获得了焦点 Note: only available on Web at the moment. */ isFocused() : void; } /** !#en The Label Component. !#zh 文字标签组件 */ export class Label extends _RendererUnderSG { /** !#en Content string of label. !#zh 标签显示的文本内容。 */ string : string; /** !#en Horizontal Alignment of label. !#zh 文本内容的水平对齐方式。 */ horizontalAlign : Label.HorizontalAlign; /** !#en Vertical Alignment of label. !#zh 文本内容的垂直对齐方式。 */ verticalAlign : Label.VerticalAlign; /** !#en The actual rendering font size in shrink mode !#zh SHRINK 模式下面文本实际渲染的字体大小 */ actualFontSize : number; /** !#en Font size of label. !#zh 文本字体大小。 */ fontSize : number; /** !#en Line Height of label. !#zh 文本行高。 */ lineHeight : number; /** !#en Overflow of label. !#zh 文字显示超出范围时的处理方式。 */ overflow : Label.Overflow; /** !#en Whether auto wrap label when string width is large than label width. !#zh 是否自动换行。 */ enableWrapText : boolean; /** !#en The font of label. !#zh 文本字体。 */ font : Font; /** !#en Whether use system font name or not. !#zh 是否使用系统字体。 */ isSystemFontUsed : boolean; } /** !#en Outline effect used to change the display, only used for TTF font !#zh 描边效果组件,用于字体描边,只能用于系统字体 */ export class LabelOutline extends Component { /** !#en Change the outline color !#zh 改变描边的颜色 */ color : Color; /** !#en Change the outline width !#zh 改变描边的宽度 */ width : number; } /** !#en The Layout is a container component, use it to arrange child elements easily. !#zh Layout 组件相当于一个容器,能自动对它的所有子节点进行统一排版。 */ export class Layout extends Component { /** !#en The layout type. !#zh 布局类型 */ type : Layout.Type; /** !#en The are three resize modes for Layout. None, resize Container and resize children. !#zh 缩放模式 */ resizeMode : Layout.ResizeMode; /** !#en The cell size for grid layout. !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。 */ cellSize : Size; /** !#en The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first, and then break line on demand. Choose vertical if you want to layout vertically at first . !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 */ startAxis : Layout.AxisDirection; /** !#en The left padding of layout, it only effect the layout in one direction. !#zh 容器内左边距,只会在一个布局方向上生效。 */ paddingLeft : number; /** !#en The right padding of layout, it only effect the layout in one direction. !#zh 容器内右边距,只会在一个布局方向上生效。 */ paddingRight : number; /** !#en The top padding of layout, it only effect the layout in one direction. !#zh 容器内上边距,只会在一个布局方向上生效。 */ paddingTop : number; /** !#en The bottom padding of layout, it only effect the layout in one direction. !#zh 容器内下边距,只会在一个布局方向上生效。 */ paddingBottom : number; /** !#en The distance in x-axis between each element in layout. !#zh 子节点之间的水平间距。 */ spacingX : number; /** !#en The distance in y-axis between each element in layout. !#zh 子节点之间的垂直间距。 */ spacingY : number; /** !#en Only take effect in Vertical layout mode. This option changes the start element's positioning. !#zh 垂直排列子节点的方向。 */ verticalDirection : Layout.VerticalDirection; /** !#en Only take effect in Horizontal layout mode. This option changes the start element's positioning. !#zh 水平排列子节点的方向。 */ horizontalDirection : Layout.HorizontalDirection; /** !#en The padding of layout, it effects the layout in four direction. !#zh 容器内边距,该属性会在四个布局方向上生效。 */ padding : number; } /** !#en The Mask Component !#zh 遮罩组件 */ export class Mask extends _RendererInSG { /** !#en The mask type. !#zh 遮罩类型 */ type : Mask.Type; /** !#en The mask image !#zh 遮罩所需要的贴图 */ spriteFrame : SpriteFrame; /** !#en The alpha threshold.(Not supported Canvas Mode) <br/> The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold. <br/> Should be a float between 0 and 1. <br/> This default to 1 (so alpha test is disabled). !#zh Alpha 阈值(不支持 Canvas 模式)<br/> 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。<br/> 该数值 0 ~ 1 之间的浮点数,默认值为 1(因此禁用 alpha) */ alphaThreshold : number; /** !#en Reverse mask (Not supported Canvas Mode) !#zh 反向遮罩(不支持 Canvas 模式) */ inverted : boolean; /** !#en The segements for ellipse mask. !#zh 椭圆遮罩的曲线细分数 */ segements : number; } /** !#en The PageView control !#zh 页面视图组件 */ export class PageView extends ScrollView { /** !#en Specify the size type of each page in PageView. !#zh 页面视图中每个页面大小类型 */ sizeMode : PageView.SizeMode; /** !#en The page view direction !#zh 页面视图滚动类型 */ direction : PageView.Direction; /** !#en The scroll threshold value, when drag exceeds this value, release the next page will automatically scroll, less than the restore !#zh 滚动临界值,默认单位百分比,当拖拽超出该数值时,松开会自动滚动下一页,小于时则还原。 */ scrollThreshold : number; /** !#en Auto page turning velocity threshold. When users swipe the PageView quickly, it will calculate a velocity based on the scroll distance and time, if the calculated velocity is larger than the threshold, then it will trigger page turning. !#zh 快速滑动翻页临界值。 当用户快速滑动时,会根据滑动开始和结束的距离与时间计算出一个速度值, 该值与此临界值相比较,如果大于临界值,则进行自动翻页。 */ autoPageTurningThreshold : number; /** !#en Change the PageTurning event timing of PageView. !#zh 设置 PageView PageTurning 事件的发送时机。 */ pageTurningEventTiming : number; /** !#en The Page View Indicator !#zh 页面视图指示器组件 */ indicator : PageViewIndicator; /** !#en PageView events callback !#zh 滚动视图的事件回调函数 */ pageEvents : Component.EventHandler[]; /** !#en Returns current page index !#zh 返回当前页面索引 */ getCurrentPageIndex() : number; /** !#en Set current page index !#zh 设置当前页面索引 */ setCurrentPageIndex(index : number) : void; /** !#en Returns all pages of pageview !#zh 返回视图中的所有页面 */ getPages() : Node[]; /** !#en At the end of the current page view to insert a new view !#zh 在当前页面视图的尾部插入一个新视图 */ addPage(page : Node) : void; /** !#en Inserts a page in the specified location !#zh 将页面插入指定位置中 */ insertPage(page : Node, index : number) : void; /** !#en Removes a page from PageView. !#zh 移除指定页面 */ removePage(page : Node) : void; /** !#en Removes a page at index of PageView. !#zh 移除指定下标的页面 */ removePageAtIndex(index : number) : void; /** !#en Removes all pages from PageView !#zh 移除所有页面 */ removeAllPages() : void; /** !#en Scroll PageView to index. !#zh 滚动到指定页面 @param idx index of page. @param timeInSecond scrolling time */ scrollToPage(idx : number, timeInSecond : number) : void; } /** !#en The Page View Indicator Component !#zh 页面视图每页标记组件 */ export class PageViewIndicator extends Component { /** !#en The spriteFrame for each element. !#zh 每个页面标记显示的图片 */ spriteFrame : SpriteFrame; /** !#en The location direction of PageViewIndicator. !#zh 页面标记摆放方向 */ direction : PageViewIndicator.Direction; /** !#en The cellSize for each element. !#zh 每个页面标记的大小 */ cellSize : Size; /** !#en The distance between each element. !#zh 每个页面标记之间的边距 */ spacing : number; /** !#en Set Page View !#zh 设置页面视图 */ setPageView(target : PageView) : void; } /** !#en Visual indicator of progress in some operation. Displays a bar to the user representing how far the operation has progressed. !#zh 进度条组件,可用于显示加载资源时的进度。 */ export class ProgressBar extends Component { /** !#en The targeted Sprite which will be changed progressively. !#zh 用来显示进度条比例的 Sprite 对象。 */ barSprite : Sprite; /** !#en The progress mode, there are two modes supported now: horizontal and vertical. !#zh 进度条的模式 */ mode : ProgressBar.Mode; /** !#en The total width or height of the bar sprite. !#zh 进度条实际的总长度 */ totalLength : number; /** !#en The current progress of the bar sprite. The valid value is between 0-1. !#zh 当前进度值,该数值的区间是 0-1 之间。 */ progress : number; /** !#en Whether reverse the progress direction of the bar sprite. !#zh 进度条是否进行反方向变化。 */ reverse : boolean; } /** Rendering component in scene graph. Maintains a node which will be the scene graph of component's Node. */ export class _RendererInSG extends _SGComponent { } /** The base rendering component which will attach a leaf node to the cocos2d scene graph. */ export class _RendererUnderSG extends _SGComponent { } /** !#en The RichText Component. !#zh 富文本组件 */ export class RichText extends Component { /** !#en Content string of RichText. !#zh 富文本显示的文本内容。 */ string : string; /** !#en Horizontal Alignment of each line in RichText. !#zh 文本内容的水平对齐方式。 */ horizontalAlign : TextAlignment; /** !#en Font size of RichText. !#zh 富文本字体大小。 */ fontSize : number; /** !#en Custom TTF font of RichText !#zh 富文本定制字体 */ font : cc.TTFFont; /** !#en The maximize width of the RichText !#zh 富文本的最大宽度 */ maxWidth : number; /** !#en Line Height of RichText. !#zh 富文本行高。 */ lineHeight : number; /** !#en The image atlas for the img tag. For each src value in the img tag, there should be a valid spriteFrame in the image atlas. !#zh 对于 img 标签里面的 src 属性名称,都需要在 imageAtlas 里面找到一个有效的 spriteFrame,否则 img tag 会判定为无效。 */ imageAtlas : SpriteAtlas; } /** The base class for all rendering component in scene graph. You should override: - _createSgNode - _initSgNode */ export class _SGComponent extends Component { } /** !#en The Scrollbar control allows the user to scroll an image or other view that is too large to see completely !#zh 滚动条组件 */ export class Scrollbar extends Component { /** !#en The "handle" part of the scrollbar. !#zh 作为当前滚动区域位置显示的滑块 Sprite。 */ handle : Sprite; /** !#en The direction of scrollbar. !#zh ScrollBar 的滚动方向。 */ direction : Scrollbar.Direction; /** !#en Whehter enable auto hide or not. !#zh 是否在没有滚动动作时自动隐藏 ScrollBar。 */ enableAutoHide : boolean; /** !#en The time to hide scrollbar when scroll finished. Note: This value is only useful when enableAutoHide is true. !#zh 没有滚动动作后经过多久会自动隐藏。 注意:只要当 “enableAutoHide” 为 true 时,才有效。 */ autoHideTime : number; } /** !#en Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display. !#zh 滚动视图组件 */ export class ScrollView extends Component { /** !#en This is a reference to the UI element to be scrolled. !#zh 可滚动展示内容的节点。 */ content : Node; /** !#en Enable horizontal scroll. !#zh 是否开启水平滚动。 */ horizontal : boolean; /** !#en Enable vertical scroll. !#zh 是否开启垂直滚动。 */ vertical : boolean; /** !#en When inertia is set, the content will continue to move when touch ended. !#zh 是否开启滚动惯性。 */ inertia : boolean; /** !#en It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. A value of 0 will never stop the movement until it reaches to the boundary of scrollview. !#zh 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 */ brake : number; /** !#en When elastic is set, the content will be bounce back when move out of boundary. !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。 */ elastic : boolean; /** !#en The elapse time of bouncing back. A value of 0 will bounce back immediately. !#zh 回弹持续的时间,0 表示将立即反弹。 */ bounceDuration : number; /** !#en The horizontal scrollbar reference. !#zh 水平滚动的 ScrollBar。 */ horizontalScrollBar : Scrollbar; /** !#en The vertical scrollbar reference. !#zh 垂直滚动的 ScrollBar。 */ verticalScrollBar : Scrollbar; /** !#en Scrollview events callback !#zh 滚动视图的事件回调函数 */ scrollEvents : Component.EventHandler[]; /** !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes It's set to true by default. !#zh 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 */ cancelInnerEvents : boolean; /** !#en Scroll the content to the bottom boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图底部。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the bottom boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the bottom of the view. scrollView.scrollToBottom(0.1); ``` */ scrollToBottom(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the top boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图顶部。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the top boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the top of the view. scrollView.scrollToTop(0.1); ``` */ scrollToTop(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the left boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图左边。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the left boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the left of the view. scrollView.scrollToLeft(0.1); ``` */ scrollToLeft(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the right boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图右边。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the right boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the right of the view. scrollView.scrollToRight(0.1); ``` */ scrollToRight(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the top left boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图左上角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the top left boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the upper left corner of the view. scrollView.scrollToTopLeft(0.1); ``` */ scrollToTopLeft(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the top right boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图右上角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the top right boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the top right corner of the view. scrollView.scrollToTopRight(0.1); ``` */ scrollToTopRight(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the bottom left boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图左下角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the bottom left boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the lower left corner of the view. scrollView.scrollToBottomLeft(0.1); ``` */ scrollToBottomLeft(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the bottom right boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图右下角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the bottom right boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the lower right corner of the view. scrollView.scrollToBottomRight(0.1); ``` */ scrollToBottomRight(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll with an offset related to the ScrollView's top left origin, if timeInSecond is omitted, then it will jump to the specific offset immediately. !#zh 视图内容在规定时间内将滚动到 ScrollView 相对左上角原点的偏移位置, 如果 timeInSecond参数不传,则立即滚动到指定偏移位置。 @param offset A Vec2, the value of which each axis between 0 and maxScrollOffset @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the specific offset of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to middle position in 0.1 second in x-axis var maxScrollOffset = this.getMaxScrollOffset(); scrollView.scrollToOffset(cc.p(maxScrollOffset.x / 2, 0), 0.1); ``` */ scrollToOffset(offset : Vec2, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Get the positive offset value corresponds to the content's top left boundary. !#zh 获取滚动视图相对于左上角原点的当前滚动偏移 */ getScrollOffset() : Vec2; /** !#en Get the maximize available scroll offset !#zh 获取滚动视图最大可以滚动的偏移量 */ getMaxScrollOffset() : Vec2; /** !#en Scroll the content to the horizontal percent position of ScrollView. !#zh 视图内容在规定时间内将滚动到 ScrollView 水平方向的百分比位置上。 @param percent A value between 0 and 1. @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the horizontal percent position of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to middle position. scrollView.scrollToBottomRight(0.5, 0.1); ``` */ scrollToPercentHorizontal(percent : number, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the percent position of ScrollView in any direction. !#zh 视图内容在规定时间内进行垂直方向和水平方向的滚动,并且滚动到指定百分比位置上。 @param anchor A point which will be clamp between cc.p(0,0) and cc.p(1,1). @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the percent position of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Vertical scroll to the bottom of the view. scrollView.scrollTo(cc.p(0, 1), 0.1); // Horizontal scroll to view right. scrollView.scrollTo(cc.p(1, 0), 0.1); ``` */ scrollTo(anchor : Vec2, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the vertical percent position of ScrollView. !#zh 视图内容在规定时间内滚动到 ScrollView 垂直方向的百分比位置上。 @param percent A value between 0 and 1. @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the vertical percent position of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. // Scroll to middle position. scrollView.scrollToPercentVertical(0.5, 0.1); */ scrollToPercentVertical(percent : number, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Stop auto scroll immediately !#zh 停止自动滚动, 调用此 API 可以让 Scrollview 立即停止滚动 */ stopAutoScroll() : void; /** !#en Modify the content position. !#zh 设置当前视图内容的坐标点。 @param position The position in content's parent space. */ setContentPosition(position : Vec2) : void; /** !#en Query the content's position in its parent space. !#zh 获取当前视图内容的坐标点。 */ getContentPosition() : Position; } /** !#en The Slider Control !#zh 滑动器组件 */ export class Slider extends Component { /** !#en The "handle" part of the slider !#zh 滑动器滑块按钮部件 */ handle : Button; /** !#en The slider direction !#zh 滑动器方向 */ direction : Slider.Direction; /** !#en The current progress of the slider. The valid value is between 0-1 !#zh 当前进度值,该数值的区间是 0-1 之间 */ progress : number; /** !#en The slider events callback !#zh 滑动器组件事件回调函数 */ slideEvents : Component.EventHandler[]; } /** !#en Renders a sprite in the scene. !#zh 该组件用于在场景中渲染精灵。 */ export class Sprite extends _RendererUnderSG { /** !#en The sprite frame of the sprite. !#zh 精灵的精灵帧 */ spriteFrame : SpriteFrame; /** !#en The sprite render type. !#zh 精灵渲染类型 */ type : Sprite.SpriteType; /** !#en The fill type, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 精灵填充类型,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillType : Sprite.FillType; /** !#en The fill Center, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 填充中心点,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillCenter : Vec2; /** !#en The fill Start, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 填充起始点,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillStart : number; /** !#en The fill Range, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 填充范围,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillRange : number; /** !#en specify the frame is trimmed or not. !#zh 是否使用裁剪模式 */ trim : boolean; /** !#en specify the source Blend Factor. !#zh 指定原图的混合模式 */ srcBlendFactor : BlendFactor; /** !#en specify the destination Blend Factor. !#zh 指定目标的混合模式 */ dstBlendFactor : BlendFactor; /** !#en specify the size tracing mode. !#zh 精灵尺寸调整模式 */ sizeMode : Sprite.SizeMode; /** !#en Change the left sprite's cap inset. !#zh 设置精灵左边框-用于九宫格。 @param insetLeft The values to use for the cap inset. @example ```js sprite.setInsetLeft(5); ``` */ setInsetLeft(insetLeft : number) : void; /** !#en Query the left sprite's cap inset. !#zh 获取精灵左边框 @example ```js var insetLeft = sprite.getInsetLeft(); cc.log("Inset Left:" + insetLeft); ``` */ getInsetLeft() : number; /** !#en Change the top sprite's cap inset. !#zh 设置精灵上边框-用于九宫格。 @param insetTop The values to use for the cap inset. @example ```js sprite.setInsetTop(5); ``` */ setInsetTop(insetTop : number) : void; /** !#en Query the top sprite's cap inset. !#zh 获取精灵上边框。 @example ```js var insetTop = sprite.getInsetTop(); cc.log("Inset Top:" + insetTop); ``` */ getInsetTop() : number; /** !#en Change the right sprite's cap inset. !#zh 设置精灵右边框-用于九宫格。 @param insetRight The values to use for the cap inset. @example ```js sprite.setInsetRight(5); ``` */ setInsetRight(insetRight : number) : void; /** !#en Query the right sprite's cap inset. !#zh 获取精灵右边框。 @example ```js var insetRight = sprite.getInsetRight(); cc.log("Inset Right:" + insetRight); ``` */ getInsetRight() : number; /** !#en Change the bottom sprite's cap inset. !#zh 设置精灵下边框-用于九宫格。 @param bottomInset The values to use for the cap inset. @example ```js sprite.setInsetBottom(5); ``` */ setInsetBottom(bottomInset : number) : void; /** !#en Query the bottom sprite's cap inset. !#zh 获取精灵下边框。 @example ```js var insetBottom = sprite.getInsetBottom(); cc.log("Inset Bottom:" + insetBottom); ``` */ getInsetBottom() : number; } /** !#en A distortion used to change the rendering of simple sprite.If will take effect after sprite component is added. !#zh 扭曲效果组件,用于改变SIMPLE类型sprite的渲染,只有当sprite组件已经添加后,才能起作用. */ export class SpriteDistortion extends Component { /** !#en Change the UV offset for distortion rendering. !#zh 在渲染时改变UV的整体偏移. */ offset : Vec2; /** !#en Change the UV scale for distortion rendering. !#zh 在渲染时改变UV的寻址系数 */ tiling : Vec2; } /** !#en The toggle component is a CheckBox, when it used together with a ToggleGroup, it could be treated as a RadioButton. !#zh Toggle 是一个 CheckBox,当它和 ToggleGroup 一起使用的时候,可以变成 RadioButton。 */ export class Toggle extends Button { /** !#en When this value is true, the check mark component will be enabled, otherwise the check mark component will be disabled. !#zh 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。 */ isChecked : boolean; /** !#en The toggle group which the toggle belongs to, when it is null, the toggle is a CheckBox. Otherwise, the toggle is a RadioButton. !#zh Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox, 否则,Toggle 是一个 RadioButton。 */ toggleGroup : ToggleGroup; /** !#en The image used for the checkmark. !#zh Toggle 处于选中状态时显示的图片 */ checkMark : Sprite; /** !#en If Toggle is clicked, it will trigger event's handler !#zh Toggle 按钮的点击事件列表。 */ checkEvents : Component.EventHandler[]; /** !#en Make the toggle button checked. !#zh 使 toggle 按钮处于选中状态 */ check() : void; /** !#en Make the toggle button unchecked. !#zh 使 toggle 按钮处于未选中状态 */ uncheck() : void; } /** !#en ToggleGroup is not a visiable UI component but a way to modify the behavior of a set of Toggles. Toggles that belong to the same group could only have one of them to be switched on at a time. !#zh ToggleGroup 不是一个可见的 UI 组件,它可以用来修改一组 Toggle 组件的行为。当一组 Toggle 属于同一个 ToggleGroup 的时候, 任何时候只能有一个 Toggle 处于选中状态。 */ export class ToggleGroup extends Component { /** !#en If this setting is true, a toggle could be switched off and on when pressed. If it is false, it will make sure there is always only one toggle could be switched on and the already switched on toggle can't be switched off. !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 */ allowSwitchOff : boolean; } /** !#en cc.VideoPlayer is a component for playing videos, you can use it for showing videos in your game. !#zh Video 组件,用于在游戏中播放视频 */ export class VideoPlayer extends _RendererUnderSG { /** !#en The resource type of videoplayer, REMOTE for remote url and LOCAL for local file path. !#zh 视频来源:REMOTE 表示远程视频 URL,LOCAL 表示本地视频地址。 */ resourceType : VideoPlayer.ResourceType; /** !#en The remote URL of video. !#zh 远程视频的 URL */ remoteURL : string; /** !#en The local video full path. !#zh 本地视频的 URL */ clip : string; /** !#en The current playback time of the now playing item in seconds, you could also change the start playback time. !#zh 指定视频从什么时间点开始播放,单位是秒,也可以用来获取当前视频播放的时间进度。 */ currentTime : number; /** !#en Whether keep the aspect ration of the original video. !#zh 是否保持视频原来的宽高比 */ keepAspectRatio : boolean; /** !#en Whether play video in fullscreen mode. !#zh 是否全屏播放视频 */ isFullscreen : boolean; /** !#en the video player's callback, it will be triggered when certain event occurs, like: playing, paused, stopped and completed. !#zh 视频播放回调函数,该回调函数会在特定情况被触发,比如播放中,暂时,停止和完成播放。 */ videoPlayerEvent : Component.EventHandler[]; /** !#en If a video is paused, call this method could resume playing. If a video is stopped, call this method to play from scratch. !#zh 如果视频被暂停播放了,调用这个接口可以继续播放。如果视频被停止播放了,调用这个接口可以从头开始播放。 */ play() : void; /** !#en If a video is paused, call this method to resume playing. !#zh 如果一个视频播放被暂停播放了,调用这个接口可以继续播放。 */ resume() : void; /** !#en If a video is playing, call this method to pause playing. !#zh 如果一个视频正在播放,调用这个接口可以暂停播放。 */ pause() : void; /** !#en If a video is playing, call this method to stop playing immediately. !#zh 如果一个视频正在播放,调用这个接口可以立马停止播放。 */ stop() : void; } /** !#en Handling touch events in a ViewGroup takes special care, because it's common for a ViewGroup to have children that are targets for different touch events than the ViewGroup itself. To make sure that each view correctly receives the touch events intended for it, ViewGroup should register capture phase event and handle the event propagation properly. Please refer to Scrollview for more information. !#zh ViewGroup的事件处理比较特殊,因为 ViewGroup 里面的子节点关心的事件跟 ViewGroup 本身可能不一样。 为了让子节点能够正确地处理事件,ViewGroup 需要注册 capture 阶段的事件,并且合理地处理 ViewGroup 之间的事件传递。 请参考 ScrollView 的实现来获取更多信息。 */ export class ViewGroup extends Component { } /** !#en cc.WebView is a component for display web pages in the game !#zh WebView 组件,用于在游戏中显示网页 */ export class WebView extends _RendererUnderSG { /** !#en A given URL to be loaded by the WebView, it should have a http or https prefix. !#zh 指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串 */ url : string; /** !#en The webview's event callback , it will be triggered when certain webview event occurs. !#zh WebView 的回调事件,当网页加载过程中,加载完成后或者加载出错时都会回调此函数 */ webviewLoadedEvents : Component.EventHandler[]; } /** !#en Stores and manipulate the anchoring based on its parent. Widget are used for GUI but can also be used for other things. Widget will adjust current node's position and size automatically, but the results after adjustment can not be obtained until the next frame unless you call {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}} manually. !#zh Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。 Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到,除非你先手动调用 {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}}。 */ export class Widget extends Component { /** !#en Specifies an alignment target that can only be one of the parent nodes of the current node. The default value is null, and when null, indicates the current parent. !#zh 指定一个对齐目标,只能是当前节点的其中一个父节点,默认为空,为空时表示当前父节点。 */ target : Node; /** !#en Whether to align the top. !#zh 是否对齐上边。 */ isAlignTop : boolean; /** !#en Vertically aligns the midpoint, This will open the other vertical alignment options cancel. !#zh 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。 */ isAlignVerticalCenter : boolean; /** !#en Whether to align the bottom. !#zh 是否对齐下边。 */ isAlignBottom : boolean; /** !#en Whether to align the left. !#zh 是否对齐左边 */ isAlignLeft : boolean; /** !#en Horizontal aligns the midpoint. This will open the other horizontal alignment options canceled. !#zh 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。 */ isAlignHorizontalCenter : boolean; /** !#en Whether to align the right. !#zh 是否对齐右边。 */ isAlignRight : boolean; /** !#en Whether the stretched horizontally, when enable the left and right alignment will be stretched horizontally, the width setting is invalid (read only). !#zh 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸,此时节点的宽度只读。 */ isStretchWidth : boolean; /** !#en Whether the stretched vertically, when enable the left and right alignment will be stretched vertically, then height setting is invalid (read only) !#zh 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度只读。 */ isStretchHeight : boolean; /** !#en The margins between the top of this node and the top of parent node, the value can be negative, Only available in 'isAlignTop' open. !#zh 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。 */ top : number; /** !#en The margins between the bottom of this node and the bottom of parent node, the value can be negative, Only available in 'isAlignBottom' open. !#zh 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。 */ bottom : number; /** !#en The margins between the left of this node and the left of parent node, the value can be negative, Only available in 'isAlignLeft' open. !#zh 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。 */ left : number; /** !#en The margins between the right of this node and the right of parent node, the value can be negative, Only available in 'isAlignRight' open. !#zh 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。 */ right : number; /** !#en Horizontal aligns the midpoint offset value, the value can be negative, Only available in 'isAlignHorizontalCenter' open. !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。 */ horizontalCenter : number; /** !#en Vertical aligns the midpoint offset value, the value can be negative, Only available in 'isAlignVerticalCenter' open. !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。 */ verticalCenter : number; /** !#en If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin. !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 */ isAbsoluteHorizontalCenter : boolean; /** !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin. !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 */ isAbsoluteVerticalCenter : boolean; /** !#en If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. !#zh 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 */ isAbsoluteTop : boolean; /** !#en If true, bottom is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. !#zh 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 */ isAbsoluteBottom : boolean; /** !#en If true, left is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. !#zh 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 */ isAbsoluteLeft : boolean; /** !#en If true, right is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. !#zh 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 */ isAbsoluteRight : boolean; /** !#en TODO !#zh 开启后仅会在 onEnable 的当帧结束时对齐一次,然后立刻禁用当前组件。 这样便于脚本或动画继续控制当前节点。 注意:onEnable 时所在的那一帧仍然会进行对齐。 */ isAlignOnce : boolean; /** !#en Immediately perform the widget alignment. You need to manually call this method only if you need to get the latest results after the alignment before the end of current frame. !#zh 立刻执行 widget 对齐操作。这个接口一般不需要手工调用。 只有当你需要在当前帧结束前获得 widget 对齐后的最新结果时才需要手动调用这个方法。 @example ```js widget.top = 10; // change top margin cc.log(widget.node.y); // not yet changed widget.updateAlignment(); cc.log(widget.node.y); // changed ``` */ updateAlignment() : void; } /** undefined */ export class Graphics extends _RendererUnderSG { /** !#en Current line width. !#zh 当前线条宽度 */ lineWidth : number; /** !#en lineJoin determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together. !#zh lineJoin 用来设置2个长度不为0的相连部分(线段,圆弧,曲线)如何连接在一起的属性。 */ lineJoin : Graphics.LineJoin; /** !#en lineCap determines how the end points of every line are drawn. !#zh lineCap 指定如何绘制每一条线段末端。 */ lineCap : Graphics.LineCap; /** !#en stroke color !#zh 线段颜色 */ strokeColor : Color; /** !#en fill color !#zh 填充颜色 */ fillColor : Color; /** !#en Sets the miter limit ratio !#zh 设置斜接面限制比例 */ miterLimit : number; /** !#en Move path start point to (x,y). !#zh 移动路径起点到坐标(x, y) @param x The x axis of the coordinate for the end point. @param y The y axis of the coordinate for the end point. */ moveTo(x? : number, y? : number) : void; /** !#en Adds a straight line to the path !#zh 绘制直线路径 @param x The x axis of the coordinate for the end point. @param y The y axis of the coordinate for the end point. */ lineTo(x? : number, y? : number) : void; /** !#en Adds a cubic Bézier curve to the path !#zh 绘制三次贝赛尔曲线路径 @param c1x The x axis of the coordinate for the first control point. @param c1y The y axis of the coordinate for first control point. @param c2x The x axis of the coordinate for the second control point. @param c2y The y axis of the coordinate for the second control point. @param x The x axis of the coordinate for the end point. @param y The y axis of the coordinate for the end point. */ bezierCurveTo(c1x? : number, c1y? : number, c2x? : number, c2y? : number, x? : number, y? : number) : void; /** !#en Adds a quadratic Bézier curve to the path !#zh 绘制二次贝赛尔曲线路径 @param cx The x axis of the coordinate for the control point. @param cy The y axis of the coordinate for the control point. @param x The x axis of the coordinate for the end point. @param y The y axis of the coordinate for the end point. */ quadraticCurveTo(cx? : number, cy? : number, x? : number, y? : number) : void; /** !#en Adds an arc to the path which is centered at (cx, cy) position with radius r starting at startAngle and ending at endAngle going in the given direction by counterclockwise (defaulting to false). !#zh 绘制圆弧路径。圆弧路径的圆心在 (cx, cy) 位置,半径为 r ,根据 counterclockwise (默认为false)指定的方向从 startAngle 开始绘制,到 endAngle 结束。 @param cx The x axis of the coordinate for the center point. @param cy The y axis of the coordinate for the center point. @param r The arc's radius. @param startAngle The angle at which the arc starts, measured clockwise from the positive x axis and expressed in radians. @param endAngle The angle at which the arc ends, measured clockwise from the positive x axis and expressed in radians. @param counterclockwise An optional Boolean which, if true, causes the arc to be drawn counter-clockwise between the two angles. By default it is drawn clockwise. */ arc(cx? : number, cy? : number, r? : number, startAngle? : number, endAngle? : number, counterclockwise? : number) : void; /** !#en Adds an ellipse to the path. !#zh 绘制椭圆路径。 @param cx The x axis of the coordinate for the center point. @param cy The y axis of the coordinate for the center point. @param rx The ellipse's x-axis radius. @param ry The ellipse's y-axis radius. */ ellipse(cx? : number, cy? : number, rx? : number, ry? : number) : void; /** !#en Adds an circle to the path. !#zh 绘制圆形路径。 @param cx The x axis of the coordinate for the center point. @param cy The y axis of the coordinate for the center point. @param r The circle's radius. */ circle(cx? : number, cy? : number, r? : number) : void; /** !#en Adds an rectangle to the path. !#zh 绘制矩形路径。 @param x The x axis of the coordinate for the rectangle starting point. @param y The y axis of the coordinate for the rectangle starting point. @param w The rectangle's width. @param h The rectangle's height. */ rect(x? : number, y? : number, w? : number, h? : number) : void; /** !#en Adds an round corner rectangle to the path. !#zh 绘制圆角矩形路径。 @param x The x axis of the coordinate for the rectangle starting point. @param y The y axis of the coordinate for the rectangle starting point. @param w The rectangles width. @param h The rectangle's height. @param r The radius of the rectangle. */ roundRect(x? : number, y? : number, w? : number, h? : number, r? : number) : void; /** !#en Draws a filled rectangle. !#zh 绘制填充矩形。 @param x The x axis of the coordinate for the rectangle starting point. @param y The y axis of the coordinate for the rectangle starting point. @param w The rectangle's width. @param h The rectangle's height. */ fillRect(x? : number, y? : number, w? : number, h? : number) : void; /** !#en Erasing any previously drawn content. !#zh 擦除之前绘制的所有内容的方法。 */ clear() : void; /** !#en Causes the point of the pen to move back to the start of the current path. It tries to add a straight line from the current point to the start. !#zh 将笔点返回到当前路径起始点的。它尝试从当前点到起始点绘制一条直线。 */ close() : void; /** !#en Strokes the current or given path with the current stroke style. !#zh 根据当前的画线样式,绘制当前或已经存在的路径。 */ stroke() : void; /** !#en Fills the current or given path with the current fill style. !#zh 根据当前的画线样式,填充当前或已经存在的路径。 */ stroke() : void; } /** !#en <p> The base class of event listener. <br/> If you need custom listener which with different callback, you need to inherit this class. <br/> For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard, <br/> EventListenerTouchOneByOne, EventListenerCustom. </p> !#zh 封装用户的事件处理逻辑。 注意:这是一个抽象类,开发者不应该直接实例化这个类,请参考 {{#crossLink "EventListener/create:method"}}cc.EventListener.create{{/crossLink}}。 */ export class EventListener { /** Constructor */ EventListener(type : number, listenerID : number, callback : number) : EventListener; /** !#en Checks whether the listener is available. !#zh 检测监听器是否有效 */ checkAvailable() : boolean; /** !#en Clones the listener, its subclasses have to override this method. !#zh 克隆监听器,它的子类必须重写此方法。 */ clone() : EventListener; /** !#en Enables or disables the listener !#zh 启用或禁用监听器。 */ setEnabled(enabled : boolean) : void; /** !#en Checks whether the listener is enabled !#zh 检查监听器是否可用。 */ isEnabled() : boolean; /** !#en The type code of unknown event listener. !#zh 未知的事件监听器类型 */ UNKNOWN : number; /** !#en The type code of keyboard event listener. !#zh 键盘事件监听器类型 */ KEYBOARD : number; /** !#en The type code of focus event listener. !#zh 加速器事件监听器类型 */ ACCELERATION : number; /** !#en Create a EventListener object with configuration including the event type, handlers and other parameters. In handlers, this refer to the event listener object itself. You can also pass custom parameters in the configuration object, all custom parameters will be polyfilled into the event listener object and can be accessed in handlers. !#zh 通过指定不同的 Event 对象来设置想要创建的事件监听器。 @param argObj a json object @example ```js // Create KEYBOARD EventListener. cc.EventListener.create({ event: cc.EventListener.KEYBOARD, onKeyPressed: function (keyCode, event) { cc.log('pressed key: ' + keyCode); }, onKeyReleased: function (keyCode, event) { cc.log('released key: ' + keyCode); } }); // Create ACCELERATION EventListener. cc.EventListener.create({ event: cc.EventListener.ACCELERATION, callback: function (acc, event) { cc.log('acc: ' + keyCode); } }); ``` */ create(argObj : any) : EventListener; } /** !#en <p> cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching. <br/> <br/> The EventListener list is managed in such way so that event listeners can be added and removed <br/> while events are being dispatched. </p> !#zh 事件管理器,它主要管理事件监听器注册和派发系统事件。 原始设计中,它支持鼠标,触摸,键盘,陀螺仪和自定义事件。 在 Creator 的设计中,鼠标,触摸和自定义事件的监听和派发请参考 http://cocos.com/docs/creator/scripting/events.html。 */ export class eventManager { /** !#en Pauses all listeners which are associated the specified target. !#zh 暂停传入的 node 相关的所有监听器的事件响应。 */ pauseTarget(node : Node, recursive : boolean) : void; /** !#en Resumes all listeners which are associated the specified target. !#zh 恢复传入的 node 相关的所有监听器的事件响应。 */ resumeTarget(node : Node, recursive : boolean) : void; /** !#en Query whether the specified event listener id has been added. !#zh 查询指定的事件 ID 是否存在 @param listenerID The listener id. */ hasEventListener(listenerID : string|number) : boolean; /** !#en <p> Adds a event listener for a specified event.<br/> if the parameter "nodeOrPriority" is a node, it means to add a event listener for a specified event with the priority of scene graph.<br/> if the parameter "nodeOrPriority" is a Number, it means to add a event listener for a specified event with the fixed priority.<br/> </p> !#zh 将事件监听器添加到事件管理器中。<br/> 如果参数 “nodeOrPriority” 是节点,优先级由 node 的渲染顺序决定,显示在上层的节点将优先收到事件。<br/> 如果参数 “nodeOrPriority” 是数字,优先级则固定为该参数的数值,数字越小,优先级越高。<br/> @param listener The listener of a specified event or a object of some event parameters. @param nodeOrPriority The priority of the listener is based on the draw order of this node or fixedPriority The fixed priority of the listener. */ addListener(listener : EventListener|any, nodeOrPriority : Node|number) : EventListener; /** !#en Remove a listener. !#zh 移除一个已添加的监听器。 @param listener an event listener or a registered node target @example ```js // 1. remove eventManager add Listener; var mouseListener1 = cc.eventManager.addListener({ event: cc.EventListener.MOUSE, onMouseDown: function(keyCode, event){ }, onMouseUp: function(keyCode, event){ }, onMouseMove: function () { }, onMouseScroll: function () { } }, node); cc.eventManager.removeListener(mouseListener1); // 2. remove eventListener create Listener; var mouseListener2 = cc.EventListener.create({ event: cc.EventListener.MOUSE, onMouseDown: function(keyCode, event){ }, onMouseUp: function(keyCode, event){ }, onMouseMove: function () { }, onMouseScroll: function () { } }); cc.eventManager.removeListener(mouseListener2); ``` */ removeListener(listener: (type: number, listenerID: number, callback: number) => void) : void; /** !#en Removes all listeners with the same event listener type or removes all listeners of a node. !#zh 移除注册到 eventManager 中指定类型的所有事件监听器。<br/> 1. 如果传入的第一个参数类型是 Node,那么事件管理器将移除与该对象相关的所有事件监听器。 (如果第二参数 recursive 是 true 的话,就会连同该对象的子控件上所有的事件监听器也一并移除)<br/> 2. 如果传入的第一个参数类型是 Number(该类型 EventListener 中定义的事件类型), 那么事件管理器将移除该类型的所有事件监听器。<br/> 下列是目前存在监听器类型: <br/> cc.EventListener.UNKNOWN <br/> cc.EventListener.KEYBOARD <br/> cc.EventListener.ACCELERATION,<br/> @param listenerType listenerType or a node */ removeListeners(listenerType : number|Node, recursive : boolean) : void; /** !#en Removes all listeners !#zh 移除所有事件监听器。 */ removeAllListeners() : void; /** !#en Sets listener's priority with fixed value. !#zh 设置 FixedPriority 类型监听器的优先级。 @param listener Constructor */ setPriority(listener: (type: number, listenerID: number, callback: number) => void, fixedPriority : number) : void; /** !#en Whether to enable dispatching events !#zh 启用或禁用事件管理器,禁用后不会分发任何事件。 */ setEnabled(enabled : boolean) : void; /** !#en Checks whether dispatching events is enabled !#zh 检测事件管理器是否启用。 */ isEnabled() : boolean; } /** !#en The System event, it currently supports the key events and accelerometer events !#zh 系统事件,它目前支持按键事件和重力感应事件 */ export class SystemEvent extends EventTarget { } /** !#en The touch event class !#zh 封装了触摸相关的信息。 */ export class Touch { /** !#en Returns the current touch location in OpenGL coordinates.、 !#zh 获取当前触点位置。 */ getLocation() : Vec2; /** !#en Returns X axis location value. !#zh 获取当前触点 X 轴位置。 */ getLocationX() : number; /** !#en Returns Y axis location value. !#zh 获取当前触点 Y 轴位置。 */ getLocationY() : number; /** !#en Returns the previous touch location in OpenGL coordinates. !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocation() : Vec2; /** !#en Returns the start touch location in OpenGL coordinates. !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 */ getStartLocation() : Vec2; /** !#en Returns the delta distance from the previous touche to the current one in screen coordinates. !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 */ getDelta() : Vec2; /** !#en Returns the current touch location in screen coordinates. !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 */ getLocationInView() : Vec2; /** !#en Returns the previous touch location in screen coordinates. !#zh 获取触点在上一次事件时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocationInView() : Vec2; /** !#en Returns the start touch location in screen coordinates. !#zh 获取触点落下时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 */ getStartLocationInView() : Vec2; /** !#en Returns the id of cc.Touch. !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 */ getID() : number; /** !#en Sets information to touch. !#zh 设置触摸相关的信息。用于监控触摸事件。 */ setTouchInfo(id : number, x : number, y : number) : void; } /** Loader for resource loading process. It's a singleton object. */ export class loader extends Pipeline { /** The downloader in cc.loader's pipeline, it's by default the first pipe. It's used to download files with several handlers: pure text, image, script, audio, font, uuid. You can add your own download function with addDownloadHandlers */ downloader : any; /** The downloader in cc.loader's pipeline, it's by default the second pipe. It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid. You can add your own download function with addLoadHandlers */ loader : any; /** Add custom supported types handler or modify existing type handler for download process. @param extMap Custom supported types with corresponded handler @example ```js cc.loader.addDownloadHandlers({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ addDownloadHandlers(extMap : any) : void; /** Add custom supported types handler or modify existing type handler for load process. @param extMap Custom supported types with corresponded handler @example ```js cc.loader.addLoadHandlers({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ addLoadHandlers(extMap : any) : void; /** Load resources with a progression callback and a complete callback. The progression callback is the same as Pipeline's {{#crossLink "Pipeline/onProgress:method"}}onProgress{{/crossLink}} The complete callback is almost the same as Pipeline's {{#crossLink "Pipeline/onComplete:method"}}onComplete{{/crossLink}} The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter. @param resources Url list in an array @param progressCallback Callback invoked when progression change @param completeCallback Callback invoked when all resources loaded @example ```js cc.loader.load('a.png', function (err, tex) { cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D)); }); cc.loader.load('http://example.com/a.png', function (err, tex) { cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D)); }); cc.loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) { cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D)); }); cc.loader.load(['a.png', 'b.json'], function (errors, results) { if (errors) { for (var i = 0; i < errors.length; i++) { cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i])); } } var aTex = results.getContent('a.png'); var bJsonObj = results.getContent('b.json'); }); ``` */ load(resources : string|any[], progressCallback? : Function, completeCallback : Function) : void; /** Load resources from the "resources" folder inside the "assets" folder of your project.<br> <br> Note: All asset urls in Creator use forward slashes, urls using backslashes will not work. @param url Url of the target resource. The url is relative to the "resources" folder, extensions must be omitted. @param type Only asset of type will be loaded if this argument is supplied. @param completeCallback Callback invoked when the resource loaded. @example ```js // load the prefab (project/assets/resources/misc/character/cocos) from resources folder cc.loader.loadRes('misc/character/cocos', function (err, prefab) { if (err) { cc.error(err.message || err); return; } cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab)); }); // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { if (err) { cc.error(err.message || err); return; } cc.log('Result should be a sprite frame: ' + (spriteFrame instanceof cc.SpriteFrame)); }); ``` */ loadRes(url : string, type? : Function, completeCallback: (error: Error, resource: any) => void) : void; /** Load all assets in a folder inside the "assets/resources" folder of your project.<br> <br> Note: All asset urls in Creator use forward slashes, urls using backslashes will not work. @param url Url of the target folder. The url is relative to the "resources" folder, extensions must be omitted. @param type Only asset of type will be loaded if this argument is supplied. @param completeCallback A callback which is called when all assets have been loaded, or an error occurs. @example ```js // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame cc.loader.loadResDir('imgs/cocos', function (err, assets) { if (err) { cc.error(err); return; } var texture = assets[0]; var spriteFrame = assets[1]; }); // load all textures in "resources/imgs/" cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) { if (err) { cc.error(err); return; } var texture1 = textures[0]; var texture2 = textures[1]; }); ``` */ loadResDir(url : string, type? : Function, completeCallback: (error: Error, assets: any[]) => void) : void; /** Get resource data by id. <br> When you load resources with {{#crossLink "loader/load:method"}}{{/crossLink}} or {{#crossLink "loader/loadRes:method"}}{{/crossLink}}, the url will be the unique identity of the resource. After loaded, you can acquire them by passing the url to this API. @param type Only asset of type will be returned if this argument is supplied. */ getRes(url : string, type? : Function) : any; /** !#en Release the content of an asset or an array of assets by uuid. Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content. For example, if you release a texture, the texture asset and its gl texture data will be freed up. In complexe project, you can use this function with {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} to free up memory in critical circumstances. Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors. If you only want to remove the cache of an asset, please use {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} !#zh 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。 在复杂项目中,我们建议你结合 {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。 如果你只想删除一个资源的缓存引用,请使用 {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} @example ```js // Release a texture which is no longer need cc.loader.release(texture); // Release all dependencies of a loaded prefab var deps = cc.loader.getDependsRecursively('prefabs/sample'); cc.loader.release(deps); // If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up. // If you have some other nodes share a texture in this prefab, you can skip it in two ways: // 1. Forbid auto release a texture before release cc.loader.setAutoRelease(texture2d, false); // 2. Remove it from the dependencies array var deps = cc.loader.getDependsRecursively('prefabs/sample'); var index = deps.indexOf(texture2d._uuid); if (index !== -1) deps.splice(index, 1); cc.loader.release(deps); ``` */ release(asset : Asset|RawAsset|string|any[]) : void; /** !#en Release the asset by its object. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. !#zh 通过资源对象自身来释放资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} */ releaseAsset(asset : Asset) : void; /** !#en Release the asset loaded by {{#crossLink "loader/loadRes:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. !#zh 释放通过 {{#crossLink "loader/loadRes:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} @param type Only asset of type will be released if this argument is supplied. */ releaseRes(url : string, type? : Function) : void; /** !#en Release the all assets loaded by {{#crossLink "loader/loadResDir:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. !#zh 释放通过 {{#crossLink "loader/loadResDir:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} @param type Only asset of type will be released if this argument is supplied. */ releaseResDir(url : string, type? : Function) : void; /** !#en Resource all assets. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. !#zh 释放所有资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} */ releaseAll() : void; /** !#en Indicates whether to release the asset when loading a new scene.<br> By default, when loading a new scene, all assets in the previous scene will be released or preserved according to whether the previous scene checked the "Auto Release Assets" option. On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` will not be affected by that option, remain not released by default.<br> Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.<br> <br> See: {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} !#zh 设置当场景切换时是否自动释放资源。<br> 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br> 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。<br> <br> 参考:{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} @param assetOrUrlOrUuid asset object or the raw asset's url or uuid @param autoRelease indicates whether should release automatically @example ```js // auto release the texture event if "Auto Release Assets" disabled in current scene cc.loader.setAutoRelease(texture2d, true); // don't release the texture even if "Auto Release Assets" enabled in current scene cc.loader.setAutoRelease(texture2d, false); // first parameter can be url cc.loader.setAutoRelease(audioUrl, false); ``` */ setAutoRelease(assetOrUrlOrUuid : Asset|string, autoRelease : boolean) : void; /** !#en Indicates whether to release the asset and its referenced other assets when loading a new scene.<br> By default, when loading a new scene, all assets in the previous scene will be released or preserved according to whether the previous scene checked the "Auto Release Assets" option. On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` will not be affected by that option, remain not released by default.<br> Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.<br> <br> See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} !#zh 设置当场景切换时是否自动释放资源及资源引用的其它资源。<br> 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br> 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。<br> <br> 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} @param assetOrUrlOrUuid asset object or the raw asset's url or uuid @param autoRelease indicates whether should release automatically @example ```js // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene cc.loader.setAutoReleaseRecursively(spriteFrame, true); // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene cc.loader.setAutoReleaseRecursively(spriteFrame, false); // don't release the Prefab and all the referenced assets cc.loader.setAutoReleaseRecursively(prefab, false); ``` */ setAutoReleaseRecursively(assetOrUrlOrUuid : Asset|string, autoRelease : boolean) : void; /** !#en Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.<br> <br> See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} !#zh 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。<br> <br> 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} @param assetOrUrl asset object or the raw asset's url */ isAutoRelease(assetOrUrl : Asset|string) : boolean; } /** !#en LoadingItems is the queue of items which can flow them into the loading pipeline.</br> Please don't construct it directly, use {{#crossLink "LoadingItems.create"}}LoadingItems.create{{/crossLink}} instead, because we use an internal pool to recycle the queues.</br> It hold a map of items, each entry in the map is a url to object key value pair.</br> Each item always contains the following property:</br> - id: The identification of the item, usually it's identical to url</br> - url: The url </br> - type: The type, it's the extension name of the url by default, could be specified manually too.</br> - error: The error happened in pipeline will be stored in this property.</br> - content: The content processed by the pipeline, the final result will also be stored in this property.</br> - complete: The flag indicate whether the item is completed by the pipeline.</br> - states: An object stores the states of each pipe the item go through, the state can be: Pipeline.ItemState.WORKING | Pipeline.ItemState.ERROR | Pipeline.ItemState.COMPLETE</br> </br> Item can hold other custom properties.</br> Each LoadingItems object will be destroyed for recycle after onComplete callback</br> So please don't hold its reference for later usage, you can copy properties in it though. !#zh LoadingItems 是一个加载对象队列,可以用来输送加载对象到加载管线中。</br> 请不要直接使用 new 构造这个类的对象,你可以使用 {{#crossLink "LoadingItems.create"}}LoadingItems.create{{/crossLink}} 来创建一个新的加载队列,这样可以允许我们的内部对象池回收并重利用加载队列。 它有一个 map 属性用来存放加载项,在 map 对象中已 url 为 key 值。</br> 每个对象都会包含下列属性:</br> - id:该对象的标识,通常与 url 相同。</br> - url:路径 </br> - type: 类型,它这是默认的 URL 的扩展名,可以手动指定赋值。</br> - error:pipeline 中发生的错误将被保存在这个属性中。</br> - content: pipeline 中处理的临时结果,最终的结果也将被存储在这个属性中。</br> - complete:该标志表明该对象是否通过 pipeline 完成。</br> - states:该对象存储每个管道中对象经历的状态,状态可以是 Pipeline.ItemState.WORKING | Pipeline.ItemState.ERROR | Pipeline.ItemState.COMPLETE</br> </br> 对象可容纳其他自定义属性。</br> 每个 LoadingItems 对象都会在 onComplete 回调之后被销毁,所以请不要持有它的引用并在结束回调之后依赖它的内容执行任何逻辑,有这种需求的话你可以提前复制它的内容。 */ export class LoadingItems extends CallbacksInvoker { /** !#en This is a callback which will be invoked while an item flow out the pipeline. You can pass the callback function in LoadingItems.create or set it later. !#zh 这个回调函数将在 item 加载结束后被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 @param completedCount The number of the items that are already completed. @param totalCount The total number of the items. @param item The latest item which flow out the pipeline. @example ```js loadingItems.onProgress = function (completedCount, totalCount, item) { var progress = (100 * completedCount / totalCount).toFixed(2); cc.log(progress + '%'); } ``` */ onProgress(completedCount : number, totalCount : number, item : any) : void; /** !#en This is a callback which will be invoked while all items is completed, You can pass the callback function in LoadingItems.create or set it later. !#zh 该函数将在加载队列全部完成时被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 @param errors All errored urls will be stored in this array, if no error happened, then it will be null @param items All items. @example ```js loadingItems.onComplete = function (errors, items) { if (error) cc.log('Completed with ' + errors.length + ' errors'); else cc.log('Completed ' + items.totalCount + ' items'); } ``` */ onComplete(errors : any[], items : LoadingItems) : void; /** !#en The map of all items. !#zh 存储所有加载项的对象。 */ map : any; /** !#en The map of completed items. !#zh 存储已经完成的加载项。 */ completed : any; /** !#en Total count of all items. !#zh 所有加载项的总数。 */ totalCount : number; /** !#en Total count of completed items. !#zh 所有完成加载项的总数。 */ completedCount : number; /** !#en Activated or not. !#zh 是否启用。 */ active : boolean; /** !#en The constructor function of LoadingItems, this will use recycled LoadingItems in the internal pool if possible. You can pass onProgress and onComplete callbacks to visualize the loading process. !#zh LoadingItems 的构造函数,这种构造方式会重用内部对象缓冲池中的 LoadingItems 队列,以尽量避免对象创建。 你可以传递 onProgress 和 onComplete 回调函数来获知加载进度信息。 @param pipeline The pipeline to process the queue. @param urlList The items array. @param onProgress The progression callback, refer to {{#crossLink "LoadingItems.onProgress"}}{{/crossLink}} @param onComplete The completion callback, refer to {{#crossLink "LoadingItems.onComplete"}}{{/crossLink}} @example ```js LoadingItems.create(cc.loader, ['a.png', 'b.plist'], function (completedCount, totalCount, item) { var progress = (100 * completedCount / totalCount).toFixed(2); cc.log(progress + '%'); }, function (errors, items) { if (errors) { for (var i = 0; i < errors.length; ++i) { cc.log('Error url: ' + errors[i] + ', error: ' + items.getError(errors[i])); } } else { var result_a = items.getContent('a.png'); // ... } }) ``` */ create(pipeline : Pipeline, urlList : any[], onProgress : Function, onComplete : Function) : LoadingItems; /** !#en Retrieve the LoadingItems queue object for an item. !#zh 通过 item 对象获取它的 LoadingItems 队列。 @param item The item to query */ getQueue(item : any) : LoadingItems; /** !#en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening. !#zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。 @param item The item which has completed */ itemComplete(item : any) : void; /** !#en Add urls to the LoadingItems queue. !#zh 向一个 LoadingItems 队列添加加载项。 @param urlList The url list to be appended, the url can be object or string */ append(urlList : any[]) : any[]; /** !#en Complete a LoadingItems queue, please do not call this method unless you know what's happening. !#zh 完成一个 LoadingItems 队列,请不要调用这个函数,除非你知道自己在做什么。 */ allComplete() : void; /** !#en Check whether all items are completed. !#zh 检查是否所有加载项都已经完成。 */ isCompleted() : boolean; /** !#en Check whether an item is completed. !#zh 通过 id 检查指定加载项是否已经加载完成。 @param id The item's id. */ isItemCompleted(id : string) : boolean; /** !#en Check whether an item exists. !#zh 通过 id 检查加载项是否存在。 @param id The item's id. */ exists(id : string) : boolean; /** !#en Returns the content of an internal item. !#zh 通过 id 获取指定对象的内容。 @param id The item's id. */ getContent(id : string) : any; /** !#en Returns the error of an internal item. !#zh 通过 id 获取指定对象的错误信息。 @param id The item's id. */ getError(id : string) : any; /** !#en Add a listener for an item, the callback will be invoked when the item is completed. !#zh 监听加载项(通过 key 指定)的完成事件。 @param callback can be null @param target can be null */ addListener(key : string, callback : Function, target : any) : boolean; /** !#en Check if the specified key has any registered callback. </br> If a callback is also specified, it will only return true if the callback is registered. !#zh 检查指定的加载项是否有完成事件监听器。</br> 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。 */ hasListener(key : string, callback? : Function, target? : any) : boolean; /** !#en Removes a listener. </br> It will only remove when key, callback, target all match correctly. !#zh 移除指定加载项已经注册的完成事件监听器。</br> 只会删除 key, callback, target 均匹配的监听器。 */ remove(key : string, callback : Function, target : any) : boolean; /** !#en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target. !#zh 删除指定目标的所有完成事件监听器。 @param key The event key to be removed or the target to be removed */ removeAllListeners(key : string|any) : void; /** !#en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening. !#zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。 @param id The item url */ itemComplete(id : string) : void; /** !#en Destroy the LoadingItems queue, the queue object won't be garbage collected, it will be recycled, so every after destroy is not reliable. !#zh 销毁一个 LoadingItems 队列,这个队列对象会被内部缓冲池回收,所以销毁后的所有内部信息都是不可依赖的。 */ destroy() : void; } /** !#en A pipeline describes a sequence of manipulations, each manipulation is called a pipe.</br> It's designed for loading process. so items should be urls, and the url will be the identity of each item during the process.</br> A list of items can flow in the pipeline and it will output the results of all pipes.</br> They flow in the pipeline like water in tubes, they go through pipe by pipe separately.</br> Finally all items will flow out the pipeline and the process is finished. !#zh pipeline 描述了一系列的操作,每个操作都被称为 pipe。</br> 它被设计来做加载过程的流程管理。所以 item 应该是 url,并且该 url 将是在处理中的每个 item 的身份标识。</br> 一个 item 列表可以在 pipeline 中流动,它将输出加载项经过所有 pipe 之后的结果。</br> 它们穿过 pipeline 就像水在管子里流动,将会按顺序流过每个 pipe。</br> 最后当所有加载项都流出 pipeline 时,整个加载流程就结束了。 */ export class Pipeline { /** !#en Constructor, pass an array of pipes to construct a new Pipeline, the pipes will be chained in the given order.</br> A pipe is an object which must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.</br> It can also include `async` property to identify whether it's an asynchronous process. !#zh 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。</br> 一个 pipe 就是一个对象,它包含了字符串类型的 ‘id’ 和 ‘handle’ 函数,在 pipeline 中 id 必须是唯一的。</br> 它还可以包括 ‘async’ 属性以确定它是否是一个异步过程。 @example ```js var pipeline = new Pipeline([ { id: 'Downloader', handle: function (item, callback) {}, async: true }, {id: 'Parser', handle: function (item) {}, async: false} ]); ``` */ Pipeline(pipes : any[]) : void; /** !#en Insert a new pipe at the given index of the pipeline. </br> A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. !#zh 在给定的索引位置插入一个新的 pipe。</br> 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 @param pipe The pipe to be inserted @param index The index to insert */ insertPipe(pipe : any, index : number) : void; /** !#en Add a new pipe at the end of the pipeline. </br> A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. !#zh 添加一个新的 pipe 到 pipeline 尾部。 </br> 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 @param pipe The pipe to be appended */ appendPipe(pipe : any) : void; /** !#en Let new items flow into the pipeline. </br> Each item can be a simple url string or an object, if it's an object, it must contain `id` property. </br> You can specify its type by `type` property, by default, the type is the extension name in url. </br> By adding a `skips` property including pipe ids, you can skip these pipe. </br> The object can contain any supplementary property as you want. </br> !#zh 让新的 item 流入 pipeline 中。</br> 这里的每个 item 可以是一个简单字符串类型的 url 或者是一个对象, 如果它是一个对象的话,他必须要包含 ‘id’ 属性。</br> 你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。</br> 也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。</br> 该对象可以包含任何附加属性。 @example ```js pipeline.flowIn([ 'res/Background.png', { id: 'res/scene.json', type: 'scene', name: 'scene', skips: ['Downloader'] } ]); ``` */ flowIn(items : any[]) : void; /** !#en Let new items flow into the pipeline and give a callback when the list of items are all completed. </br> This is for loading dependencies for an existing item in flow, usually used in a pipe logic. </br> For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded </br> after all its dependencies are loaded, then you will need to use function to flow in all dependencies </br> found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback). !#zh 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。</br> 这个 API 的使用通常是为了加载依赖项。</br> 例如:</br> 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。 */ flowInDeps(urlList : any[], callback : Function) : any[]; /** !#en Copy the item states from one source item to all destination items. </br> It's quite useful when a pipe generate new items from one source item,</br> then you should flowIn these generated items into pipeline, </br> but you probably want them to skip all pipes the source item already go through,</br> you can achieve it with this API. </br> </br> For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again. !#zh 从一个源 item 向所有目标 item 复制它的 pipe 状态,用于避免重复通过部分 pipe。</br> 当一个源 item 生成了一系列新的 items 时很有用,</br> 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,</br> 但是你可能希望他们源 item 已经通过并跳过所有 pipes,</br> 这个时候就可以使用这个 API。 @param srcItem The source item @param dstItems A single destination item or an array of destination items */ copyItemStates(srcItem : any, dstItems : any[]|any) : void; /** !#en Returns whether the pipeline is flowing (contains item) currently. !#zh 获取 pipeline 当前是否正在处理中。 */ isFlowing() : boolean; /** !#en Returns all items in pipeline. !#zh 获取 pipeline 中的所有 items。 */ getItems() : LoadingItems; /** !#en Returns an item in pipeline. !#zh 根据 id 获取一个 item @param id The id of the item */ getItem(id : any) : any; /** !#en Removes an completed item in pipeline. It will only remove the cache in the pipeline or loader, its dependencies won't be released. cc.loader provided another method to completely cleanup the resource and its dependencies, please refer to {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} !#zh 移除指定的已完成 item。 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。 cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} @param id The id of the item */ removeItem(id : any) : boolean; /** !#en Clear the current pipeline, this function will clean up the items. !#zh 清空当前 pipeline,该函数将清理 items。 */ clear() : void; } /** !#en A cc.SpriteFrame has:<br/> - texture: A cc.Texture2D that will be used by the _ccsg.Sprite<br/> - rectangle: A rectangle of the texture !#zh 一个 SpriteFrame 包含:<br/> - 纹理:会被 Sprite 使用的 Texture2D 对象。<br/> - 矩形:在纹理中的矩形区域。 */ export class SpriteFrame extends Asset { /** !#en Constructor of SpriteFrame class. !#zh SpriteFrame 类的构造函数。 @param rotated Whether the frame is rotated in the texture @param offset The offset of the frame in the texture @param originalSize The size of the frame in the texture */ SpriteFrame(filename? : string|Texture2D, rect? : Rect, rotated? : boolean, offset? : Vec2, originalSize? : Size) : void; /** !#en Top border of the sprite !#zh sprite 的顶部边框 */ insetTop : number; /** !#en Bottom border of the sprite !#zh sprite 的底部边框 */ insetBottom : number; /** !#en Left border of the sprite !#zh sprite 的左边边框 */ insetLeft : number; /** !#en Right border of the sprite !#zh sprite 的左边边框 */ insetRight : number; /** !#en Returns whether the texture have been loaded !#zh 返回是否已加载纹理 */ textureLoaded() : boolean; /** Add a event listener for texture loaded event. */ addLoadedEventListener(callback : Function, target : any) : void; /** !#en Returns whether the sprite frame is rotated in the texture. !#zh 获取 SpriteFrame 是否旋转 */ isRotated() : boolean; /** !#en Set whether the sprite frame is rotated in the texture. !#zh 设置 SpriteFrame 是否旋转 */ setRotated(bRotated : boolean) : void; /** !#en Returns the rect of the sprite frame in the texture. !#zh 获取 SpriteFrame 的纹理矩形区域 */ getRect() : Rect; /** !#en Sets the rect of the sprite frame in the texture. !#zh 设置 SpriteFrame 的纹理矩形区域 */ setRect(rect : Rect) : void; /** !#en Returns the original size of the trimmed image. !#zh 获取修剪前的原始大小 */ getOriginalSize() : Size; /** !#en Sets the original size of the trimmed image. !#zh 设置修剪前的原始大小 */ setOriginalSize(size : Size) : void; /** !#en Returns the texture of the frame. !#zh 获取使用的纹理实例 */ getTexture() : Texture2D; /** !#en Returns the offset of the frame in the texture. !#zh 获取偏移量 */ getOffset() : Vec2; /** !#en Sets the offset of the frame in the texture. !#zh 设置偏移量 */ setOffset(offsets : Vec2) : void; /** !#en Clone the sprite frame. !#zh 克隆 SpriteFrame */ clone() : SpriteFrame; /** #en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.<br/> #zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame */ setTexture(textureOrTextureFile : string|Texture2D, rect? : Rect, rotated? : boolean, offset? : Vec2, originalSize? : Size) : boolean; /** !#en If a loading scene is marked as `asyncLoadAssets`, all the textures of the SpriteFrame which associated by user's custom Components in the scene, will not preload automatically. These textures will be load when Sprite component is going to render the SpriteFrames. You can call this method if you want to load the texture early. !#zh 当加载中的场景被标记为 `asyncLoadAssets` 时,用户在场景中由自定义组件关联到的所有 SpriteFrame 的贴图都不会被提前加载。 只有当 Sprite 组件要渲染这些 SpriteFrame 时,才会检查贴图是否加载。如果你希望加载过程提前,你可以手工调用这个方法。 @example ```js if (spriteFrame.textureLoaded()) { this._onSpriteFrameLoaded(); } else { spriteFrame.once('load', this._onSpriteFrameLoaded, this); spriteFrame.ensureLoadTexture(); } ``` */ ensureLoadTexture() : void; } /** <p> This class manages all events of input. include: touch, mouse, accelerometer, keyboard <br/> </p> */ export class inputManager { /** */ handleTouchesBegin(touches : any[]) : void; /** */ handleTouchesMove(touches : any[]) : void; /** */ handleTouchesEnd(touches : any[]) : void; /** */ handleTouchesCancel(touches : any[]) : void; /** */ getSetOfTouchesEndOrCancel(touches : any[]) : any[]; /** */ getHTMLElementPosition(element : HTMLElement) : any; /** */ getPreTouch(touch : Touch) : Touch; /** */ setPreTouch(touch : Touch) : void; /** */ getTouchByXY(tx : number, ty : number, pos : Vec2) : Touch; /** */ getTouchByXY(location : Vec2, pos : Vec2, eventType : number) : Event.EventMouse; /** */ getPointByEvent(event : Touch, pos : Vec2) : Vec2; /** */ getTouchesByEvent(event : Touch, pos : Vec2) : any[]; /** */ registerSystemEvent(element : HTMLElement) : void; /** */ update(dt : number) : void; } /** !#en Key map for keyboard event !#zh 键盘事件的按键值 */ export enum KEY { none = 0, back = 0, menu = 0, backspace = 0, tab = 0, enter = 0, shift = 0, ctrl = 0, alt = 0, pause = 0, capslock = 0, escape = 0, space = 0, pageup = 0, pagedown = 0, end = 0, home = 0, left = 0, up = 0, right = 0, down = 0, select = 0, insert = 0, Delete = 0, a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0, x = 0, y = 0, z = 0, num0 = 0, num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0, '*' = 0, '+' = 0, '-' = 0, numdel = 0, '/' = 0, f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0, f6 = 0, f7 = 0, f8 = 0, f9 = 0, f10 = 0, f11 = 0, f12 = 0, numlock = 0, scrolllock = 0, ';' = 0, semicolon = 0, equal = 0, '=' = 0, ',' = 0, comma = 0, dash = 0, '.' = 0, period = 0, forwardslash = 0, grave = 0, '[' = 0, openbracket = 0, backslash = 0, ']' = 0, closebracket = 0, quote = 0, dpadLeft = 0, dpadRight = 0, dpadUp = 0, dpadDown = 0, dpadCenter = 0, } /** Image formats */ export enum ImageFormat { JPG = 0, PNG = 0, TIFF = 0, WEBP = 0, PVR = 0, ETC = 0, S3TC = 0, ATITC = 0, TGA = 0, RAWDATA = 0, UNKNOWN = 0, getImageFormatByData = 0, } /** Predefined constants */ export enum Macro { INVALID_INDEX = 0, NODE_TAG_INVALID = 0, PI = 0, PI2 = 0, FLT_MAX = 0, FLT_MIN = 0, RAD = 0, DEG = 0, UINT_MAX = 0, REPEAT_FOREVER = 0, FLT_EPSILON = 0, ONE = 0, ZERO = 0, SRC_ALPHA = 0, SRC_ALPHA_SATURATE = 0, SRC_COLOR = 0, DST_ALPHA = 0, DST_COLOR = 0, ONE_MINUS_SRC_ALPHA = 0, ONE_MINUS_SRC_COLOR = 0, ONE_MINUS_DST_ALPHA = 0, ONE_MINUS_DST_COLOR = 0, ONE_MINUS_CONSTANT_ALPHA = 0, ONE_MINUS_CONSTANT_COLOR = 0, LINEAR = 0, BLEND_DST = 0, WEB_ORIENTATION_PORTRAIT = 0, WEB_ORIENTATION_LANDSCAPE_LEFT = 0, WEB_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 0, WEB_ORIENTATION_LANDSCAPE_RIGHT = 0, ORIENTATION_PORTRAIT = 0, ORIENTATION_LANDSCAPE = 0, ORIENTATION_AUTO = 0, VERTEX_ATTRIB_FLAG_NONE = 0, VERTEX_ATTRIB_FLAG_POSITION = 0, VERTEX_ATTRIB_FLAG_COLOR = 0, VERTEX_ATTRIB_FLAG_TEX_COORDS = 0, VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = 0, GL_ALL = 0, VERTEX_ATTRIB_POSITION = 0, VERTEX_ATTRIB_COLOR = 0, VERTEX_ATTRIB_TEX_COORDS = 0, VERTEX_ATTRIB_MAX = 0, UNIFORM_PMATRIX = 0, UNIFORM_MVMATRIX = 0, UNIFORM_MVPMATRIX = 0, UNIFORM_TIME = 0, UNIFORM_SINTIME = 0, UNIFORM_COSTIME = 0, UNIFORM_RANDOM01 = 0, UNIFORM_SAMPLER = 0, UNIFORM_MAX = 0, SHADER_POSITION_TEXTURECOLOR = 0, SHADER_SPRITE_POSITION_TEXTURECOLOR = 0, SHADER_POSITION_TEXTURECOLORALPHATEST = 0, SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST = 0, SHADER_POSITION_COLOR = 0, SHADER_SPRITE_POSITION_COLOR = 0, SHADER_POSITION_TEXTURE = 0, SHADER_POSITION_TEXTURE_UCOLOR = 0, SHADER_POSITION_TEXTUREA8COLOR = 0, SHADER_POSITION_UCOLOR = 0, SHADER_POSITION_LENGTHTEXTURECOLOR = 0, UNIFORM_PMATRIX_S = 0, UNIFORM_MVMATRIX_S = 0, UNIFORM_MVPMATRIX_S = 0, UNIFORM_TIME_S = 0, UNIFORM_SINTIME_S = 0, UNIFORM_COSTIME_S = 0, UNIFORM_RANDOM01_S = 0, UNIFORM_SAMPLER_S = 0, UNIFORM_ALPHA_TEST_VALUE_S = 0, ATTRIBUTE_NAME_COLOR = 0, ATTRIBUTE_NAME_POSITION = 0, ATTRIBUTE_NAME_TEX_COORD = 0, ITEM_SIZE = 0, CURRENT_ITEM = 0, ZOOM_ACTION_TAG = 0, NORMAL_TAG = 0, SELECTED_TAG = 0, DISABLE_TAG = 0, FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0, DIRECTOR_STATS_POSITION = 0, DIRECTOR_FPS_INTERVAL = 0, COCOSNODE_RENDER_SUBPIXEL = 0, SPRITEBATCHNODE_RENDER_SUBPIXEL = 0, AUTO_PREMULTIPLIED_ALPHA_FOR_PNG = 0, OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 0, TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0, TEXTURE_ATLAS_USE_VAO = 0, TEXTURE_NPOT_SUPPORT = 0, USE_LA88_LABELS = 0, SPRITE_DEBUG_DRAW = 0, LABELBMFONT_DEBUG_DRAW = 0, LABELATLAS_DEBUG_DRAW = 0, ENABLE_STACKABLE_ACTIONS = 0, ENABLE_GL_STATE_CACHE = 0, TOUCH_TIMEOUT = 0, BATCH_VERTEX_COUNT = 0, ENABLE_GC_FOR_NATIVE_OBJECTS = 0, } /** The base class of most of all the objects in Fireball. */ export class Object { /** !#en The name of the object. !#zh 该对象的名称。 */ name : string; /** !#en Indicates whether the object is not yet destroyed. !#zh 表示该对象是否可用(被销毁后将不可用)。 */ isValid : boolean; /** !#en Destroy this Object, and release all its own references to other objects.<br/> Actual object destruction will delayed until before rendering. <br/> After destroy, this CCObject is not usable any more. You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. !#zh 销毁该对象,并释放所有它对其它对象的引用。<br/> 销毁后,CCObject 不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 实际销毁操作会延迟到当前帧渲染前执行。 @example ```js obj.destroy(); ``` */ destroy() : boolean; } /** Bit mask that controls object states. */ export class Flags { /** !#en The object will not be saved. !#zh 该对象将不会被保存。 */ DontSave : number; /** !#en The object will not be saved when building a player. !#zh 构建项目时,该对象将不会被保存。 */ EditorOnly : number; } /** The fullscreen API provides an easy way for web content to be presented using the user's entire screen. It's invalid on safari, QQbrowser and android browser */ export class screen { /** initialize */ init() : void; /** return true if it's full now. */ fullScreen() : boolean; /** change the screen to full mode. */ requestFullScreen(element : Element, onFullScreenChange : Function) : void; /** exit the full mode. */ exitFullScreen() : boolean; /** Automatically request full screen with a touch/click event */ autoFullScreen(element : Element, onFullScreenChange : Function) : void; } /** System variables */ export class sys { /** English language code */ LANGUAGE_ENGLISH : string; /** Chinese language code */ LANGUAGE_CHINESE : string; /** French language code */ LANGUAGE_FRENCH : string; /** Italian language code */ LANGUAGE_ITALIAN : string; /** German language code */ LANGUAGE_GERMAN : string; /** Spanish language code */ LANGUAGE_SPANISH : string; /** Spanish language code */ LANGUAGE_DUTCH : string; /** Russian language code */ LANGUAGE_RUSSIAN : string; /** Korean language code */ LANGUAGE_KOREAN : string; /** Japanese language code */ LANGUAGE_JAPANESE : string; /** Hungarian language code */ LANGUAGE_HUNGARIAN : string; /** Portuguese language code */ LANGUAGE_PORTUGUESE : string; /** Arabic language code */ LANGUAGE_ARABIC : string; /** Norwegian language code */ LANGUAGE_NORWEGIAN : string; /** Polish language code */ LANGUAGE_POLISH : string; /** Turkish language code */ LANGUAGE_TURKISH : string; /** Ukrainian language code */ LANGUAGE_UKRAINIAN : string; /** Romanian language code */ LANGUAGE_ROMANIAN : string; /** Bulgarian language code */ LANGUAGE_BULGARIAN : string; /** Unknown language code */ LANGUAGE_UNKNOWN : string; OS_IOS : string; OS_ANDROID : string; OS_WINDOWS : string; OS_MARMALADE : string; OS_LINUX : string; OS_BADA : string; OS_BLACKBERRY : string; OS_OSX : string; OS_WP8 : string; OS_WINRT : string; OS_UNKNOWN : string; UNKNOWN : number; WIN32 : number; LINUX : number; MACOS : number; ANDROID : number; IPHONE : number; IPAD : number; BLACKBERRY : number; NACL : number; EMSCRIPTEN : number; TIZEN : number; WINRT : number; WP8 : number; MOBILE_BROWSER : number; DESKTOP_BROWSER : number; /** Indicates whether executes in editor's window process (Electron's renderer context) */ EDITOR_PAGE : number; /** Indicates whether executes in editor's main process (Electron's browser context) */ EDITOR_CORE : number; /** BROWSER_TYPE_WECHAT */ BROWSER_TYPE_WECHAT : string; BROWSER_TYPE_ANDROID : string; BROWSER_TYPE_IE : string; BROWSER_TYPE_QQ : string; BROWSER_TYPE_MOBILE_QQ : string; BROWSER_TYPE_UC : string; BROWSER_TYPE_360 : string; BROWSER_TYPE_BAIDU_APP : string; BROWSER_TYPE_BAIDU : string; BROWSER_TYPE_MAXTHON : string; BROWSER_TYPE_OPERA : string; BROWSER_TYPE_OUPENG : string; BROWSER_TYPE_MIUI : string; BROWSER_TYPE_FIREFOX : string; BROWSER_TYPE_SAFARI : string; BROWSER_TYPE_CHROME : string; BROWSER_TYPE_LIEBAO : string; BROWSER_TYPE_QZONE : string; BROWSER_TYPE_SOUGOU : string; BROWSER_TYPE_UNKNOWN : string; /** Is native ? This is set to be true in jsb auto. */ isNative : boolean; /** Is web browser ? */ isBrowser : boolean; /** Indicate whether system is mobile system */ isMobile : boolean; /** Indicate the running platform */ platform : number; /** Indicate the current language of the running system */ language : string; /** Indicate the running os name */ os : string; /** Indicate the running os version */ osVersion : string; /** Indicate the running os main version */ osMainVersion : number; /** Indicate the running browser type */ browserType : string; /** Indicate the running browser version */ browserVersion : string; /** Indicate the real pixel resolution of the whole game window */ windowPixelResolution : Size; /** cc.sys.localStorage is a local storage component. */ localStorage : any; /** The capabilities of the current platform */ capabilities : any; /** Forces the garbage collection, only available in JSB */ garbageCollect() : void; /** Dumps rooted objects, only available in JSB */ dumpRoot() : void; /** Restart the JS VM, only available in JSB */ restartVM() : void; /** Clean a script in the JS VM, only available in JSB */ cleanScript(jsfile : string) : void; /** Check whether an object is valid, In web engine, it will return true if the object exist In native engine, it will return true if the JS object and the correspond native object are both valid */ isObjectValid(obj : any) : boolean; /** Dump system informations */ dump() : void; /** Open a url in browser */ openURL(url : string) : void; /** Get the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. */ now() : number; } /** cc.view is the singleton object which represents the game window.<br/> It's main task include: <br/> - Apply the design resolution policy<br/> - Provide interaction with the window, like resize event on web, retina display support, etc...<br/> - Manage the game view port which can be different with the window<br/> - Manage the content scale and translation<br/> <br/> Since the cc.view is a singleton, you don't need to call any constructor or create functions,<br/> the standard way to use it is by calling:<br/> - cc.view.methodName(); <br/> */ export class View { /** <p> Sets view's target-densitydpi for android mobile browser. it can be set to: <br/> 1. cc.macro.DENSITYDPI_DEVICE, value is "device-dpi" <br/> 2. cc.macro.DENSITYDPI_HIGH, value is "high-dpi" (default value) <br/> 3. cc.macro.DENSITYDPI_MEDIUM, value is "medium-dpi" (browser's default value) <br/> 4. cc.macro.DENSITYDPI_LOW, value is "low-dpi" <br/> 5. Custom value, e.g: "480" <br/> </p> */ setTargetDensityDPI(densityDPI : string) : void; /** Returns the current target-densitydpi value of cc.view. */ getTargetDensityDPI() : string; /** Sets whether resize canvas automatically when browser's size changed.<br/> Useful only on web. @param enabled Whether enable automatic resize with browser's resize event */ resizeWithBrowserSize(enabled : boolean) : void; /** Sets the callback function for cc.view's resize action,<br/> this callback will be invoked before applying resolution policy, <br/> so you can do any additional modifications within the callback.<br/> Useful only on web. @param callback The callback function */ setResizeCallback(callback : Function|void) : void; /** Sets the orientation of the game, it can be landscape, portrait or auto. When set it to landscape or portrait, and screen w/h ratio doesn't fit, cc.view will automatically rotate the game canvas using CSS. Note that this function doesn't have any effect in native, in native, you need to set the application orientation in native project settings @param orientation Possible values: cc.macro.ORIENTATION_LANDSCAPE | cc.macro.ORIENTATION_PORTRAIT | cc.macro.ORIENTATION_AUTO */ setOrientation(orientation : number) : void; /** Sets whether the engine modify the "viewport" meta in your web page.<br/> It's enabled by default, we strongly suggest you not to disable it.<br/> And even when it's enabled, you can still set your own "viewport" meta, it won't be overridden<br/> Only useful on web @param enabled Enable automatic modification to "viewport" meta */ adjustViewPort(enabled : boolean) : void; /** Retina support is enabled by default for Apple device but disabled for other devices,<br/> it takes effect only when you called setDesignResolutionPolicy<br/> Only useful on web @param enabled Enable or disable retina display */ enableRetina(enabled : boolean) : void; /** Check whether retina display is enabled.<br/> Only useful on web */ isRetinaEnabled() : boolean; /** !#en Whether to Enable on anti-alias !#zh 控制抗锯齿是否开启 @param enabled Enable or not anti-alias */ enableAntiAlias(enabled : boolean) : void; /** !#en Returns whether the current enable on anti-alias !#zh 返回当前是否抗锯齿 */ isAntiAliasEnabled() : boolean; /** If enabled, the application will try automatically to enter full screen mode on mobile devices<br/> You can pass true as parameter to enable it and disable it by passing false.<br/> Only useful on web @param enabled Enable or disable auto full screen on mobile devices */ enableAutoFullScreen(enabled : boolean) : void; /** Check whether auto full screen is enabled.<br/> Only useful on web */ isAutoFullScreenEnabled() : boolean; /** Get whether render system is ready(no matter opengl or canvas),<br/> this name is for the compatibility with cocos2d-x, subclass must implement this method. */ isViewReady() : boolean; /** Sets the resolution translate on View. */ setContentTranslateLeftTop(offsetLeft : number, offsetTop : number) : void; /** Returns the resolution translate on View */ getContentTranslateLeftTop() : Size; /** Returns the frame size of the view.<br/> On native platforms, it returns the screen size since the view is a fullscreen view.<br/> On web, it returns the size of the canvas's outer DOM element. */ getFrameSize() : Size; /** On native, it sets the frame size of view.<br/> On web, it sets the size of the canvas's outer DOM element. */ setFrameSize(width : number, height : number) : void; /** Returns the visible area size of the view port. */ getVisibleSize() : Size; /** Returns the visible area size of the view port. */ getVisibleSizeInPixel() : Size; /** Returns the visible origin of the view port. */ getVisibleOrigin() : Vec2; /** Returns the visible origin of the view port. */ getVisibleOriginInPixel() : Vec2; /** Returns whether developer can set content's scale factor. */ canSetContentScaleFactor() : boolean; /** Returns the current resolution policy */ getResolutionPolicy() : ResolutionPolicy; /** Sets the current resolution policy */ setResolutionPolicy(resolutionPolicy : ResolutionPolicy|number) : void; /** Sets the resolution policy with designed view size in points.<br/> The resolution policy include: <br/> [1] ResolutionExactFit Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched.<br/> [2] ResolutionNoBorder Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut.<br/> [3] ResolutionShowAll Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.<br/> [4] ResolutionFixedHeight Scale the content's height to screen's height and proportionally scale its width<br/> [5] ResolutionFixedWidth Scale the content's width to screen's width and proportionally scale its height<br/> [cc.ResolutionPolicy] [Web only feature] Custom resolution policy, constructed by cc.ResolutionPolicy<br/> @param width Design resolution width. @param height Design resolution height. @param resolutionPolicy The resolution policy desired */ setDesignResolutionSize(width : number, height : number, resolutionPolicy : ResolutionPolicy|number) : void; /** Returns the designed size for the view. Default resolution size is the same as 'getFrameSize'. */ getDesignResolutionSize() : Size; /** Sets the container to desired pixel resolution and fit the game content to it. This function is very useful for adaptation in mobile browsers. In some HD android devices, the resolution is very high, but its browser performance may not be very good. In this case, enabling retina display is very costy and not suggested, and if retina is disabled, the image may be blurry. But this API can be helpful to set a desired pixel resolution which is in between. This API will do the following: 1. Set viewport's width to the desired width in pixel 2. Set body width to the exact pixel resolution 3. The resolution policy will be reset with designed view size in points. @param width Design resolution width. @param height Design resolution height. @param resolutionPolicy The resolution policy desired */ setRealPixelResolution(width : number, height : number, resolutionPolicy : ResolutionPolicy|number) : void; /** Sets view port rectangle with points. @param w width @param h height */ setViewPortInPoints(x : number, y : number, w : number, h : number) : void; /** Sets Scissor rectangle with points. */ setScissorInPoints(x : number, y : number, w : number, h : number) : void; /** Returns whether GL_SCISSOR_TEST is enable */ isScissorEnabled() : boolean; /** Returns the current scissor rectangle */ getScissorRect() : Rect; /** Sets the name of the view */ setViewName(viewName : string) : void; /** Returns the name of the view */ getViewName() : string; /** Returns the view port rectangle. */ getViewPortRect() : Rect; /** Returns scale factor of the horizontal direction (X axis). */ getScaleX() : number; /** Returns scale factor of the vertical direction (Y axis). */ getScaleY() : number; /** Returns device pixel ratio for retina display. */ getDevicePixelRatio() : number; /** Returns the real location in view for a translation based on a related position @param tx The X axis translation @param ty The Y axis translation @param relatedPos The related position object including "left", "top", "width", "height" informations */ convertToLocationInView(tx : number, ty : number, relatedPos : any) : Vec2; } /** <p>cc.ContainerStrategy class is the root strategy class of container's scale strategy, it controls the behavior of how to scale the cc.container and cc.game.canvas object</p> */ export class ContainerStrategy { /** Manipulation before appling the strategy @param view The target view */ preApply(view : View) : void; /** Function to apply this strategy */ apply(view : View, designedResolution : Size) : void; /** Manipulation after applying the strategy @param view The target view */ postApply(view : View) : void; } /** <p>cc.ContentStrategy class is the root strategy class of content's scale strategy, it controls the behavior of how to scale the scene and setup the viewport for the game</p> */ export class ContentStrategy { /** Manipulation before applying the strategy @param view The target view */ preApply(view : View) : void; /** Function to apply this strategy The return value is {scale: [scaleX, scaleY], viewport: {cc.Rect}}, The target view can then apply these value to itself, it's preferred not to modify directly its private variables */ apply(view : View, designedResolution : Size) : any; /** Manipulation after applying the strategy @param view The target view */ postApply(view : View) : void; } /** undefined */ export class EqualToFrame extends ContainerStrategy { } /** undefined */ export class ProportionalToFrame extends ContainerStrategy { } /** undefined */ export class EqualToWindow extends EqualToFrame { } /** undefined */ export class ProportionalToWindow extends ProportionalToFrame { } /** undefined */ export class OriginalContainer extends ContainerStrategy { } /** <p>cc.ResolutionPolicy class is the root strategy class of scale strategy, its main task is to maintain the compatibility with Cocos2d-x</p> */ export class ResolutionPolicy { /** @param containerStg The container strategy @param contentStg The content strategy */ ResolutionPolicy(containerStg : ContainerStrategy, contentStg : ContentStrategy) : void; /** Manipulation before applying the resolution policy @param view The target view */ preApply(view : View) : void; /** Function to apply this resolution policy The return value is {scale: [scaleX, scaleY], viewport: {cc.Rect}}, The target view can then apply these value to itself, it's preferred not to modify directly its private variables @param view The target view @param designedResolution The user defined design resolution */ apply(view : View, designedResolution : Size) : any; /** Manipulation after appyling the strategy @param view The target view */ postApply(view : View) : void; /** Setup the container's scale strategy */ setContainerStrategy(containerStg : ContainerStrategy) : void; /** Setup the content's scale strategy */ setContentStrategy(contentStg : ContentStrategy) : void; /** The entire application is visible in the specified area without trying to preserve the original aspect ratio.<br/> Distortion can occur, and the application may appear stretched or compressed. */ EXACT_FIT : number; /** The entire application fills the specified area, without distortion but possibly with some cropping,<br/> while maintaining the original aspect ratio of the application. */ NO_BORDER : number; /** The entire application is visible in the specified area without distortion while maintaining the original<br/> aspect ratio of the application. Borders can appear on two sides of the application. */ SHOW_ALL : number; /** The application takes the height of the design resolution size and modifies the width of the internal<br/> canvas so that it fits the aspect ratio of the device<br/> no distortion will occur however you must make sure your application works on different<br/> aspect ratios */ FIXED_HEIGHT : number; /** The application takes the width of the design resolution size and modifies the height of the internal<br/> canvas so that it fits the aspect ratio of the device<br/> no distortion will occur however you must make sure your application works on different<br/> aspect ratios */ FIXED_WIDTH : number; /** Unknow policy */ UNKNOWN : number; } /** cc.visibleRect is a singleton object which defines the actual visible rect of the current view, it should represent the same rect as cc.view.getViewportRect() */ export class visibleRect { /** initialize */ init(visibleRect : Rect) : void; /** Top left coordinate of the screen related to the game scene. */ topLeft : Vec2; /** Top right coordinate of the screen related to the game scene. */ topRight : Vec2; /** Top center coordinate of the screen related to the game scene. */ top : Vec2; /** Bottom left coordinate of the screen related to the game scene. */ bottomLeft : Vec2; /** Bottom right coordinate of the screen related to the game scene. */ bottomRight : Vec2; /** Bottom center coordinate of the screen related to the game scene. */ bottom : Vec2; /** Center coordinate of the screen related to the game scene. */ center : Vec2; /** Left center coordinate of the screen related to the game scene. */ left : Vec2; /** Right center coordinate of the screen related to the game scene. */ right : Vec2; /** Width of the screen. */ width : number; /** Height of the screen. */ height : number; } /** The CallbacksHandler is an abstract class that can register and unregister callbacks by key. Subclasses should implement their own methods about how to invoke the callbacks. */ export class _CallbacksHandler { /** @param target can be null */ add(key : string, callback : Function, target? : any) : boolean; /** Check if the specified key has any registered callback. If a callback is also specified, it will only return true if the callback is registered. */ has(key : string, callback? : Function, target? : any) : boolean; /** Removes all callbacks registered in a certain event type or all callbacks registered with a certain target @param key The event key to be removed or the target to be removed */ removeAll(key : string|any) : void; /** */ remove(key : string, callback : Function, target : any) : boolean; } /** !#en The callbacks invoker to handle and invoke callbacks by key. !#zh CallbacksInvoker 用来根据 Key 管理并调用回调方法。 */ export class CallbacksInvoker extends _CallbacksHandler { /** */ invoke(key : string, p1? : any, p2? : any, p3? : any, p4? : any, p5? : any) : void; /** */ invokeAndRemove(key : string, p1? : any, p2? : any, p3? : any, p4? : any, p5? : any) : void; /** @param remove remove callbacks after invoked */ bindKey(key : string, remove? : boolean) : Function; } /** !#en Contains information collected during deserialization !#zh 包含反序列化时的一些信息 */ export class Details { /** list of the depends assets' uuid */ uuidList : String[]; /** the obj list whose field needs to load asset by uuid */ uuidObjList : any[]; /** the corresponding field name which referenced to the asset */ uuidPropList : String[]; /** the corresponding field name which referenced to the raw object */ rawProp : string; reset() : void; /** */ getUuidOf(obj : any, propName : string) : string; /** */ push(obj : any, propName : string, uuid : string) : void; } /** undefined */ export class url { /** Returns the url of raw assets, you will only need this if the raw asset is inside the "resources" folder. @example ```js --- var url = cc.url.raw("textures/myTexture.png"); console.log(url); // "resources/raw/textures/myTexture.png" ``` */ raw(url : string) : string; /** Returns the url of builtin raw assets. This method can only used in editor. @example ```js --- var url = cc.url.builtinRaw("textures/myTexture.png"); console.log(url); // "resources/default-raw/textures/myTexture.png" ``` */ builtinRaw(url : string) : string; } /** <p> This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data. <br/> The created cc.Texture2D object will always have power-of-two dimensions. <br/> Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions <br/> i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0). <br/> Be aware that the content of the generated textures will be upside-down! </p> */ export class Texture2D extends RawAsset { /** Get width in pixels. */ getPixelWidth() : number; /** Get height of in pixels. */ getPixelHeight() : number; /** Get content size. */ getContentSize() : Size; /** Get content size in pixels. */ getContentSizeInPixels() : Size; /** Init with HTML element. @example ```js var img = new Image(); img.src = dataURL; texture.initWithElement(img); texture.handleLoadedTexture(); ``` */ initWithElement(element : HTMLImageElement|HTMLCanvasElement) : void; /** Intializes with a texture2d with data. */ initWithData(data : any[], pixelFormat : number, pixelsWide : number, pixelsHigh : number, contentSize : Size) : boolean; /** Initializes a texture from a UIImage object. Extensions to make it easy to create a CCTexture2D object from an image file. Note that RGBA type textures will have their alpha premultiplied - use the blending mode (gl.ONE, gl.ONE_MINUS_SRC_ALPHA). */ initWithImage(uiImage : HTMLImageElement) : boolean; /** HTMLElement Object getter. */ getHtmlElementObj() : HTMLImageElement; /** Check whether texture is loaded. */ isLoaded() : boolean; /** Handler of texture loaded event. */ handleLoadedTexture(premultiplied? : boolean) : void; /** Description of cc.Texture2D. */ description() : string; /** Release texture. */ releaseTexture() : void; /** Pixel format of the texture. */ getPixelFormat() : number; /** Whether or not the texture has their Alpha premultiplied, support only in WebGl rendering mode. */ hasPremultipliedAlpha() : boolean; /** Whether or not use mipmap, support only in WebGl rendering mode. */ hasMipmaps() : boolean; /** Sets the min filter, mag filter, wrap s and wrap t texture parameters. <br/> If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. @param texParams texParams object or minFilter */ setTexParameters(texParams : any|number, magFilter? : number, wrapS? : Texture2D.WrapMode, wrapT? : Texture2D.WrapMode) : void; /** sets antialias texture parameters: <br/> - GL_TEXTURE_MIN_FILTER = GL_NEAREST <br/> - GL_TEXTURE_MAG_FILTER = GL_NEAREST <br/> supported only in native or WebGl rendering mode */ setAntiAliasTexParameters() : void; /** Sets alias texture parameters: <br/> GL_TEXTURE_MIN_FILTER = GL_NEAREST <br/> GL_TEXTURE_MAG_FILTER = GL_NEAREST <br/> supported only in native or WebGl rendering mode */ setAliasTexParameters() : void; /** WebGLTexture Object. */ name : WebGLTexture; /** Pixel format of the texture. */ pixelFormat : number; /** Width in pixels. */ pixelWidth : number; /** Height in pixels. */ pixelHeight : number; /** Content width in points. */ width : number; /** Content height in points. */ height : number; } /** <p>A class that implements a Texture Atlas. <br /> Supported features: <br /> The atlas file can be a PNG, JPG. <br /> Quads can be updated in runtime <br /> Quads can be added in runtime <br /> Quads can be removed in runtime <br /> Quads can be re-ordered in runtime <br /> The TextureAtlas capacity can be increased or decreased in runtime.</p> */ export class TextureAtlas { /** <p>Creates a TextureAtlas with an filename and with an initial capacity for Quads. <br /> The TextureAtlas capacity can be increased in runtime. </p> Constructor of cc.TextureAtlas @example ```js -------------------------- 1. //creates a TextureAtlas with filename var textureAtlas = new cc.TextureAtlas("res/hello.png", 3); 2. //creates a TextureAtlas with texture var texture = cc.textureCache.addImage("hello.png"); var textureAtlas = new cc.TextureAtlas(texture, 3); ``` */ TextureAtlas(fileName : string|Texture2D, capacity : number) : void; /** Quantity of quads that are going to be drawn. */ getTotalQuads() : number; /** Quantity of quads that can be stored with the current texture atlas size. */ getCapacity() : number; /** Texture of the texture atlas. */ getTexture() : Image; /** Set texture for texture atlas. */ setTexture(texture : Image) : void; /** specify if the array buffer of the VBO needs to be updated. */ setDirty(dirty : boolean) : void; /** whether or not the array buffer of the VBO needs to be updated. */ isDirty() : boolean; /** Quads that are going to be rendered. */ getQuads() : any[]; /** */ setQuads(quads : any[]) : void; /** <p>Initializes a TextureAtlas with a filename and with a certain capacity for Quads.<br /> The TextureAtlas capacity can be increased in runtime.<br /> WARNING: Do not reinitialize the TextureAtlas because it will leak memory. </p> @example ```js -------------------------------------------------- var textureAtlas = new cc.TextureAtlas(); textureAtlas.initWithTexture("hello.png", 3); ``` */ initWithFile(file : string, capacity : number) : boolean; /** <p>Initializes a TextureAtlas with a previously initialized Texture2D object, and<br /> with an initial capacity for Quads.<br /> The TextureAtlas capacity can be increased in runtime.<br /> WARNING: Do not reinitialize the TextureAtlas because it will leak memory</p> @example ```js --------------------------- var texture = cc.textureCache.addImage("hello.png"); var textureAtlas = new cc.TextureAtlas(); textureAtlas.initWithTexture(texture, 3); ``` */ initWithTexture(texture : Image, capacity : number) : boolean; /** <p>Updates a Quad (texture, vertex and color) at a certain index <br /> index must be between 0 and the atlas capacity - 1 </p> */ updateQuad(quad : V3F_C4B_T2F_Quad, index : number) : void; /** <p>Inserts a Quad (texture, vertex and color) at a certain index<br /> index must be between 0 and the atlas capacity - 1 </p> */ insertQuad(quad : V3F_C4B_T2F_Quad, index : number) : void; /** <p> Inserts a c array of quads at a given index <br /> index must be between 0 and the atlas capacity - 1 <br /> this method doesn't enlarge the array when amount + index > totalQuads <br /> </p> */ insertQuads(quads : any[], index : number, amount : number) : void; /** <p>Removes the quad that is located at a certain index and inserts it at a new index <br /> This operation is faster than removing and inserting in a quad in 2 different steps</p> */ insertQuadFromIndex(fromIndex : number, newIndex : number) : void; /** <p>Removes a quad at a given index number.<br /> The capacity remains the same, but the total number of quads to be drawn is reduced in 1 </p> */ removeQuadAtIndex(index : number) : void; /** Removes a given number of quads at a given index. */ removeQuadsAtIndex(index : number, amount : number) : void; /** <p>Removes all Quads. <br /> The TextureAtlas capacity remains untouched. No memory is freed.<br /> The total number of quads to be drawn will be 0</p> */ removeAllQuads() : void; /** <p>Resize the capacity of the CCTextureAtlas.<br /> The new capacity can be lower or higher than the current one<br /> It returns YES if the resize was successful. <br /> If it fails to resize the capacity it will return NO with a new capacity of 0. <br /> no used for js</p> */ resizeCapacity(newCapacity : number) : boolean; /** Used internally by CCParticleBatchNode <br/> don't use this unless you know what you're doing. */ increaseTotalQuadsWith(amount : number) : void; /** Moves an amount of quads from oldIndex at newIndex. */ moveQuadsFromIndex(oldIndex : number, amount : number, newIndex : number) : void; /** Ensures that after a realloc quads are still empty <br/> Used internally by CCParticleBatchNode. */ fillWithEmptyQuadsFromIndex(index : number, amount : number) : void; /** <p>Draws n quads from an index (offset). <br /> n + start can't be greater than the capacity of the atlas</p> */ drawNumberOfQuads(n : number, start : number) : void; /** Indicates whether or not the array buffer of the VBO needs to be updated. */ dirty : boolean; /** Image texture for cc.TextureAtlas. */ texture : Image; /** Quantity of quads that can be stored with the current texture atlas size. */ capacity : number; /** Quantity of quads that are going to be drawn. */ totalQuads : number; /** Quads that are going to be rendered. */ quads : any[]; } /** cc.textureCache is a singleton object, it's the global cache for cc.Texture2D */ export class textureCache { /** Description */ description() : string; /** Returns an already created texture. Returns null if the texture doesn't exist. @example ```js ------------------ var key = cc.textureCache.textureForKey("hello.png"); ``` */ textureForKey(textureKeyName : string) : Texture2D; /** Returns an already created texture. Returns null if the texture doesn't exist. @example ```js ------------------ var key = cc.textureCache.getTextureForKey("hello.png"); ``` */ getTextureForKey(textureKeyName : string) : Texture2D; /** @example ```js --------------- var cacheTextureForColor = cc.textureCache.getTextureColors(texture); ``` */ getTextureColors(texture : Image) : any[]; /** #en get all textures #zh 获取所有贴图 */ getAllTextures() : Texture2D[]; /** <p>Purges the dictionary of loaded textures. <br /> Call this method if you receive the "Memory Warning" <br /> In the short term: it will free some resources preventing your app from being killed <br /> In the medium term: it will allocate more resources <br /> In the long term: it will be the same</p> @example ```js -------- cc.textureCache.removeAllTextures(); ``` */ removeAllTextures() : void; /** Deletes a texture from the cache given a texture. @example ```js ----- cc.textureCache.removeTexture(texture); ``` */ removeTexture(texture : Image) : void; /** Deletes a texture from the cache given a its key name. @example ```js ------ cc.textureCache.removeTexture("hello.png"); ``` */ removeTextureForKey(textureKeyName : string) : void; /** <p>Returns a Texture2D object given an file image <br /> If the file image was not previously loaded, it will create a new Texture2D <br /> object and it will return it. It will use the filename as a key.<br /> Otherwise it will return a reference of a previously loaded image. <br /> Supported image extensions: .png, .jpg, .gif</p> @example ```js ---- cc.textureCache.addImage("hello.png"); ``` */ addImage(url : string, cb : Function, target : any) : Texture2D; /** Cache the image data. */ cacheImage(path : string, texture : Image|HTMLImageElement|HTMLCanvasElement) : void; /** <p>Returns a Texture2D object given an UIImage image<br /> If the image was not previously loaded, it will create a new Texture2D object and it will return it.<br /> Otherwise it will return a reference of a previously loaded image<br /> The "key" parameter will be used as the "key" for the cache.<br /> If "key" is null, then a new texture will be created each time.</p> */ addUIImage(image : HTMLImageElement|HTMLCanvasElement, key : string) : Texture2D; } /** A base node for CCNode and CCEScene, it will: - provide the same api with origin cocos2d rendering node (SGNode) - maintains properties of the internal SGNode - retain and release the SGNode - serialize datas for SGNode (but SGNode itself will not being serialized) - notifications if some properties changed - define some interfaces shares between CCNode and CCEScene */ export class _BaseNode extends Object { /** !#en Name of node. !#zh 该节点名称。 */ name : string; /** !#en The parent of the node. !#zh 该节点的父节点。 */ parent : Node; /** !#en The uuid for editor, will be stripped before building project. !#zh 用于编辑器使用的 uuid,在构建项目之前将会被剔除。 */ uuid : string; /** !#en Skew x !#zh 该节点 Y 轴倾斜角度。 */ skewX : number; /** !#en Skew y !#zh 该节点 X 轴倾斜角度。 */ skewY : number; /** !#en Z order in depth which stands for the drawing order. !#zh 该节点渲染排序的 Z 轴深度。 */ zIndex : number; /** !#en Rotation of node. !#zh 该节点旋转角度。 */ rotation : number; /** !#en Rotation on x axis. !#zh 该节点 X 轴旋转角度。 */ rotationX : number; /** !#en Rotation on y axis. !#zh 该节点 Y 轴旋转角度。 */ rotationY : number; /** !#en Scale on x axis. !#zh 节点 X 轴缩放。 */ scaleX : number; /** !#en Scale on y axis. !#zh 节点 Y 轴缩放。 */ scaleY : number; /** !#en x axis position of node. !#zh 节点 X 轴坐标。 */ x : number; /** !#en y axis position of node. !#zh 节点 Y 轴坐标。 */ y : number; /** !#en All children nodes. !#zh 节点的所有子节点。 */ children : Node[]; /** !#en All children nodes. !#zh 节点的子节点数量。 */ childrenCount : number; /** !#en Anchor point's position on x axis. !#zh 节点 X 轴锚点位置。 */ anchorX : number; /** !#en Anchor point's position on y axis. !#zh 节点 Y 轴锚点位置。 */ anchorY : number; /** !#en Width of node. !#zh 节点宽度。 */ width : number; /** !#en Height of node. !#zh 节点高度。 */ height : number; /** !#en Tag of node. !#zh 节点标签。 */ tag : number; /** !#en Opacity of node, default value is 255. !#zh 节点透明度,默认值为 255。 */ opacity : number; /** !#en Indicate whether node's opacity value affect its child nodes, default value is true. !#zh 节点的不透明度值是否影响其子节点,默认值为 true。 */ cascadeOpacity : boolean; /** !#en Color of node, default value is white: (255, 255, 255). !#zh 节点颜色。默认为白色,数值为:(255,255,255)。 */ color : Color; /** !#en Properties configuration function </br> All properties in attrs will be set to the node, </br> when the setter of the node is available, </br> the property will be set via setter function.</br> !#zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 @param attrs Properties to be set to node @example ```js var attrs = { key: 0, num: 100 }; node.attr(attrs); ``` */ attr(attrs : any) : void; /** !#en Returns the scale factor of the node. Assertion will fail when _scaleX != _scaleY. !#zh 获取节点的缩放。当 X 轴和 Y 轴有相同的缩放数值时。 @example ```js cc.log("Node Scale: " + node.getScale()); ``` */ getScale() : number; /** !#en Sets the scale factor of the node. 1.0 is the default scale factor. This function can modify the X and Y scale at the same time. !#zh 设置节点的缩放比例,默认值为 1.0。这个函数可以在同一时间修改 X 和 Y 缩放。 @param scaleX scaleX or scale @example ```js node.setScale(cc.v2(1, 1)); node.setScale(1, 1); ``` */ setScale(scaleX : number|Vec2, scaleY? : number) : void; /** !#en Returns a copy of the position (x,y) of the node in cocos2d coordinates. (0,0) is the left-bottom corner. !#zh 获取在父节点坐标系中节点的位置( x , y )。 @example ```js cc.log("Node Position: " + node.getPosition()); ``` */ getPosition() : Vec2; /** !#en Changes the position (x,y) of the node in cocos2d coordinates.<br/> The original point (0,0) is at the left-bottom corner of screen.<br/> Usually we use cc.v2(x,y) to compose CCVec2 object.<br/> and Passing two numbers (x,y) is more efficient than passing CCPoint object. !#zh 设置节点在父坐标系中的位置。<br/> 可以通过 2 种方式设置坐标点:<br/> 1.传入 cc.v2(x, y) 类型为 cc.Vec2 的对象。<br/> 2.传入 2 个数值 x 和 y。 @param newPosOrxValue The position (x,y) of the node in coordinates or the X coordinate for position @param yValue Y coordinate for position @example ```js node.setPosition(cc.v2(0, 0)); node.setPosition(0, 0); ``` */ setPosition(newPosOrxValue : Vec2|number, yValue? : number) : void; /** !#en Returns a copy of the anchor point.<br/> Anchor point is the point around which all transformations and positioning manipulations take place.<br/> It's like a pin in the node where it is "attached" to its parent. <br/> The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. <br/> But you can use values higher than (1,1) and lower than (0,0) too. <br/> The default anchor point is (0.5,0.5), so it starts at the center of the node. !#zh 获取节点锚点,用百分比表示。<br/> 锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。<br/> 锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。<br/> 但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。<br/> 默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。<br/> 注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。 @example ```js cc.log("Node AnchorPoint: " + node.getAnchorPoint()); ``` */ getAnchorPoint() : Vec2; /** !#en Sets the anchor point in percent. <br/> anchor point is the point around which all transformations and positioning manipulations take place. <br/> It's like a pin in the node where it is "attached" to its parent. <br/> The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.<br/> But you can use values higher than (1,1) and lower than (0,0) too.<br/> The default anchor point is (0.5,0.5), so it starts at the center of the node. !#zh 设置锚点的百分比。<br/> 锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。<br/> 锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。<br/> 但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。<br/> 默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。<br/> 注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。 @param point The anchor point of node or The x axis anchor of node. @param y The y axis anchor of node. @example ```js node.setAnchorPoint(cc.v2(1, 1)); node.setAnchorPoint(1, 1); ``` */ setAnchorPoint(point : Vec2|number, y? : number) : void; /** !#en Returns a copy of the anchor point in absolute pixels. <br/> you can only read it. If you wish to modify it, use setAnchorPoint. !#zh 返回锚点的绝对像素位置。<br/> 你只能读它。如果您要修改它,使用 setAnchorPoint。 @example ```js cc.log("AnchorPointInPoints: " + node.getAnchorPointInPoints()); ``` */ getAnchorPointInPoints() : Vec2; /** !#en Returns a copy the untransformed size of the node. <br/> The contentSize remains the same no matter the node is scaled or rotated.<br/> All nodes has a size. Layer and Scene has the same size of the screen by default. <br/> !#zh 获取节点自身大小,不受该节点是否被缩放或者旋转的影响。 @param ignoreSizeProvider true if you need to get the original size of the node @example ```js cc.log("Content Size: " + node.getContentSize()); ``` */ getContentSize(ignoreSizeProvider? : boolean) : Size; /** !#en Sets the untransformed size of the node.<br/> The contentSize remains the same no matter the node is scaled or rotated.<br/> All nodes has a size. Layer and Scene has the same size of the screen. !#zh 设置节点原始大小,不受该节点是否被缩放或者旋转的影响。 @param size The untransformed size of the node or The untransformed size's width of the node. @param height The untransformed size's height of the node. @example ```js node.setContentSize(cc.size(100, 100)); node.setContentSize(100, 100); ``` */ setContentSize(size : Size|number, height? : number) : void; /** !#en Returns a "local" axis aligned bounding box of the node. <br/> The returned box is relative only to its parent. !#zh 返回父节坐标系下的轴向对齐的包围盒。 @example ```js var boundingBox = node.getBoundingBox(); ``` */ getBoundingBox() : Rect; /** !#en Stops all running actions and schedulers. !#zh 停止所有正在播放的动作和计时器。 @example ```js node.cleanup(); ``` */ cleanup() : void; /** !#en Returns a child from the container given its tag. !#zh 通过标签获取节点的子节点。 @param aTag An identifier to find the child node. @example ```js var child = node.getChildByTag(1001); ``` */ getChildByTag(aTag : number) : Node; /** !#en Returns a child from the container given its uuid. !#zh 通过 uuid 获取节点的子节点。 @param uuid The uuid to find the child node. @example ```js var child = node.getChildByUuid(uuid); ``` */ getChildByUuid(uuid : string) : Node; /** !#en Returns a child from the container given its name. !#zh 通过名称获取节点的子节点。 @param name A name to find the child node. @example ```js var child = node.getChildByName("Test Node"); ``` */ getChildByName(name : string) : Node; /** !#en "add" logic MUST only be in this method <br/> !#zh 添加子节点,并且可以修改该节点的 局部 Z 顺序和标签。 @param child A child node @param localZOrder Z order for drawing priority. Please refer to setZOrder(int) @param tag An integer or a name to identify the node easily. Please refer to setTag(int) and setName(string) @example ```js node.addChild(newNode, 1, 1001); ``` */ addChild(child : Node, localZOrder? : number, tag? : number|string) : void; /** !#en Remove itself from its parent node. If cleanup is true, then also remove all actions and callbacks. <br/> If the cleanup parameter is not passed, it will force a cleanup. <br/> If the node orphan, then nothing happens. !#zh 从父节点中删除一个节点。cleanup 参数为 true,那么在这个节点上所有的动作和回调都会被删除,反之则不会。<br/> 如果不传入 cleanup 参数,默认是 true 的。<br/> 如果这个节点是一个孤节点,那么什么都不会发生。 @param cleanup true if all actions and callbacks on this node should be removed, false otherwise. @example ```js node.removeFromParent(); node.removeFromParent(false); ``` */ removeFromParent(cleanup? : boolean) : void; /** !#en Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. </p> If the cleanup parameter is not passed, it will force a cleanup. <br/> "remove" logic MUST only be on this method <br/> If a class wants to extend the 'removeChild' behavior it only needs <br/> to override this method. !#zh 移除节点中指定的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。<br/> 如果 cleanup 参数不传入,默认为 true 表示清理。<br/> @param child The child node which will be removed. @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. @example ```js node.removeChild(newNode); node.removeChild(newNode, false); ``` */ removeChild(child : Node, cleanup? : boolean) : void; /** !#en Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter. If the cleanup parameter is not passed, it will force a cleanup. <br/> !#zh 通过标签移除节点中指定的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。<br/> 如果 cleanup 参数不传入,默认为 true 表示清理。 @param tag An integer number that identifies a child node @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. @example ```js node.removeChildByTag(1001); node.removeChildByTag(1001, false); ``` */ removeChildByTag(tag : number, cleanup? : boolean) : void; /** !#en Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. <br/> If the cleanup parameter is not passed, it will force a cleanup. !#zh 移除节点所有的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。<br/> 如果 cleanup 参数不传入,默认为 true 表示清理。 @param cleanup true if all running actions on all children nodes should be cleanup, false otherwise. @example ```js node.removeAllChildren(); node.removeAllChildren(false); ``` */ removeAllChildren(cleanup? : boolean) : void; /** !#en Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates.<br/> The matrix is in Pixels. The returned transform is readonly and cannot be changed. !#zh 返回将父节点的坐标系转换成节点(局部)的空间坐标系的矩阵。<br/> 该矩阵以像素为单位。返回的矩阵是只读的,不能更改。 @example ```js var affineTransform = node.getParentToNodeTransform(); ``` */ getParentToNodeTransform() : AffineTransform; /** !#en Returns the world affine transform matrix. The matrix is in Pixels. !#zh 返回节点到世界坐标系的仿射变换矩阵。矩阵单位是像素。 @example ```js var affineTransform = node.getNodeToWorldTransform(); ``` */ getNodeToWorldTransform() : AffineTransform; /** !#en Returns the world affine transform matrix. The matrix is in Pixels.<br/> This method is AR (Anchor Relative). !#zh 返回节点到世界坐标仿射变换矩阵。矩阵单位是像素。<br/> 该方法基于节点坐标。 @example ```js var mat = node.getNodeToWorldTransformAR(); ``` */ getNodeToWorldTransformAR() : AffineTransform; /** !#en Returns the inverse world affine transform matrix. The matrix is in Pixels. !#en 返回世界坐标系到节点坐标系的逆矩阵。 @example ```js var affineTransform = node.getWorldToNodeTransform(); ``` */ getWorldToNodeTransform() : AffineTransform; /** !#en Converts a Point to node (local) space coordinates. The result is in Vec2. !#zh 将一个点转换到节点 (局部) 坐标系。结果以 Vec2 为单位。 @example ```js var newVec2 = node.convertToNodeSpace(cc.v2(100, 100)); ``` */ convertToNodeSpace(worldPoint : Vec2) : Vec2; /** !#en Converts a Point to world space coordinates. The result is in Points. !#zh 将一个点转换到世界空间坐标系。结果以 Vec2 为单位。 @example ```js var newVec2 = node.convertToWorldSpace(cc.v2(100, 100)); ``` */ convertToWorldSpace(nodePoint : Vec2) : Vec2; /** !#en Converts a Point to node (local) space coordinates. The result is in Points.<br/> treating the returned/received node point as anchor relative. !#zh 将一个点转换到节点 (局部) 空间坐标系。结果以 Vec2 为单位。<br/> 返回值将基于节点坐标。 @example ```js var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100)); ``` */ convertToNodeSpaceAR(worldPoint : Vec2) : Vec2; /** !#en Converts a local Point to world space coordinates.The result is in Points.<br/> treating the returned/received node point as anchor relative. !#zh 将一个点转换到世界空间坐标系。结果以 Vec2 为单位。<br/> 返回值将基于世界坐标。 @example ```js var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100)); ``` */ convertToWorldSpaceAR(nodePoint : Vec2) : Vec2; /** !#en convenience methods which take a cc.Touch instead of cc.Vec2. !#zh 将触摸点转换成本地坐标系中位置。 @param touch The touch object @example ```js var newVec2 = node.convertTouchToNodeSpace(touch); ``` */ convertTouchToNodeSpace(touch : Touch) : Vec2; /** !#en converts a cc.Touch (world coordinates) into a local coordinate. This method is AR (Anchor Relative). !#zh 转换一个 cc.Touch(世界坐标)到一个局部坐标,该方法基于节点坐标。 @param touch The touch object @example ```js var newVec2 = node.convertTouchToNodeSpaceAR(touch); ``` */ convertTouchToNodeSpaceAR(touch : Touch) : Vec2; /** !#en Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.<br/> The matrix is in Pixels. !#zh 返回这个将节点(局部)的空间坐标系转换成父节点的空间坐标系的矩阵。这个矩阵以像素为单位。 @example ```js var affineTransform = node.getNodeToParentTransform(); ``` */ getNodeToParentTransform() : AffineTransform; /** !#en Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.<br/> The matrix is in Pixels.<br/> This method is AR (Anchor Relative). !#zh 返回这个将节点(局部)的空间坐标系转换成父节点的空间坐标系的矩阵。<br/> 这个矩阵以像素为单位。<br/> 该方法基于节点坐标。 @example ```js var affineTransform = node.getNodeToParentTransformAR(); ``` */ getNodeToParentTransformAR() : AffineTransform; /** !#en Returns a "world" axis aligned bounding box of the node.<br/> The bounding box contains self and active children's world bounding box. !#zh 返回节点在世界坐标系下的对齐轴向的包围盒(AABB)。<br/> 该边框包含自身和已激活的子节点的世界边框。 @example ```js var newRect = node.getBoundingBoxToWorld(); ``` */ getBoundingBoxToWorld() : Rect; /** !#en Returns the displayed opacity of Node, the difference between displayed opacity and opacity is that displayed opacity is calculated based on opacity and parent node's opacity when cascade opacity enabled. !#zh 获取节点显示透明度, 显示透明度和透明度之间的不同之处在于当启用级连透明度时, 显示透明度是基于自身透明度和父节点透明度计算的。 @example ```js var displayOpacity = node.getDisplayedOpacity(); ``` */ getDisplayedOpacity() : number; /** !#en Returns the displayed color of Node, the difference between displayed color and color is that displayed color is calculated based on color and parent node's color when cascade color enabled. !#zh 获取节点的显示透明度, 显示透明度和透明度之间的不同之处在于显示透明度是基于透明度和父节点透明度启用级连透明度时计算的。 @example ```js var displayColor = node.getDisplayedColor(); ``` */ getDisplayedColor() : Color; /** !#en Set whether color should be changed with the opacity value, useless in ccsg.Node, but this function is override in some class to have such behavior. !#zh 设置更改透明度时是否修改RGB值, @example ```js node.setOpacityModifyRGB(true); ``` */ setOpacityModifyRGB(opacityValue : boolean) : void; /** !#en Get whether color should be changed with the opacity value. !#zh 更改透明度时是否修改RGB值。 @example ```js var hasChange = node.isOpacityModifyRGB(); ``` */ isOpacityModifyRGB() : boolean; /** !#en Get the sibling index. !#zh 获取同级索引。 @example ```js var index = node.getSiblingIndex(); ``` */ getSiblingIndex() : number; /** !#en Set the sibling index of this node. !#zh 设置节点同级索引。 @example ```js node.setSiblingIndex(1); ``` */ setSiblingIndex(index : number) : void; /** !#en Is this node a child of the given node? !#zh 是否是指定节点的子节点? @example ```js node.isChildOf(newNode); ``` */ isChildOf(parent : Node) : boolean; /** !#en Sorts the children array depends on children's zIndex and arrivalOrder, normally you won't need to invoke this function. !#zh 根据子节点的 zIndex 和 arrivalOrder 进行排序,正常情况下开发者不需要手动调用这个函数。 */ sortAllChildren() : void; /** !#en The local scale relative to the parent. !#zh 节点相对父节点的缩放。 */ scale : number; /** !#en Returns the x axis position of the node in cocos2d coordinates. !#zh 获取节点 X 轴坐标。 @example ```js var posX = node.getPositionX(); ``` */ getPositionX() : number; /** !#en Sets the x axis position of the node in cocos2d coordinates. !#zh 设置节点 X 轴坐标。 @example ```js node.setPositionX(1); ``` */ setPositionX(x : number) : void; /** !#en Returns the y axis position of the node in cocos2d coordinates. !#zh 获取节点 Y 轴坐标。 @example ```js var posY = node.getPositionY(); ``` */ getPositionY() : number; /** !#en Sets the y axis position of the node in cocos2d coordinates. !#zh 设置节点 Y 轴坐标。 @param y The new position in y axis @example ```js node.setPositionY(100); ``` */ setPositionY(y : number) : void; /** !#en Returns the local Z order of this node. !#zh 获取节点局部 Z 轴顺序。 @example ```js var localZorder = node.getLocalZOrder(); ``` */ getLocalZOrder() : number; /** !#en LocalZOrder is the 'key' used to sort the node relative to its siblings. <br/> <br/> The Node's parent will sort all its children based ont the LocalZOrder value. <br/> If two nodes have the same LocalZOrder, then the node that was added first to the children's array <br/> will be in front of the other node in the array. <br/> Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order ) <br/> And Nodes that have LocalZOder values smaller than 0 are the "left" subtree <br/> While Nodes with LocalZOder greater than 0 are the "right" subtree. !#zh LocalZOrder 是 “key” (关键)来分辨节点和它兄弟节点的相关性。 父节点将会通过 LocalZOrder 的值来分辨所有的子节点。 如果两个节点有同样的 LocalZOrder,那么先加入子节点数组的节点将会显示在后加入的节点的前面。 同样的,场景图使用 “In-Order(按顺序)” 遍历数算法来遍历 ( http://en.wikipedia.org/wiki/Tree_traversal#In-order ) 并且拥有小于 0 的 LocalZOrder 的值的节点是 “ left ” 子树(左子树) 所以拥有大于 0 的 LocalZOrder 的值得节点是 “ right ”子树(右子树)。 @example ```js node.setLocalZOrder(1); ``` */ setLocalZOrder(localZOrder : number) : void; /** !#en Returns whether node's opacity value affect its child nodes. !#zh 返回节点的不透明度值是否影响其子节点。 @example ```js cc.log(node.isCascadeOpacityEnabled()); ``` */ isCascadeOpacityEnabled() : boolean; /** !#en Enable or disable cascade opacity, if cascade enabled, child nodes' opacity will be the multiplication of parent opacity and its own opacity. !#zh 启用或禁用级连不透明度,如果级连启用,子节点的不透明度将是父不透明度乘上它自己的不透明度。 @example ```js node.setCascadeOpacityEnabled(true); ``` */ setCascadeOpacityEnabled(cascadeOpacityEnabled : boolean) : void; /** !#en Enable or disable cascade color, if cascade enabled, child nodes' opacity will be the cascade value of parent color and its own color. !#zh 启用或禁用级连颜色,如果级连启用,子节点的颜色将是父颜色和它自己的颜色的级连值。 @example ```js node.setCascadeColorEnabled(true); ``` */ setCascadeColorEnabled(cascadeColorEnabled : boolean) : void; } /** !#en cc.AffineTransform class represent an affine transform matrix. It's composed basically by translation, rotation, scale transformations.<br/> Please do not use its constructor directly, use cc.affineTransformMake alias function instead. !#zh cc.AffineTransform 类代表一个仿射变换矩阵。它基本上是由平移旋转,缩放转变所组成。<br/> 请不要直接使用它的构造,请使用 cc.affineTransformMake 函数代替。 */ export class AffineTransform { /** !#en Create a cc.AffineTransform object with all contents in the matrix. !#zh 用在矩阵中的所有内容创建一个 cc.AffineTransform 对象。 */ affineTransformMake(a : number, b : number, c : number, d : number, tx : number, ty : number) : AffineTransform; /** !#en Clone a cc.AffineTransform object from the specified transform. !#zh 克隆指定的 cc.AffineTransform 对象。 */ affineTransformClone(t : AffineTransform) : AffineTransform; /** !#en Apply the affine transformation on a point. !#zh 对一个点应用矩阵变换。 @param point or x. @param transOrY transform matrix or y. @param t transform matrix or y. */ pointApplyAffineTransform(point : Vec2|number, transOrY : AffineTransform|number, t : AffineTransform) : Vec2; /** !#en Apply the affine transformation on a size. !#zh 应用 Size 到仿射变换矩阵上。 */ sizeApplyAffineTransform(size : Size, t : AffineTransform) : Size; /** !#en Create a identity transformation matrix: <br/> [ 1, 0, 0, <br/> 0, 1, 0 ] !#zh 单位矩阵:<br/> [ 1, 0, 0, <br/> 0, 1, 0 ] */ affineTransformMakeIdentity() : AffineTransform; /** !#en Apply the affine transformation on a rect. !#zh 应用 Rect 到仿射变换矩阵上。 */ rectApplyAffineTransform(rect : Rect, anAffineTransform : AffineTransform) : Rect; /** !#en Apply the affine transformation on a rect, and truns to an Oriented Bounding Box. !#zh 应用 Rect 到仿射变换矩阵上, 并转换为有向包围盒 */ obbApplyAffineTransform(rect : Rect, anAffineTransform : AffineTransform, out_bl : Vec2, out_tl : Vec2, out_tr : Vec2, out_br : Vec2) : void; /** !#en Create a new affine transformation with a base transformation matrix and a translation based on it. !#zh 基于一个基础矩阵加上一个平移操作来创建一个新的矩阵。 @param t The base affine transform object. @param tx The translation on x axis. @param ty The translation on y axis. */ affineTransformTranslate(t : AffineTransform, tx : number, ty : number) : AffineTransform; /** !#en Create a new affine transformation with a base transformation matrix and a scale based on it. !#zh 创建一个基础变换矩阵,并在此基础上进行了 Scale 仿射变换。 @param t The base affine transform object. @param sx The scale on x axis. @param sy The scale on y axis. */ affineTransformScale(t : AffineTransform, sx : number, sy : number) : AffineTransform; /** !#en Create a new affine transformation with a base transformation matrix and a rotation based on it. !#zh 创建一个基础变换矩阵,并在此基础上进行了 Rotation 仿射变换。 @param aTransform The base affine transform object. @param anAngle The angle to rotate. */ affineTransformRotate(aTransform : AffineTransform, anAngle : number) : AffineTransform; /** !#en Concatenate a transform matrix to another and return the result:<br/> t' = t1 * t2 !#zh 拼接两个矩阵,并返回结果:<br/> t' = t1 * t2 @param t1 The first transform object. @param t2 The transform object to concatenate. */ affineTransformConcat(t1 : AffineTransform, t2 : AffineTransform) : AffineTransform; /** !#en Concatenate a transform matrix to another<br/> The results are reflected in the first matrix.<br/> t' = t1 * t2 !#zh 拼接两个矩阵,将结果保存到第一个矩阵。<br/> t' = t1 * t2 @param t1 The first transform object. @param t2 The transform object to concatenate. */ affineTransformConcatIn(t1 : AffineTransform, t2 : AffineTransform) : AffineTransform; /** !#en Return true if an affine transform equals to another, false otherwise. !#zh 判断两个矩阵是否相等。 */ affineTransformEqualToTransform(t1 : AffineTransform, t2 : AffineTransform) : boolean; /** !#en Get the invert transform of an AffineTransform object. !#zh 求逆矩阵。 */ affineTransformInvert(t : AffineTransform) : AffineTransform; /** !#en Put the invert transform of an AffineTransform object into the out AffineTransform object. !#zh 求逆矩阵并存入用户传入的矩阵对象参数。 */ affineTransformInvert(t : AffineTransform, out : AffineTransform) : void; } /** !#en Representation of RGBA colors. Each color component is a floating point value with a range from 0 to 255. You can also use the convenience method {{#crossLink "cc/color:method"}}cc.color{{/crossLink}} to create a new Color. !#zh cc.Color 用于表示颜色。 它包含 RGBA 四个以浮点数保存的颜色分量,每个的值都在 0 到 255 之间。 您也可以通过使用 {{#crossLink "cc/color:method"}}cc.color{{/crossLink}} 的便捷方法来创建一个新的 Color。 */ export class Color extends ValueType { /** @param r red component of the color, default value is 0. @param g green component of the color, defualt value is 0. @param b blue component of the color, default value is 0. @param a alpha component of the color, default value is 255. */ Color(r? : number, g? : number, b? : number, a? : number) : Color; /** !#en Solid white, RGBA is [255, 255, 255, 255]. !#zh 纯白色,RGBA 是 [255, 255, 255, 255]。 */ WHITE : Color; /** !#en Solid black, RGBA is [0, 0, 0, 255]. !#zh 纯黑色,RGBA 是 [0, 0, 0, 255]。 */ BLACK : Color; /** !#en Transparent, RGBA is [0, 0, 0, 0]. !#zh 透明,RGBA 是 [0, 0, 0, 0]。 */ TRANSPARENT : Color; /** !#en Grey, RGBA is [127.5, 127.5, 127.5]. !#zh 灰色,RGBA 是 [127.5, 127.5, 127.5]。 */ GRAY : Color; /** !#en Solid red, RGBA is [255, 0, 0]. !#zh 纯红色,RGBA 是 [255, 0, 0]。 */ RED : Color; /** !#en Solid green, RGBA is [0, 255, 0]. !#zh 纯绿色,RGBA 是 [0, 255, 0]。 */ GREEN : Color; /** !#en Solid blue, RGBA is [0, 0, 255]. !#zh 纯蓝色,RGBA 是 [0, 0, 255]。 */ BLUE : Color; /** !#en Yellow, RGBA is [255, 235, 4]. !#zh 黄色,RGBA 是 [255, 235, 4]。 */ YELLOW : Color; /** !#en Orange, RGBA is [255, 127, 0]. !#zh 橙色,RGBA 是 [255, 127, 0]。 */ ORANGE : Color; /** !#en Cyan, RGBA is [0, 255, 255]. !#zh 青色,RGBA 是 [0, 255, 255]。 */ CYAN : Color; /** !#en Magenta, RGBA is [255, 0, 255]. !#zh 洋红色(品红色),RGBA 是 [255, 0, 255]。 */ MAGENTA : Color; /** !#en Clone a new color from the current color. !#zh 克隆当前颜色。 @example ```js var color = new cc.Color(); var newColor = color.clone();// Color {r: 0, g: 0, b: 0, a: 255} ``` */ clone() : Color; /** !#en TODO !#zh 判断两个颜色是否相等。 @example ```js var color1 = cc.Color.WHITE; var color2 = new cc.Color(255, 255, 255); cc.log(color1.equals(color2)); // true; color2 = cc.Color.RED; cc.log(color2.equals(color1)); // false; ``` */ equals(other: (r: number, g: number, b: number, a: number) => void) : boolean; /** !#en TODO !#zh 线性插值 @param ratio the interpolation coefficient. @param out optional, the receiving vector. @example ```js // Converts a white color to a black one trough time. update: function (dt) { var color = this.node.color; if (color.equals(cc.Color.BLACK)) { return; } this.ratio += dt * 0.1; this.node.color = cc.Color.WHITE.lerp(cc.Color.BLACK, ratio); } ``` */ lerp(to: (r: number, g: number, b: number, a: number) => void, ratio : number, out: (r: number, g: number, b: number, a: number) => void) : Color; /** !#en TODO !#zh 转换为方便阅读的字符串。 @example ```js var color = cc.Color.WHITE; color.toString(); // "rgba(255, 255, 255, 255)" ``` */ toString() : string; /** !#en Gets red channel value !#zh 获取当前颜色的红色值。 */ getR() : number; /** !#en Sets red value and return the current color object !#zh 设置当前的红色值,并返回当前对象。 @param red the new Red component. @example ```js var color = new cc.Color(); color.setR(255); // Color {r: 255, g: 0, b: 0, a: 255} ``` */ setR(red : number) : Color; /** !#en Gets green channel value !#zh 获取当前颜色的绿色值。 */ getG() : number; /** !#en Sets green value and return the current color object !#zh 设置当前的绿色值,并返回当前对象。 @param green the new Green component. @example ```js var color = new cc.Color(); color.setG(255); // Color {r: 0, g: 255, b: 0, a: 255} ``` */ setG(green : number) : Color; /** !#en Gets blue channel value !#zh 获取当前颜色的蓝色值。 */ getB() : number; /** !#en Sets blue value and return the current color object !#zh 设置当前的蓝色值,并返回当前对象。 @param blue the new Blue component. @example ```js var color = new cc.Color(); color.setB(255); // Color {r: 0, g: 0, b: 255, a: 255} ``` */ setB(blue : number) : Color; /** !#en Gets alpha channel value !#zh 获取当前颜色的透明度值。 */ getA() : number; /** !#en Sets alpha value and return the current color object !#zh 设置当前的透明度,并返回当前对象。 @param alpha the new Alpha component. @example ```js var color = new cc.Color(); color.setA(0); // Color {r: 0, g: 0, b: 0, a: 0} ``` */ setA(alpha : number) : Color; /** !#en Convert color to css format. !#zh 转换为 CSS 格式。 @param opt "rgba", "rgb", "#rgb" or "#rrggbb". @example ```js var color = cc.Color.BLACK; color.toCSS(); // "#000"; color.toCSS("rgba"); // "rgba(0,0,0,1.00)"; color.toCSS("rgb"); // "rgba(0,0,0)"; color.toCSS("#rgb"); // "#000"; color.toCSS("#rrggbb"); // "#000000"; ``` */ toCSS(opt : string) : string; /** !#en Clamp this color to make all components between 0 to 255。 !#zh 限制颜色数值,在 0 到 255 之间。 @example ```js var color = new cc.Color(1000, 0, 0, 255); color.clamp(); cc.log(color); // (255, 0, 0, 255) ``` */ clamp() : void; /** !#en Read hex string and store color data into the current color object, the hex string must be formated as rgba or rgb. !#zh 读取 16 进制颜色。 @example ```js var color = cc.Color.BLACK; color.fromHEX("#FFFF33"); // Color {r: 255, g: 255, b: 51, a: 255}; ``` */ fromHEX(hexString : string) : Color; /** !#en TODO !#zh 转换为 16 进制。 @param fmt "#rgb" or "#rrggbb". @example ```js var color = cc.Color.BLACK; color.toHEX("#rgb"); // "000"; color.toHEX("#rrggbb"); // "000000"; ``` */ toHEX(fmt : string) : string; /** !#en Convert to 24bit rgb value. !#zh 转换为 24bit 的 RGB 值。 @example ```js var color = cc.Color.YELLOW; color.toRGBValue(); // 16771844; ``` */ toRGBValue() : number; /** !#en TODO !#zh 读取 HSV(色彩模型)格式。 @example ```js var color = cc.Color.YELLOW; color.fromHSV(0, 0, 1); // Color {r: 255, g: 255, b: 255, a: 255}; ``` */ fromHSV(h : number, s : number, v : number) : Color; /** !#en TODO !#zh 转换为 HSV(色彩模型)格式。 @example ```js var color = cc.Color.YELLOW; color.toHSV(); // Object {h: 0.1533864541832669, s: 0.9843137254901961, v: 1}; ``` */ toHSV() : any; /** !#en TODO !#zh RGB 转换为 HSV。 @param r red, must be [0, 255]. @param g red, must be [0, 255]. @param b red, must be [0, 255]. @example ```js cc.Color.rgb2hsv(255, 255, 255); // Object {h: 0, s: 0, v: 1}; ``` */ rgb2hsv(r : number, g : number, b : number) : any; /** !#en TODO !#zh HSV 转换为 RGB。 @example ```js cc.Color.hsv2rgb(0, 0, 1); // Object {r: 255, g: 255, b: 255}; ``` */ hsv2rgb(h : number, s : number, v : number) : any; } /** !#en A 2D rectangle defined by x, y position and width, height. !#zh 通过位置和宽高定义的 2D 矩形。 */ export class Rect extends ValueType { /** !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 */ Rect(x? : number, y? : number, w? : number, h? : number) : Rect; /** !#en Creates a rectangle from two coordinate values. !#zh 根据指定 2 个坐标创建出一个矩形区域。 @example ```js cc.Rect.fromMinMax(cc.v2(10, 10), cc.v2(20, 20)); // Rect {x: 10, y: 10, width: 10, height: 10}; ``` */ fromMinMax(v1 : Vec2, v2 : Vec2) : Rect; /** !#en Checks if rect contains. !#zh 判断 2 个矩形是否有包含。<br/> 返回 1 为 a 包含 b,如果 -1 为 b 包含 a, 0 这则都不包含。 @param a Rect a @param b Rect b @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(5, 5, 5, 5); var c = new cc.rect(20, 20, 10, 10); cc.Rect.contain(a, b); // 1; cc.Rect.contain(b, a); // -1; cc.Rect.contain(a, c); // 0; ``` */ contain(a: (x: number, y: number, w: number, h: number) => void, b: (x: number, y: number, w: number, h: number) => void) : number; /** !#en TODO !#zh 克隆一个新的 Rect。 @example ```js var a = new cc.rect(0, 0, 10, 10); a.clone();// Rect {x: 0, y: 0, width: 10, height: 10} ``` */ clone() : Rect; /** !#en TODO !#zh 是否等于指定的矩形。 @param other !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 10, 10); a.equals(b);// true; ``` */ equals(other: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en TODO !#zh 线性插值 @param to !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param ratio the interpolation coefficient. @param out optional, the receiving vector. @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(50, 50, 100, 100); update (dt) { // method 1; var c = a.lerp(b, dt * 0.1); // method 2; a.lerp(b, dt * 0.1, c); } ``` */ lerp(to: (x: number, y: number, w: number, h: number) => void, ratio : number, out: (x: number, y: number, w: number, h: number) => void) : Rect; /** !#en TODO !#zh 转换为方便阅读的字符串 @example ```js var a = new cc.rect(0, 0, 10, 10); a.toString();// "(0.00, 0.00, 10.00, 10.00)"; ``` */ toString() : string; /** !#en TODO !#zh 矩形 x 轴上的最小值。 */ xMin : number; /** !#en TODO !#zh 矩形 y 轴上的最小值。 */ yMin : number; /** !#en TODO !#zh 矩形 x 轴上的最大值。 */ xMax : number; /** !#en TODO !#zh 矩形 y 轴上的最大值。 */ yMax : number; /** !#en TODO !#zh 矩形的中心点。 */ center : number; /** !#en TODO !#zh 矩形的大小。 */ size : Size; /** !#en TODO !#zh 当前矩形与指定矩形是否相交。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 20, 20); a.intersects(b);// true ``` */ intersects(rect: (x: number, y: number, w: number, h: number) => void) : void; /** !#en TODO !#zh 当前矩形是否包含指定坐标点。 Returns true if the point inside this rectangle. @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.v2(0, 5); a.contains(b);// true ``` */ contains(point : Vec2) : void; /** !#en Returns true if the other rect totally inside this rectangle. !#zh 当前矩形是否包含指定矩形。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 20, 20); a.containsRect(b);// true ``` */ containsRect(rect: (x: number, y: number, w: number, h: number) => void) : void; } /** !#en cc.Size is the class for size object,<br/> please do not use its constructor to create sizes,<br/> use {{#crossLink "cc/size:method"}}{{/crossLink}} alias function instead.<br/> It will be deprecated soon, please use cc.Vec2 instead. !#zh cc.Size 是 size 对象的类。<br/> 请不要使用它的构造函数创建的 size,<br/> 使用 {{#crossLink "cc/size:method"}}{{/crossLink}} 别名函数。<br/> 它不久将被取消,请使用cc.Vec2代替。 */ export class Size { /** */ Size(width : number, height : number) : Size; /** !#en return a Size object with width = 0 and height = 0. !#zh 返回一个宽度为 0 和高度为 0 的 Size 对象。 */ ZERO : Size; /** !#en TODO !#zh 克隆 size 对象。 @example ```js var a = new cc.size(10, 10); a.clone();// return Size {width: 0, height: 0}; ``` */ clone() : Size; /** !#en TODO !#zh 当前 Size 对象是否等于指定 Size 对象。 @example ```js var a = new cc.size(10, 10); a.equals(new cc.size(10, 10));// return true; ``` */ equals(other: (width: number, height: number) => void) : boolean; /** !#en TODO !#zh 线性插值。 @param to !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param ratio the interpolation coefficient. @param out optional, the receiving vector. @example ```js var a = new cc.size(10, 10); var b = new cc.rect(50, 50, 100, 100); update (dt) { // method 1; var c = a.lerp(b, dt * 0.1); // method 2; a.lerp(b, dt * 0.1, c); } ``` */ lerp(to: (x: number, y: number, w: number, h: number) => void, ratio : number, out: (width: number, height: number) => void) : Size; /** !#en TODO !#zh 转换为方便阅读的字符串。 @example ```js var a = new cc.size(10, 10); a.toString();// return "(10.00, 10.00)"; ``` */ toString() : string; /** !#en Helper function that creates a cc.Size.<br/> Please use cc.p or cc.v2 instead, it will soon replace cc.Size. !#zh 创建一个 cc.Size 对象的帮助函数。<br/> 注意:可以使用 cc.p 或者是 cc.v2 代替,它们将很快取代 cc.Size。 @param w width or a size object @param h height @example ```js var size1 = cc.size(); var size2 = cc.size(100,100); var size3 = cc.size(size2); var size4 = cc.size({width: 100, height: 100}); ``` */ size(w : number|Size, h : number) : Size; /** !#en Check whether a point's value equals to another. !#zh 检查 Size 对象是否等于另一个。 @example ```js var a = new cc.size(10, 10); var b = new cc.size(10, 10); cc.sizeEqualToSize(a, b);// return true; var b = new cc.size(5, 10); cc.sizeEqualToSize(a, b);// return false; ``` */ sizeEqualToSize(size1: (width: number, height: number) => void, size2: (width: number, height: number) => void) : boolean; } /** !#en the device accelerometer reports values for each axis in units of g-force. !#zh 设备重力传感器传递的各个轴的数据。 */ export class Acceleration { /** */ Acceleration(x : number, y : number, z : number, timestamp : number) : Acceleration; } /** !#en Blend Function used for textures. !#zh 图像的混合方式。 */ export class BlendFunc { constructor(); /** @param src1 source blend function @param dst1 destination blend function */ BlendFunc(src1 : number, dst1 : number) : BlendFunc; } /** !#en Enum for blend factor Refer to: http://www.andersriggelsen.dk/glblendfunc.php !#zh 混合因子 可参考: http://www.andersriggelsen.dk/glblendfunc.php */ export enum BlendFactor { ONE = 0, ZERO = 0, SRC_ALPHA = 0, SRC_COLOR = 0, DST_ALPHA = 0, DST_COLOR = 0, ONE_MINUS_SRC_ALPHA = 0, ONE_MINUS_SRC_COLOR = 0, ONE_MINUS_DST_ALPHA = 0, ONE_MINUS_DST_COLOR = 0, blendFuncDisable = 0, } /** undefined */ export enum TextAlignment { LEFT = 0, CENTER = 0, RIGHT = 0, } /** undefined */ export class WebGLColor { /** */ WebGLColor(r : number, g : number, b : number, a : number, arrayBuffer : any[], offset : number) : WebGLColor; BYTES_PER_ELEMENT : number; } /** undefined */ export class Vertex2F { /** */ Vertex2F(x : number, y : number, arrayBuffer : any[], offset : number) : Vertex2F; BYTES_PER_ELEMENT : number; } /** undefined */ export class Vertex3F { /** */ Vertex3F(x : number, y : number, z : number, arrayBuffer : any[], offset : number) : Vertex3F; BYTES_PER_ELEMENT : number; } /** undefined */ export class Tex2F { /** */ Tex2F(u : number, v : number, arrayBuffer : any[], offset : number) : Tex2F; BYTES_PER_ELEMENT : number; } /** undefined */ export class Quad2 { /** */ Quad2(tl: (x: number, y: number, arrayBuffer: any[], offset: number) => void, tr: (x: number, y: number, arrayBuffer: any[], offset: number) => void, bl: (x: number, y: number, arrayBuffer: any[], offset: number) => void, br: (x: number, y: number, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : Quad2; BYTES_PER_ELEMENT : number; } /** A 3D Quad. 4 * 3 floats */ export class Quad3 { /** */ Quad3(bl1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, br1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, tl1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, tr1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : Quad3; } /** undefined */ export class V3F_C4B_T2F { /** */ V3F_C4B_T2F(vertices: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, colors: (r: number, g: number, b: number, a: number) => void, texCoords: (u: number, v: number, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V3F_C4B_T2F; BYTES_PER_ELEMENT() : void; } /** undefined */ export class V3F_C4B_T2F_Quad { /** */ V3F_C4B_T2F_Quad(tl: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, bl: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, tr: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, br: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V3F_C4B_T2F_Quad; BYTES_PER_ELEMENT : number; } /** undefined */ export class V2F_C4B_T2F { /** */ V2F_C4B_T2F(vertices: (x: number, y: number, arrayBuffer: any[], offset: number) => void, colors: (r: number, g: number, b: number, a: number) => void, texCoords: (u: number, v: number, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V2F_C4B_T2F; BYTES_PER_ELEMENT : number; } /** undefined */ export class V2F_C4B_T2F_Triangle { /** */ V2F_C4B_T2F_Triangle(a: (vertices: Vertex2F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, b: (vertices: Vertex2F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, c: (vertices: Vertex2F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V2F_C4B_T2F_Triangle; } /** !#en The base class of all value types. !#zh 所有值类型的基类。 */ export class ValueType { /** !#en This method returns an exact copy of current value. !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。 */ clone() : ValueType; /** !#en Compares this object with the other one. !#zh 当前对象是否等于指定对象。 */ equals(other : ValueType) : boolean; /** !#en TODO !#zh 转换为方便阅读的字符串。 */ toString() : string; /** !#en Linearly interpolates between this value to to value by ratio which is in the range [0, 1]. When ratio = 0 returns this. When ratio = 1 return to. When ratio = 0.5 returns the average of this and to. !#zh 线性插值。<br/> 当 ratio = 0 时返回自身,ratio = 1 时返回目标,ratio = 0.5 返回自身和目标的平均值。。 @param to the to value @param ratio the interpolation coefficient */ lerp(to : ValueType, ratio : number) : ValueType; } /** !#en Representation of 2D vectors and points. !#zh 表示 2D 向量和坐标 */ export class Vec2 extends ValueType { /** !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ Vec2(x? : number, y? : number) : Vec2; /** !#en clone a Vec2 value !#zh 克隆一个 Vec2 值 */ clone() : Vec2; /** !#en TODO !#zh 设置向量值。 @param newValue !#en new value to set. !#zh 要设置的新值 */ set(newValue: (x: number, y: number) => void) : Vec2; /** !#en TODO !#zh 当前的向量是否与指定的向量相等。 @param other !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ equals(other: (x: number, y: number) => void) : boolean; /** !#en TODO !#zh 转换为方便阅读的字符串。 */ toString() : string; /** !#en TODO !#zh 线性插值。 @param to !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param ratio the interpolation coefficient @param out optional, the receiving vector */ lerp(to: (x: number, y: number) => void, ratio : number, out: (x: number, y: number) => void) : Vec2; /** !#en Adds this vector. If you want to save result to another vector, use add() instead. !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.addSelf(cc.v2(5, 5));// return Vec2 {x: 15, y: 15}; ``` */ addSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Adds two vectors, and returns the new result. !#zh 向量加法,并返回新结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.add(cc.v2(5, 5)); // return Vec2 {x: 15, y: 15}; var v1; v.add(cc.v2(5, 5), v1); // return Vec2 {x: 15, y: 15}; ``` */ add(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5}; ``` */ subSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Subtracts one vector from this, and returns the new result. !#zh 向量减法,并返回新结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5}; var v1; v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5}; ``` */ sub(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 @example ```js var v = cc.v2(10, 10); v.mulSelf(5);// return Vec2 {x: 50, y: 50}; ``` */ mulSelf(num : number) : Vec2; /** !#en Multiplies by a number, and returns the new result. !#zh 缩放当前向量,并返回新结果。 @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.mul(5); // return Vec2 {x: 50, y: 50}; var v1; v.mul(5, v1); // return Vec2 {x: 50, y: 50}; ``` */ mul(num : number, out: (x: number, y: number) => void) : Vec2; /** !#en Multiplies two vectors. !#zh 分量相乘。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50}; ``` */ scaleSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Multiplies two vectors, and returns the new result. !#zh 分量相乘,并返回新的结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50}; var v1; v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50}; ``` */ scale(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Divides by a number. If you want to save result to another vector, use div() instead. !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.divSelf(5); // return Vec2 {x: 2, y: 2}; ``` */ divSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Divides by a number, and returns the new result. !#zh 向量除法,并返回新的结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.div(5); // return Vec2 {x: 2, y: 2}; var v1; v.div(5, v1); // return Vec2 {x: 2, y: 2}; ``` */ div(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Negates the components. If you want to save result to another vector, use neg() instead. !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 @example ```js var v = cc.v2(10, 10); v.negSelf(); // return Vec2 {x: -10, y: -10}; ``` */ negSelf() : Vec2; /** !#en Negates the components, and returns the new result. !#zh 返回取反后的新向量。 @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); var v1; v.neg(v1); // return Vec2 {x: -10, y: -10}; ``` */ neg(out: (x: number, y: number) => void) : Vec2; /** !#en Dot product !#zh 当前向量与指定向量进行点乘。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.dot(cc.v2(5, 5)); // return 100; ``` */ dot(vector: (x: number, y: number) => void) : number; /** !#en Cross product !#zh 当前向量与指定向量进行叉乘。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.cross(cc.v2(5, 5)); // return 0; ``` */ cross(vector: (x: number, y: number) => void) : number; /** !#en Returns the length of this vector. !#zh 返回该向量的长度。 @example ```js var v = cc.v2(10, 10); v.mag(); // return 14.142135623730951; ``` */ mag() : number; /** !#en Returns the squared length of this vector. !#zh 返回该向量的长度平方。 @example ```js var v = cc.v2(10, 10); v.magSqr(); // return 200; ``` */ magSqr() : number; /** !#en Make the length of this vector to 1. !#zh 向量归一化,让这个向量的长度为 1。 @example ```js var v = cc.v2(10, 10); v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; ``` */ normalizeSelf() : Vec2; /** !#en Returns this vector with a magnitude of 1.<br/> <br/> Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. !#zh 返回归一化后的向量。<br/> <br/> 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 @param out optional, the receiving vector */ normalize(out: (x: number, y: number) => void) : Vec2; /** !#en Get angle in radian between this and vector. !#zh 夹角的弧度。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ angle(vector: (x: number, y: number) => void) : number; /** !#en Get angle in radian between this and vector with direction. !#zh 带方向的夹角的弧度。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ signAngle(vector: (x: number, y: number) => void) : number; /** !#en rotate !#zh 返回旋转给定弧度后的新向量。 @param out optional, the receiving vector */ rotate(radians : number, out: (x: number, y: number) => void) : Vec2; /** !#en rotate self !#zh 按指定弧度旋转向量。 */ rotateSelf(radians : number) : Vec2; /** !#en return a Vec2 object with x = 1 and y = 1. !#zh 新 Vec2 对象。 */ ONE : Vec2; /** !#en return a Vec2 object with x = 0 and y = 0. !#zh 返回 x = 0 和 y = 0 的 Vec2 对象。 */ ZERO : Vec2; /** !#en return a Vec2 object with x = 0 and y = 1. !#zh 返回 x = 0 和 y = 1 的 Vec2 对象。 */ UP : Vec2; /** !#en return a Vec2 object with x = 1 and y = 0. !#zh 返回 x = 1 和 y = 0 的 Vec2 对象。 */ RIGHT : Vec2; } /** !#en Base class for handling assets used in Fireball. This class can be instantiate. You may want to override:<br/> - createNode<br/> - cc.Object._serialize<br/> - cc.Object._deserialize<br/> !#zh 资源基类,该类可以被实例化。<br/> 您可能需要重写:<br/> - createNode <br/> - cc.Object._serialize<br/> - cc.Object._deserialize<br/> */ export class Asset extends RawAsset { /** !#en Returns the url of this asset's first raw file, if none of rawFile exists, it will returns an empty string. !#zh 返回该资源的原始文件的 URL,如果不支持 RAW 文件,它将返回一个空字符串。 */ rawUrl : string; /** !#en Returns the url of this asset's raw files, if none of rawFile exists, it will returns an empty array. !#zh 返回该资源的原文件的 URL 数组,如果不支持 RAW 文件,它将返回一个空数组。 */ rawUrls : String[]; /** !#en Indicates whether its dependent raw assets can support deferred load if the owner scene is marked as `asyncLoadAssets`. !#zh 当场景被标记为 `asyncLoadAssets`,禁止延迟加载该资源所依赖的其它 RawAsset。 */ preventDeferredLoadDependents : boolean; /** !#en Create a new node using this asset in the scene.<br/> If this type of asset dont have its corresponding node type, this method should be null. !#zh 使用该资源在场景中创建一个新节点。<br/> 如果这类资源没有相应的节点类型,该方法应该是空的。 */ createNode(callback: (error: string, node: any) => void) : void; } /** !#en Class for audio data handling. !#zh 音频资源类。 */ export class AudioClip extends RawAsset { } /** !#en Class for BitmapFont handling. !#zh 位图字体资源类。 */ export class BitmapFont extends RawAsset { } /** !#en Class for Font handling. !#zh 字体资源类。 */ export class Font extends RawAsset { } /** !#en Class for LabelAtlas handling. !#zh 艺术数字字体资源类。 */ export class LabelAtlas extends cc.BitmapFont { } /** !#en Class for prefab handling. !#zh 预制资源类。 */ export class Prefab extends Asset { /** the main cc.Node in the prefab */ data : Node; /** Dynamically translation prefab data into minimized code.<br/> This method will be called automatically before the first time the prefab being instantiated, but you can re-call to refresh the create function once you modified the original prefab data in script. */ compileCreateFunction() : void; } /** !#en The base class for registering asset types. You may want to override: - createNode (static) !#zh 注册用的资源基类。<br/> 你可能要重写:<br/> - createNode (static) */ export class RawAsset extends CCObject { /** !#en Create a new node in the scene.<br/> If this type of asset dont have its corresponding node type, this method should be null. !#zh 在场景中创建一个新节点。<br/> 如果这类资源没有相应的节点类型,该方法应该是空的。 */ createNodeByInfo(Info : any, callback: (error: string, node: any) => void) : void; } /** !#en Class for scene handling. !#zh 场景资源类。 */ export class SceneAsset extends Asset { scene : Scene; /** !#en Indicates the raw assets of this scene can be load after scene launched. !#zh 指示该场景依赖的资源可否在场景切换后再延迟加载。 */ asyncLoadAssets : boolean; } /** !#en Class for script handling. !#zh Script 资源类。 */ export class _Script extends Asset { } /** !#en Class for JavaScript handling. !#zh JavaScript 资源类。 */ export class _JavaScript extends Asset { } /** !#en Class for coffee script handling. !#zh CoffeeScript 资源类。 */ export class CoffeeScript extends Asset { } /** !#en Class for sprite atlas handling. !#zh 精灵图集资源类。 */ export class SpriteAtlas extends RawAsset { /** Returns the texture of the sprite atlas */ getTexture() : Texture2D; /** Returns the sprite frame correspond to the given key in sprite atlas. */ getSpriteFrame(key : string) : SpriteFrame; /** Returns the sprite frames in sprite atlas. */ getSpriteFrames() : [SpriteFrame]; } /** !#en Class for TTFFont handling. !#zh TTF 字体资源类。 */ export class TTFFont extends Asset { } /** !#en Class for text file. !#zh 文本资源类。 */ export class TextAsset extends Asset { } /**************************************************** * audioEngine *****************************************************/ export module audioEngine { /** !#en Audio state. !#zh 声音播放状态 */ export enum AudioState { ERROR = 0, INITIALZING = 0, PLAYING = 0, PAUSED = 0, } } /**************************************************** * ParticleSystem *****************************************************/ export module ParticleSystem { /** !#en Enum for emitter modes !#zh 发射模式 */ export enum EmitterMode { GRAVITY = 0, RADIUS = 0, } } /**************************************************** * ParticleSystem *****************************************************/ export module ParticleSystem { /** !#en Enum for particles movement type. !#zh 粒子位置类型 */ export enum PositionType { FREE = 0, RELATIVE = 0, GROUPED = 0, } } /**************************************************** * Node *****************************************************/ export module Node { /** !#en The event type supported by Node !#zh Node 支持的事件类型 */ export enum EventType { TOUCH_START = 0, TOUCH_MOVE = 0, TOUCH_END = 0, TOUCH_CANCEL = 0, MOUSE_DOWN = 0, MOUSE_MOVE = 0, MOUSE_ENTER = 0, MOUSE_LEAVE = 0, MOUSE_UP = 0, MOUSE_WHEEL = 0, } } /**************************************************** * TiledMap *****************************************************/ export module TiledMap { /** !#en The orientation of tiled map. !#zh Tiled Map 地图方向。 */ export enum Orientation { ORTHO = 0, HEX = 0, ISO = 0, NONE = 0, MAP = 0, LAYER = 0, OBJECTGROUP = 0, OBJECT = 0, TILE = 0, HORIZONTAL = 0, VERTICAL = 0, DIAGONAL = 0, FLIPPED_ALL = 0, FLIPPED_MASK = 0, STAGGERAXIS_X = 0, STAGGERAXIS_Y = 0, STAGGERINDEX_ODD = 0, STAGGERINDEX_EVEN = 0, } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The Custom event !#zh 自定义事件 */ export class EventCustom extends Event { /** @param type The name of the event (case-sensitive), e.g. "click", "fire", or "submit" @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ EventCustom(type : string, bubbles : boolean) : EventCustom; /** !#en A reference to the detailed data of the event !#zh 事件的详细数据 */ detail : any; /** !#en Sets user data !#zh 设置用户数据 */ setUserData(data : any) : void; /** !#en Gets user data !#zh 获取用户数据 */ getUserData() : any; /** !#en Gets event name !#zh 获取事件名称 */ getEventName() : string; } } /**************************************************** * Button *****************************************************/ export module Button { /** !#en Enum for transition type. !#zh 过渡类型 */ export enum Transition { NONE = 0, COLOR = 0, SPRITE = 0, SCALE = 0, } } /**************************************************** * Component *****************************************************/ export module Component { /** !#en Component will register a event to target component's handler. And it will trigger the handler when a certain event occurs. !@zh “EventHandler” 类用来设置场景中的事件回调, 该类允许用户设置回调目标节点,目标组件名,组件方法名, 并可通过 emit 方法调用目标函数。 */ export class EventHandler { /** !#en Event target !#zh 目标节点 */ target : Node; /** !#en Component name !#zh 目标组件名 */ component : string; /** !#en Event handler !#zh 响应事件函数名 */ handler : string; /** !#en Custom Event Data !#zh 自定义事件数据 */ customEventData : string; /** */ emitEvents(events : Component.EventHandler[], params : any) : void; /** !#en Emit event with params !#zh 触发目标组件上的指定 handler 函数,该参数是回调函数的参数值(可不填)。 @example ```js // Call Function var eventHandler = new cc.Component.EventHandler(); eventHandler.target = newTarget; eventHandler.component = "MainMenu"; eventHandler.handler = "OnClick" eventHandler.emit(["param1", "param2", ....]); ``` */ emit(params : any[]) : void; } } /**************************************************** * EditBox *****************************************************/ export module EditBox { /** !#en Enum for keyboard return types !#zh 键盘的返回键类型 */ export enum KeyboardReturnType { DEFAULT = 0, DONE = 0, SEND = 0, SEARCH = 0, GO = 0, } } /**************************************************** * EditBox *****************************************************/ export module EditBox { /** !#en The EditBox's InputMode defines the type of text that the user is allowed to enter. !#zh 输入模式 */ export enum InputMode { ANY = 0, EMAIL_ADDR = 0, NUMERIC = 0, PHONE_NUMBER = 0, URL = 0, DECIMAL = 0, SINGLE_LINE = 0, } } /**************************************************** * EditBox *****************************************************/ export module EditBox { /** !#en Enum for the EditBox's input flags !#zh 定义了一些用于设置文本显示和文本格式化的标志位。 */ export enum InputFlag { PASSWORD = 0, SENSITIVE = 0, INITIAL_CAPS_WORD = 0, INITIAL_CAPS_SENTENCE = 0, INITIAL_CAPS_ALL_CHARACTERS = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for text alignment. !#zh 文本横向对齐类型 */ export enum HorizontalAlign { LEFT = 0, CENTER = 0, RIGHT = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for vertical text alignment. !#zh 文本垂直对齐类型 */ export enum VerticalAlign { TOP = 0, CENTER = 0, BOTTOM = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for Overflow. !#zh Overflow 类型 */ export enum Overflow { NONE = 0, CLAMP = 0, SHRINK = 0, RESIZE_HEIGHT = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for font type. !#zh Type 类型 */ export enum Type { TTF = 0, BMFont = 0, SystemFont = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for Layout type !#zh 布局类型 */ export enum Type { NONE = 0, HORIZONTAL = 0, VERTICAL = 0, GRID = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for Layout Resize Mode !#zh 缩放模式 */ export enum ResizeMode { NONE = 0, CONTAINER = 0, CHILDREN = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for Grid Layout start axis direction. The items in grid layout will be arranged in each axis at first.; !#zh 布局轴向,只用于 GRID 布局。 */ export enum AxisDirection { HORIZONTAL = 0, VERTICAL = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for vertical layout direction. Used in Grid Layout together with AxisDirection is VERTICAL !#zh 垂直方向布局方式 */ export enum VerticalDirection { BOTTOM_TO_TOP = 0, TOP_TO_BOTTOM = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for horizontal layout direction. Used in Grid Layout together with AxisDirection is HORIZONTAL !#zh 水平方向布局方式 */ export enum HorizontalDirection { LEFT_TO_RIGHT = 0, RIGHT_TO_LEFT = 0, } } /**************************************************** * Mask *****************************************************/ export module Mask { /** !#en the type for mask. !#zh 遮罩组件类型 */ export enum Type { RECT = 0, ELLIPSE = 0, IMAGE_STENCIL = 0, } } /**************************************************** * PageView *****************************************************/ export module PageView { /** !#en The Page View Size Mode !#zh 页面视图每个页面统一的大小类型 */ export enum SizeMode { Unified = 0, Free = 0, } } /**************************************************** * PageView *****************************************************/ export module PageView { /** !#en The Page View Direction !#zh 页面视图滚动类型 */ export enum Direction { Horizontal = 0, Vertical = 0, } } /**************************************************** * PageView *****************************************************/ export module PageView { /** !#en Enum for ScrollView event type. !#zh 滚动视图事件类型 */ export enum EventType { PAGE_TURNING = 0, } } /**************************************************** * PageViewIndicator *****************************************************/ export module PageViewIndicator { /** !#en Enum for PageView Indicator direction !#zh 页面视图指示器的摆放方向 */ export enum Direction { HORIZONTAL = 0, VERTICAL = 0, } } /**************************************************** * ProgressBar *****************************************************/ export module ProgressBar { /** !#en Enum for ProgressBar mode !#zh 进度条模式 */ export enum Mode { HORIZONTAL = 0, VERTICAL = 0, FILLED = 0, } } /**************************************************** * Scrollbar *****************************************************/ export module Scrollbar { /** Enum for Scrollbar direction */ export enum Direction { HORIZONTAL = 0, VERTICAL = 0, } } /**************************************************** * ScrollView *****************************************************/ export module ScrollView { /** !#en Enum for ScrollView event type. !#zh 滚动视图事件类型 */ export enum EventType { SCROLL_TO_TOP = 0, SCROLL_TO_BOTTOM = 0, SCROLL_TO_LEFT = 0, SCROLL_TO_RIGHT = 0, SCROLLING = 0, BOUNCE_TOP = 0, BOUNCE_BOTTOM = 0, BOUNCE_LEFT = 0, BOUNCE_RIGHT = 0, AUTOSCROLL_ENDED = 0, TOUCH_UP = 0, } } /**************************************************** * Slider *****************************************************/ export module Slider { /** !#en The Slider Direction !#zh 滑动器方向 */ export enum Direction { Horizontal = 0, Vertical = 0, } } /**************************************************** * Sprite *****************************************************/ export module Sprite { /** !#en Enum for sprite type. !#zh Sprite 类型 */ export enum SpriteType { SIMPLE = 0, SLICED = 0, TILED = 0, FILLED = 0, } } /**************************************************** * Sprite *****************************************************/ export module Sprite { /** !#en Enum for fill type. !#zh 填充类型 */ export enum FillType { HORIZONTAL = 0, VERTICAL = 0, RADIAL = 0, } } /**************************************************** * Sprite *****************************************************/ export module Sprite { /** !#en Sprite Size can track trimmed size, raw size or none. !#zh 精灵尺寸调整模式 */ export enum SizeMode { CUSTOM = 0, TRIMMED = 0, RAW = 0, } } /**************************************************** * VideoPlayer *****************************************************/ export module VideoPlayer { /** !#en Video event type !#zh 视频事件类型 */ export enum EventType { PLAYING = 0, PAUSED = 0, STOPPED = 0, COMPLETED = 0, } } /**************************************************** * VideoPlayer *****************************************************/ export module VideoPlayer { /** !#en Enum for video resouce type type. !#zh 视频来源 */ export enum ResourceType { REMOTE = 0, LOCAL = 0, } } /**************************************************** * WebView *****************************************************/ export module WebView { /** !#en WebView event type !#zh 网页视图事件类型 */ export enum EventType { LOADED = 0, LOADING = 0, ERROR = 0, } } /**************************************************** * Graphics *****************************************************/ export module Graphics { /** !#en Enum for LineCap. !#zh 线段末端属性 */ export enum LineCap { BUTT = 0, ROUND = 0, SQUARE = 0, } } /**************************************************** * Graphics *****************************************************/ export module Graphics { /** !#en Enum for LineJoin. !#zh 线段拐角属性 */ export enum LineJoin { BEVEL = 0, ROUND = 0, MITER = 0, } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The mouse event !#zh 鼠标事件类型 */ export class EventMouse extends Event { /** !#en Sets scroll data. !#zh 设置鼠标的滚动数据。 */ setScrollData(scrollX : number, scrollY : number) : void; /** !#en Returns the x axis scroll value. !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 */ getScrollX() : number; /** !#en Returns the y axis scroll value. !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 */ getScrollY() : number; /** !#en Sets cursor location. !#zh 设置当前鼠标位置。 */ setLocation(x : number, y : number) : void; /** !#en Returns cursor location. !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 */ getLocation() : Vec2; /** !#en Returns the current cursor location in screen coordinates. !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 */ getLocationInView() : Vec2; /** !#en Returns the previous touch location. !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocation() : Vec2; /** !#en Returns the delta distance from the previous location to current location. !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 */ getDelta() : Vec2; /** !#en Returns the X axis delta distance from the previous location to current location. !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 */ getDeltaX() : number; /** !#en Returns the Y axis delta distance from the previous location to current location. !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 */ getDeltaY() : number; /** !#en Sets mouse button. !#zh 设置鼠标按键。 */ setButton(button : number) : void; /** !#en Returns mouse button. !#zh 获取鼠标按键。 */ getButton() : number; /** !#en Returns location X axis data. !#zh 获取鼠标当前位置 X 轴。 */ getLocationX() : number; /** !#en Returns location Y axis data. !#zh 获取鼠标当前位置 Y 轴。 */ getLocationY() : number; } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The touch event !#zh 触摸事件 */ export class EventTouch extends Event { /** !#en Returns event code. !#zh 获取事件类型。 */ getEventCode() : number; /** !#en Returns touches of event. !#zh 获取触摸点的列表。 */ getTouches() : any[]; /** !#en Sets touch location. !#zh 设置当前触点位置 */ setLocation(x : number, y : number) : void; /** !#en Returns touch location. !#zh 获取触点位置。 */ getLocation() : Vec2; /** !#en Returns the current touch location in screen coordinates. !#zh 获取当前触点在游戏窗口中的位置。 */ getLocationInView() : Vec2; /** !#en Returns the previous touch location. !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocation() : Vec2; /** !#en Returns the start touch location. !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 */ getStartLocation() : Vec2; /** !#en Returns the id of cc.Touch. !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 */ getID() : number; /** !#en Returns the delta distance from the previous location to current location. !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 */ getDelta() : Vec2; /** !#en Returns the X axis delta distance from the previous location to current location. !#zh 获取触点距离上一次事件移动的 x 轴距离。 */ getDeltaX() : number; /** !#en Returns the Y axis delta distance from the previous location to current location. !#zh 获取触点距离上一次事件移动的 y 轴距离。 */ getDeltaY() : number; /** !#en Returns location X axis data. !#zh 获取当前触点 X 轴位置。 */ getLocationX() : number; /** !#en Returns location Y axis data. !#zh 获取当前触点 Y 轴位置。 */ getLocationY() : number; } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The acceleration event !#zh 加速度事件 */ export class EventAcceleration extends Event { } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The keyboard event !#zh 键盘事件 */ export class EventKeyboard extends Event { } } /**************************************************** * SystemEvent *****************************************************/ export module SystemEvent { /** !#en The event type supported by SystemEvent !#zh SystemEvent 支持的事件类型 */ export enum EventType { KEY_DOWN = 0, KEY_UP = 0, DEVICEMOTION = 0, } } /**************************************************** * Pipeline *****************************************************/ export module Pipeline { /** The downloader pipe, it can download several types of files: 1. Text 2. Image 3. Script 4. Audio All unknown type will be downloaded as plain text. You can pass custom supported types in the constructor. */ export class Downloader { /** Constructor of Downloader, you can pass custom supported types. @param extMap Custom supported types with corresponded handler @example ```js var downloader = new Downloader({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ Downloader(extMap : any) : void; /** Add custom supported types handler or modify existing type handler. @param extMap Custom supported types with corresponded handler */ addHandlers(extMap : any) : void; } } /**************************************************** * Pipeline *****************************************************/ export module Pipeline { /** The loader pipe, it can load several types of files: 1. Images 2. JSON 3. Plist 4. Audio 5. Font 6. Cocos Creator scene It will not interfere with items of unknown type. You can pass custom supported types in the constructor. */ export class Loader { /** Constructor of Loader, you can pass custom supported types. @param extMap Custom supported types with corresponded handler @example ```js var loader = new Loader({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ Loader(extMap : any) : void; /** Add custom supported types handler or modify existing type handler. @param extMap Custom supported types with corresponded handler */ addHandlers(extMap : any) : void; } } /**************************************************** * LoadingItems *****************************************************/ export module LoadingItems { /** !#en The item states of the LoadingItems, its value could be LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR !#zh LoadingItems 队列中的加载项状态,状态的值可能是 LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR */ export enum ItemState { WORKING = 0, COMPLETET = 0, ERROR = 0, } } /**************************************************** * Texture2D *****************************************************/ export module Texture2D { /** The texture wrap mode */ export enum WrapMode { REPEAT = 0, CLAMP_TO_EDGE = 0, MIRRORED_REPEAT = 0, } } } /** !#en AnySDK is a third party solution that offers game developers SDK integration without making changes to the SDK's features or parameters.It can do all of this while remaining invisible to your end user.Our goal is to handle all the tedious SDK integration work for you so that you can use your time to focus on the game itself.No matter if it’s the channel SDK, user system, payment system, ad system, statistics system, sharing system or any other type of SDK: we’ll take care of it for you. !#zh AnySDK 为 CP 提供一套第三方 SDK 接入解决方案,整个接入过程,不改变任何 SDK 的功能、特性、参数等,对于最终玩家而言是完全透明无感知的。 目的是让 CP 商能有更多时间更专注于游戏本身的品质,所有 SDK 的接入工作统统交给我们吧。第三方 SDK 包括了渠道SDK、用户系统、支付系统、广告系统、统计系统、分享系统等等。 */ declare module anysdk { /** !#en agent manager of plugin !#zh 插件管理对象 */ export var agentManager : anysdk.AgentManager; /** !#en agent manager of plugin !#zh 插件管理类 */ export class AgentManager { /** !#en AppKey appSecret and privateKey are the only three parameters generated after the packing tool client finishes creating the game. The oauthLoginServer parameter is the API address provided by the game service to login verification !#zh appKey、appSecret、privateKey是通过 AnySDK 客户端工具创建游戏后生成的。 oauthLoginServer参数是游戏服务提供的用来做登陆验证转发的接口地址。 */ init(appKey : string, appSecret : string, privateKey : string, oauthLoginServer : string) : void; /** !#en load all plugins, the operation includes SDK`s initialization !#zh 加载所有插件,该操作包含了 SDKs 初始化 @param target The object to bind to. */ loadAllPlugins(callback : Function, target : any) : void; /** !#en unload all plugins !#zh 卸载插件 */ unloadAllPlugins() : void; /** !#en get user system plugin !#zh 获取用户系统插件 */ getUserPlugin() : anysdk.ProtocolUser; /** !#en get IAP system plugins !#zh 获取支付系统插件 */ getIAPPlugins() : anysdk.ProtocolIAP; /** !#en get IAP system plugin !#zh 获取支付系统插件 */ getIAPPlugin() : anysdk.ProtocolIAP; /** !#en get social system plugin !#zh 获取社交系统插件 */ getSocialPlugin() : anysdk.ProtocolSocial; /** !#en get share system plugin !#zh 获取分享系统插件 */ getSharePlugin() : anysdk.ProtocolShare; /** !#en get analytics system plugin !#zh 获取统计系统插件 */ getAnalyticsPlugin() : anysdk.ProtocolAnalytics; /** !#en get ads system plugin !#zh 获取广告系统插件 */ getAdsPlugin() : anysdk.ProtocolAds; /** !#en get push system plugin !#zh 获取推送系统插件 */ getPushPlugin() : anysdk.ProtocolPush; /** !#en get REC system plugin !#zh 获取录屏系统插件 */ getRECPlugin() : anysdk.ProtocolREC; /** !#en get crash system plugin !#zh 获取崩溃分析系统插件 */ getCrashPlugin() : anysdk.ProtocolCrash; /** !#en get ad track system plugin !#zh 获取广告追踪系统插件 */ getAdTrackingPlugin() : anysdk.ProtocolAdTracking; /** !#en get custom system plugin !#zh 获取自定义系统插件 */ getCustomPlugin() : anysdk.ProtocolCustom; /** !#en get custom parameter !#zh 获取自定义参数 */ getCustomParam() : string; /** !#en get channel id !#zh 获取渠道唯一表示符 */ getChannelId() : string; /** !#en get status of analytics !#zh 获取统计状态 */ isAnaylticsEnabled() : boolean; /** !#en set whether to analytics !#zh 设置是否统计 */ setIsAnaylticsEnabled(enabled : boolean) : void; /** !#en destory instance !#zh 销毁单例 */ end() : void; /** !#en get instance !#zh 获取单例 */ getInstance() : anysdk.AgentManager; } /** !#en plugin protocol !#zh 插件协议 */ export class PluginProtocol { /** !#en Check whether the function is supported !#zh 判断函数是否支持 */ isFunctionSupported(functionName : string) : boolean; /** !#en get plugin name !#zh 获取插件名称 */ getPluginName() : string; /** !#en get plugin version !#zh 获取插件版本 */ getPluginVersion() : string; /** !#en get SDK version !#zh 获取 SDK 版本 */ getSDKVersion() : string; /** !#en void methods for reflections with parameter !#zh 反射调用带参数的void方法 @param args optional arguments */ callFuncWithParam(funName : string, args? : any|anysdk.PluginParam) : void; /** !#en String methods for reflections with parameter !#zh 反射调用带参数的 String 方法 @param args optional arguments */ callStringFuncWithParam(funName : string, args? : any|anysdk.PluginParam) : string; /** !#en int methods for reflections with parameter !#zh 反射调用带参数的 Int 方法 @param args optional arguments */ callIntFuncWithParam(funName : string, args? : any|anysdk.PluginParam) : number; /** !#en boolean methods for reflections with parameter !#zh 反射调用带参数的 boolean 方法 @param args optional arguments */ callBoolFuncWithParam(funName : string, args? : any|anysdk.PluginParam) : boolean; /** !#en float methods for reflections with parameter !#zh 反射调用带参数的 float 方法 @param args optional arguments */ callFloatFuncWithParam(funName : string, args? : any|anysdk.PluginParam) : number; } /** !#en user protocol !#zh 用户系统协议接口 */ export class ProtocolUser extends PluginProtocol { /** !#en login interface !#zh 登录接口 @param args optional arguments */ login(args? : string|any) : void; /** !#en get status of login !#zh 获取登录状态 */ isLogined() : boolean; /** !#en get user ID !#zh 获取用户唯一标示符 */ getUserID() : string; /** !#en get plugin ID !#zh 获取插件ID */ getPluginId() : string; /** !#en set listener !#zh 设置用户系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取用户系统的监听 */ getListener() : Function; /** !#en logout Before to invoke, you need to verdict whether this properties existed !#zh 登出,调用前需要判断属性是否存在 */ logout() : void; /** !#en show toolbar Before to invoke, you need to verdict whether this properties existed !#zh 显示悬浮窗,调用前需要判断属性是否存在 */ showToolBar(place : anysdk.ToolBarPlace) : void; /** !#en hide toolbar Before to invoke, you need to verdict whether this properties existed !#zh 隐藏悬浮窗,调用前需要判断属性是否存在 */ hideToolBar() : void; /** !#en enter platform Before to invoke, you need to verdict whether this properties existed !#zh 显示平台中心,调用前需要判断属性是否存在 */ enterPlatform() : void; /** !#en show exit page Before to invoke, you need to verdict whether this properties existed !#zh 显示退出界面,调用前需要判断属性是否存在 */ exit() : void; /** !#en show pause page Before to invoke, you need to verdict whether this properties existed !#zh 显示暂停界面,调用前需要判断属性是否存在 */ pause() : void; /** !#en Real-name registration Before to invoke, you need to verdict whether this properties existed !#zh 实名注册,调用前需要判断属性是否存在 */ realNameRegister() : void; /** !#en Anti-addiction query Before to invoke, you need to verdict whether this properties existed !#zh 防沉迷查询,调用前需要判断属性是否存在 */ antiAddictionQuery() : void; /** !#en submit game role information Before to invoke, you need to verdict whether this properties existed !#zh 提交角色信息,调用前需要判断属性是否存在 */ submitLoginGameRole(data : any) : void; /** !#en get user information Before to invoke, you need to verdict whether this properties existed !#zh 获取用户信息,调用前需要判断属性是否存在 */ getUserInfo(info : any) : void; /** !#en set login type Before to invoke, you need to verdict whether this properties existed !#zh 设置登录类型,调用前需要判断属性是否存在 */ getAvailableLoginType(info : any) : void; /** !#en set login type Before to invoke, you need to verdict whether this properties existed !#zh 设置登录类型,调用前需要判断属性是否存在 */ setLoginType(loginType : string) : void; /** !#en send to desktop Before to invoke, you need to verdict whether this properties existed !#zh 发送到桌面,调用前需要判断属性是否存在 */ sendToDesktop() : void; /** !#en open bbs Before to invoke, you need to verdict whether this properties existed !#zh 打开论坛,调用前需要判断属性是否存在 */ openBBS() : void; } /** !#en IAP protocol !#zh 支付系统协议接口 */ export class ProtocolIAP extends PluginProtocol { /** !#en pay interface !#zh 支付接口 @param info Type:map */ payForProduct(info : any) : void; /** !#en get order ID !#zh 获取订单ID */ getOrderId() : string; /** !#en reset the pay status !#zh 重置支付状态 */ resetPayState() : void; /** !#en get plugin ID !#zh 获取插件ID */ getPluginId() : string; /** !#en set listener !#zh 设置支付系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取支付系统的监听 */ getListener() : Function; } /** !#en analytics protocol !#zh 统计系统协议接口 */ export class ProtocolAnalytics extends PluginProtocol { /** !#en Start a new session. !#zh 启动会话 */ startSession() : void; /** !#en Stop a session. !#zh 关闭会话 */ stopSession() : void; /** !#en Set the timeout for expiring a session. !#zh 设置会话超时时间 @param millis Type: long */ setSessionContinueMillis(millis : number) : void; /** !#en log an error !#zh 捕捉异常 */ logError(errorId : string, message : string) : void; /** !#en log an event. !#zh 捕捉事件 @param args optional arguments Type: map */ logEvent(errorId : string, args? : any) : void; /** !#en Track an event begin. !#zh 统计事件开始 */ logTimedEventBegin(eventId : string) : void; /** !#en Track an event end. !#zh 统计事件结束 */ logTimedEventEnd(eventId : string) : void; /** !#en set Whether to catch uncaught exceptions to server. !#zh 设置是否开启自动异常捕捉 */ setCaptureUncaughtException(enabled : boolean) : void; /** !#en analytics account information !#zh 统计玩家帐户信息 @param paramMap Type: map */ setAccount(paramMap : any) : void; /** !#en track user to request payment !#zh 跟踪用户支付请求 @param paramMap Type: map */ onChargeRequest(paramMap : any) : void; /** !#en track Successful payment !#zh 追踪用户支付成功 */ onChargeSuccess(orderID : string) : void; /** !#en track failed payment !#zh 追踪用户支付失败 @param paramMap Type: map */ onChargeFail(paramMap : any) : void; /** !#en track Successful payment !#zh 统计玩家支付成功 @param paramMap Type: map */ onChargeOnlySuccess(paramMap : any) : void; /** !#en track user purchase !#zh 统计玩家消费 @param paramMap Type: map */ onPurchase(paramMap : any) : void; /** !#en track user to use goods !#zh 统计玩家使用道具 @param paramMap Type: map */ onUse(paramMap : any) : void; /** !#en track user to reward goods !#zh 统计玩家获取奖励 @param paramMap Type: map */ onReward(paramMap : any) : void; /** !#en start level !#zh 开始关卡 @param paramMap Type: map */ startLevel(paramMap : any) : void; /** !#en finish level !#zh 结束关卡 */ finishLevel(levelID : string) : void; /** !#en failed level !#zh 关卡失败 @param paramMap Type: map */ failLevel(paramMap : any) : void; /** !#en start task !#zh 开始任务 @param paramMap Type: map */ startTask(paramMap : any) : void; /** !#en finish task !#zh 完成任务 */ finishTask(taskID : string) : void; /** !#en failed task !#zh 任务失败 @param paramMap Type: map */ failTask(paramMap : any) : void; } /** !#en share protocol !#zh 分享系统协议接口 */ export class ProtocolShare extends PluginProtocol { /** !#en share interface !#zh 分享 @param info Type: map */ share(info : any) : void; /** !#en set listener !#zh 设置分享系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取分享系统的监听 */ getListener() : Function; } /** !#en ads protocol !#zh 广告系统协议接口 */ export class ProtocolAds extends PluginProtocol { /** !#en hide ads view !#zh 隐藏广告 */ hideAds(adstype : anysdk.AdsType, idx : number) : void; /** !#en preload ads view !#zh 预加载广告 */ preloadAds(adstype : anysdk.AdsType, idx : number) : void; /** !#en query points !#zh 查询分数 */ queryPoints() : number; /** !#en get whether the ads type is supported !#zh 获取广告类型是否支持 */ isAdTypeSupported(arg0 : anysdk.AdsType) : boolean; /** !#en spend point !#zh 消费分数 */ spendPoints(points : number) : void; /** !#en set listener !#zh 设置广告系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取广告系统的监听 */ getListener() : Function; } /** !#en social protocol !#zh 社交系统协议接口 */ export class ProtocolSocial extends PluginProtocol { /** !#en sign in !#zh 登录 */ signIn() : void; /** !#en sign out !#zh 登出 */ signOut() : void; /** !#en submit score !#zh 提交分数 @param score Type: long */ submitScore(leadboardID : string, score : number) : void; /** !#en show the id of Leaderboard page !#zh 根据唯一标识符显示排行榜 */ showLeaderboard(leaderboardID : string) : void; /** !#en show the page of achievements !#zh 显示成就榜 */ showAchievements() : void; /** !#en unlock achievement !#zh 解锁成就 @param info Type: map */ share(info : any) : void; /** !#en set listener !#zh 设置社交系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取社交系统的监听 */ getListener() : Function; /** !#en get friends info Before to invoke, you need to verdict whether this properties existed !#zh 获取好友信息,调用前需要判断属性是否存在 */ pauseRecording() : void; /** !#en interact Before to invoke, you need to verdict whether this properties existed !#zh 订阅,调用前需要判断属性是否存在 */ interact() : void; /** !#en subscribe Before to invoke, you need to verdict whether this properties existed !#zh 关注,调用前需要判断属性是否存在 */ subscribe() : void; } /** !#en push protocol !#zh 推送系统协议接口 */ export class ProtocolPush extends PluginProtocol { /** !#en start Push services !#zh 启动推送服务 */ startPush() : void; /** !#en close Push services !#zh 暂停推送服务 */ closePush() : void; /** !#en delete alias !#zh 删除别名 */ delAlias(alias : string) : void; /** !#en set alias !#zh 设置别名 */ setAlias(alias : string) : void; /** !#en delete tags !#zh 删除标签 @param tags Type: list */ delTags(tags : any) : void; /** !#en set tags !#zh 设置标签 @param tags Type: list */ setTags(tags : any) : void; /** !#en set listener !#zh 设置推送系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取推送系统的监听 */ getListener() : Function; } /** !#en crash protocol !#zh 崩溃分析系统协议接口 */ export class ProtocolCrash extends PluginProtocol { /** !#en set user identifier !#zh 统计用户唯一标识符 */ setUserIdentifier(identifier : string) : void; /** !#en The uploader captured in exception information !#zh 上报异常信息 */ reportException(message : string, exception : string) : void; /** !#en customize logging !#zh 自定义日志记录 */ leaveBreadcrumb(breadcrumb : string) : void; } /** !#en REC protocol !#zh 录屏系统协议接口 */ export class ProtocolREC extends PluginProtocol { /** !#en share video !#zh 分享视频 @param info Type: map */ share(info : any) : void; /** !#en Start to record video !#zh 开始录制视频 */ startRecording() : void; /** !#en Start to record video !#zh 结束录制视频 */ stopRecording() : void; /** !#en set listener !#zh 设置录屏系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取录屏系统的监听 */ getListener() : Function; /** !#en pause to record video Before to invoke, you need to verdict whether this properties existed !#zh 暂停录制视频,调用前需要判断属性是否存在 */ pauseRecording() : void; /** !#en resume to record video Before to invoke, you need to verdict whether this properties existed !#zh 恢复录制视频,调用前需要判断属性是否存在 */ resumeRecording() : void; /** !#en get whether the device is isAvailable Before to invoke, you need to verdict whether this properties existed !#zh 获取设备是否可用,调用前需要判断属性是否存在 */ isAvailable() : boolean; /** !#en get status of recording Before to invoke, you need to verdict whether this properties existed !#zh 获取录制状态,调用前需要判断属性是否存在 */ isRecording() : boolean; /** !#en show toolbar Before to invoke, you need to verdict whether this properties existed !#zh 显示悬浮窗,调用前需要判断属性是否存在 */ showToolBar() : void; /** !#en hide toolbar Before to invoke, you need to verdict whether this properties existed !#zh 隐藏悬浮窗,调用前需要判断属性是否存在 */ hideToolBar() : void; /** !#en show video center Before to invoke, you need to verdict whether this properties existed !#zh 显示视频中心,调用前需要判断属性是否存在 */ showVideoCenter() : void; /** !#en enter platform Before to invoke, you need to verdict whether this properties existed !#zh 显示平台中心,调用前需要判断属性是否存在 */ enterPlatform() : void; /** !#en Set the video data, it is recommended to check whether are recorded firstly Before to invoke, you need to verdict whether this properties existed !#zh 设置视频相关数据,建议先检查是否是正在录制,调用前需要判断属性是否存在 @param info Type: map */ setMetaData(info : any) : void; } /** !#en ad tracking protocol !#zh 广告追踪系统协议接口 */ export class ProtocolAdTracking extends PluginProtocol { /** !#en Call this method if you want to track register events as happening during a section. !#zh 统计用户注册信息 @param productInfo Type: map */ onPay(productInfo : any) : void; /** !#en Call this method if you want to track register events as happening during a section. !#zh 统计用户注册信息 @param userInfo Type: map */ onLogin(userInfo : any) : void; /** !#en Call this method if you want to track register events as happening during a section. !#zh 统计用户注册信息 */ onRegister(userId : string) : void; /** !#en Call this method if you want to track custom events with parameters as happening during a section. !#zh 统计自定义事件 @param paramMap Type: map */ trackEvent(eventId : string, paramMap : any) : void; /** !#en Call this method with parameters if you want to create role as happening during a section. !#zh 统计创建角色事件,调用前需要判断属性是否存在 @param userInfo Type: map */ onCreateRole(userInfo : any) : void; /** !#en Call this method if you want to track levelup events with parameters as happening during a section. Before to invoke, you need to verdict whether this properties existed !#zh 统计角色升级事件,调用前需要判断属性是否存在 @param info Type: map */ onLevelUp(info : any) : void; /** !#en Invoke this method with parameters if you want to start to pay as happening during a section. Before to invoke, you need to verdict whether this properties existed !#zh 统计开始充值事件,调用前需要判断属性是否存在 @param info Type: map */ onStartToPay(info : any) : void; } /** !#en custom protocol !#zh 自定义系统协议接口 */ export class ProtocolCustom extends PluginProtocol { /** !#en set listener !#zh 设置自定义系统的监听 */ setListener(listener : Function, target : any) : void; /** !#en get listener !#zh 获取自定义系统的监听 */ getListener() : Function; } /** !#en Data structure class !#zh 数据结构类 */ export class PluginParam { /** !#en create plugin parameters !#zh 创建对象 */ create(parameters : number|string|any) : anysdk.PluginParam; } /** !#en The callback of user system !#zh 用户系统回调 */ export enum UserActionResultCode { kInitSuccess = 0, kInitFail = 0, kLoginSuccess = 0, kLoginNetworkError = 0, kLoginNoNeed = 0, kLoginFail = 0, kLoginCancel = 0, kLogoutSuccess = 0, kLogoutFail = 0, kPlatformEnter = 0, kPlatformBack = 0, kPausePage = 0, kExitPage = 0, kAntiAddictionQuery = 0, kRealNameRegister = 0, kAccountSwitchSuccess = 0, kAccountSwitchFail = 0, kOpenShop = 0, kAccountSwitchCancel = 0, kUserExtension = 0, kSendToDesktopSuccess = 0, kSendToDesktopFail = 0, kGetAvailableLoginTypeSuccess = 0, kGetAvailableLoginTypeFail = 0, kGetUserInfoSuccess = 0, kGetUserInfoFail = 0, kOpenBBSSuccess = 0, kOpenBBSFail = 0, } /** !#en The toolbar position of user type !#zh 用户系统悬浮窗位置 */ export enum ToolBarPlace { kToolBarTopLeft = 0, kToolBarTopRight = 0, kToolBarMidLeft = 0, kToolBarMidRight = 0, kToolBarBottomLeft = 0, kToolBarBottomRight = 0, } /** !#en The callback of requesting reStringge !#zh 支付系统支付请求回调 */ export enum PayResultCode { kPaySuccess = 0, kPayFail = 0, kPayCancel = 0, kPayNetworkError = 0, kPayProductionInforIncomplete = 0, kPayInitSuccess = 0, kPayInitFail = 0, kPayNowPaying = 0, kPayReStringgeSuccess = 0, kPayExtension = 0, kPayNeedLoginAgain = 0, kRequestSuccess = 0, kRequestFail = 0, } /** !#en The enum of account type !#zh 统计系统的账号类型 */ export enum AccountType { ANONYMOUS = 0, REGISTED = 0, SINA_WEIBO = 0, TENCENT_WEIBO = 0, QQ = 0, ND91 = 0, } /** !#en The enum of account operation !#zh 统计系统的账号操作 */ export enum AccountOperate { LOGIN = 0, LOGOUT = 0, REGISTER = 0, } /** !#en The enum of gender !#zh 统计系统的账号性别 */ export enum AccountGender { MALE = 0, FEMALE = 0, UNKNOWN = 0, } /** !#en The enum of task type !#zh 统计系统的任务类型 */ export enum TaskType { GUIDE_LINE = 0, MAIN_LINE = 0, BRANCH_LINE = 0, DAILY = 0, ACTIVITY = 0, OTHER = 0, } /** !#en The callback of share system !#zh 分享系统回调 */ export enum ShareResultCode { kShareSuccess = 0, kShareFail = 0, kShareCancel = 0, kShareNetworkError = 0, kShareExtension = 0, } /** !#en The callback of social system !#zh 社交系统回调 */ export enum SocialRetCode { kScoreSubmitSucceed = 0, kScoreSubmitfail = 0, kAchUnlockSucceed = 0, kAchUnlockFail = 0, kSocialSignInSucceed = 0, kSocialSignInFail = 0, kSocialSignOutSucceed = 0, kSocialSignOutFail = 0, kSocialGetGameFriends = 0, kSocialExtensionCode = 0, kSocialGetFriendsInfoSuccess = 0, kSocialGetFriendsInfoFail = 0, kSocialAlreadySubscription = 0, kSocialNoSubscription = 0, kSocialSubscriptionFail = 0, } /** !#en The callback of ads system !#zh 广告系统回调 */ export enum AdsResultCode { kAdsReceived = 0, kAdsShown = 0, kAdsDismissed = 0, kPointsSpendSucceed = 0, kPointsSpendFailed = 0, kNetworkError = 0, kUnknownError = 0, kOfferWallOnPointsChanged = 0, kRewardedVideoWithReward = 0, kInAppPurchaseFinished = 0, kAdsClicked = 0, kAdsExtension = 0, } /** !#en The enum of ads position !#zh 广告位置 */ export enum AdsPos { kPosCenter = 0, kPosTop = 0, kPosTopLeft = 0, kPosTopRight = 0, kPosBottom = 0, kPosBottomLeft = 0, kPosBottomRight = 0, } /** !#en The enum of ads type !#zh 广告类型 */ export enum AdsType { AD_TYPE_BANNER = 0, AD_TYPE_FULLSCREEN = 0, AD_TYPE_MOREAPP = 0, AD_TYPE_OFFERWALL = 0, AD_TYPE_REWARDEDVIDEO = 0, AD_TYPE_NATIVEEXPRESS = 0, AD_TYPE_NATIVEADVANCED = 0, } /** !#en The callback of push system !#zh 推送系统回调 */ export enum PushActionResultCode { kPushReceiveMessage = 0, kPushExtensionCode = 0, } /** !#en The callback of custom system !#zh 自定义系统回调 */ export enum CustomResultCode { kCustomExtension = 0, } /** !#en The callback of REC system !#zh 录屏系统回调 */ export enum RECResultCode { kRECInitSuccess = 0, kRECInitFail = 0, kRECStartRecording = 0, kRECStopRecording = 0, kRECPauseRecording = 0, kRECResumeRecording = 0, kRECEnterSDKPage = 0, kRECQuitSDKPage = 0, kRECShareSuccess = 0, kRECShareFail = 0, kRECExtension = 0, } } /** !#en The global main namespace of Spine, all classes, functions, properties and constants of Spine are defined in this namespace !#zh Spine 的全局的命名空间, 与 Spine 相关的所有的类,函数,属性,常量都在这个命名空间中定义。 */ declare module sp { /** !#en The skeleton of Spine <br/> <br/> (Skeleton has a reference to a SkeletonData and stores the state for skeleton instance, which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible. <br/> Multiple skeletons can use the same SkeletonData which includes all animations, skins, and attachments.) <br/> !#zh Spine 骨骼动画 <br/> <br/> (Skeleton 具有对骨骼数据的引用并且存储了骨骼实例的状态, 它由当前的骨骼动作,slot 颜色,和可见的 slot attachments 组成。<br/> 多个 Skeleton 可以使用相同的骨骼数据,其中包括所有的动画,皮肤和 attachments。 */ export class Skeleton extends _RendererUnderSG { /** !#en The skeletal animation is paused? !#zh 该骨骼动画是否暂停。 */ paused : boolean; /** !#en The skeleton data contains the skeleton information (bind pose bones, slots, draw order, attachments, skins, etc) and animations but does not hold any state.<br/> Multiple skeletons can share the same skeleton data. !#zh 骨骼数据包含了骨骼信息(绑定骨骼动作,slots,渲染顺序, attachments,皮肤等等)和动画但不持有任何状态。<br/> 多个 Skeleton 可以共用相同的骨骼数据。 */ skeletonData : SkeletonData; /** !#en The name of default skin. !#zh 默认的皮肤名称。 */ defaultSkin : string; /** !#en The name of default animation. !#zh 默认的动画名称。 */ defaultAnimation : string; /** !#en The name of current playing animation. !#zh 当前播放的动画名称。 */ animation : string; _defaultSkinIndex : number; /** !#en TODO !#zh 是否循环播放当前骨骼动画。 */ loop : boolean; /** !#en Indicates whether to enable premultiplied alpha. You should disable this option when image's transparent area appears to have opaque pixels, or enable this option when image's half transparent area appears to be darken. !#zh 是否启用贴图预乘。 当图片的透明区域出现色块时需要关闭该选项,当图片的半透明区域颜色变黑时需要启用该选项。 */ premultipliedAlpha : boolean; /** !#en The time scale of this skeleton. !#zh 当前骨骼中所有动画的时间缩放率。 */ timeScale : number; /** !#en Indicates whether open debug slots. !#zh 是否显示 slot 的 debug 信息。 */ debugSlots : boolean; /** !#en Indicates whether open debug bones. !#zh 是否显示 bone 的 debug 信息。 */ debugBones : boolean; /** !#en Computes the world SRT from the local SRT for each bone. !#zh 重新更新所有骨骼的世界 Transform, 当获取 bone 的数值未更新时,即可使用该函数进行更新数值。 @example ```js var bone = spine.findBone('head'); cc.log(bone.worldX); // return 0; spine.updateWorldTransform(); bone = spine.findBone('head'); cc.log(bone.worldX); // return -23.12; ``` */ updateWorldTransform() : void; /** !#en Sets the bones and slots to the setup pose. !#zh 还原到起始动作 */ setToSetupPose() : void; /** !#en Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. !#zh 设置 bone 到起始动作 使用 SkeletonData 中的 BoneData 列表中的值。 */ setBonesToSetupPose() : void; /** !#en Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. !#zh 设置 slot 到起始动作。 使用 SkeletonData 中的 SlotData 列表中的值。 */ setSlotsToSetupPose() : void; /** !#en Finds a bone by name. This does a string comparison for every bone.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Bone object. !#zh 通过名称查找 bone。 这里对每个 bone 的名称进行了对比。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Bone 对象。 */ findBone(boneName : string) : sp.spine.Bone; /** !#en Finds a slot by name. This does a string comparison for every slot.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Slot object. !#zh 通过名称查找 slot。这里对每个 slot 的名称进行了比较。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Slot 对象。 */ findSlot(slotName : string) : sp.spine.Slot; /** !#en Finds a skin by name and makes it the active skin. This does a string comparison for every skin.<br> Note that setting the skin does not change which attachments are visible.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Skin object. !#zh 按名称查找皮肤,激活该皮肤。这里对每个皮肤的名称进行了比较。<br> 注意:设置皮肤不会改变 attachment 的可见性。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Skin 对象。 */ setSkin(skinName : string) : sp.spine.Skin; /** !#en Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Attachment object. !#zh 通过 slot 和 attachment 的名称获取 attachment。Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Attachment 对象。 */ getAttachment(slotName : string, attachmentName : string) : sp.spine.Attachment; /** !#en Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. !#zh 通过 slot 和 attachment 的名字来设置 attachment。 Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。 */ setAttachment(slotName : string, attachmentName : string) : void; /** !#en Sets skeleton data to sp.Skeleton. !#zh 设置 Skeleton 中的 Skeleton Data。 */ setSkeletonData(skeletonData : sp.spine.SkeletonData, ownsSkeletonData : sp.spine.SkeletonData) : void; /** !#en Sets animation state data.<br> The parameter type is {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.AnimationStateData. !#zh 设置动画状态数据。<br> 参数是 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.AnimationStateData。 */ setAnimationStateData(stateData : sp.spine.AnimationStateData) : void; /** !#en Mix applies all keyframe values, interpolated for the specified time and mixed with the current values. !#zh 为所有关键帧设定混合及混合时间(从当前值开始差值)。 */ setMix(fromAnimation : string, toAnimation : string, duration : number) : void; /** !#en Sets event listener. !#zh 设置动画事件监听器。 */ setAnimationListener(target : any, callback : Function) : void; /** !#en Set the current animation. Any queued animations are cleared.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry object. !#zh 设置当前动画。队列中的任何的动画将被清除。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry 对象。 */ setAnimation(trackIndex : number, name : string, loop : boolean) : sp.spine.TrackEntry; /** !#en Adds an animation to be played delay seconds after the current or last queued animation.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry object. !#zh 添加一个动画到动画队列尾部,还可以延迟指定的秒数。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry 对象。 */ addAnimation(trackIndex : number, name : string, loop : boolean, delay? : number) : sp.spine.TrackEntry; /** !#en Find animation with specified name. !#zh 查找指定名称的动画 */ findAnimation(name : string) : sp.spine.Animation; /** !#en Returns track entry by trackIndex.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry object. !#zh 通过 track 索引获取 TrackEntry。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry 对象。 */ getCurrent(trackIndex : void) : sp.spine.TrackEntry; /** !#en Clears all tracks of animation state. !#zh 清除所有 track 的动画状态。 */ clearTracks() : void; /** !#en Clears track of animation state by trackIndex. !#zh 清除出指定 track 的动画状态。 */ clearTrack(trackIndex : number) : void; /** !#en Set the start event listener. !#zh 用来设置开始播放动画的事件监听。 */ setStartListener(listener : Function) : void; /** !#en Set the interrupt event listener. !#zh 用来设置动画被打断的事件监听。 */ setInterruptListener(listener : Function) : void; /** !#en Set the end event listener. !#zh 用来设置动画播放完后的事件监听。 */ setEndListener(listener : Function) : void; /** !#en Set the dispose event listener. !#zh 用来设置动画将被销毁的事件监听。 */ setDisposeListener(listener : Function) : void; /** !#en Set the complete event listener. !#zh 用来设置动画播放一次循环结束后的事件监听。 */ setCompleteListener(listener : Function) : void; /** !#en Set the animation event listener. !#zh 用来设置动画播放过程中帧事件的监听。 */ setEventListener(listener : Function) : void; /** !#en Set the start event listener for specified TrackEntry (only supported on Web). !#zh 用来为指定的 TrackEntry 设置动画开始播放的事件监听。(只支持 Web 平台) */ setTrackStartListener(entry : sp.spine.TrackEntry, listener : Function) : void; /** !#en Set the interrupt event listener for specified TrackEntry (only supported on Web). !#zh 用来为指定的 TrackEntry 设置动画被打断的事件监听。(只支持 Web 平台) */ setTrackInterruptListener(entry : sp.spine.TrackEntry, listener : Function) : void; /** !#en Set the end event listener for specified TrackEntry (only supported on Web). !#zh 用来为指定的 TrackEntry 设置动画播放结束的事件监听。(只支持 Web 平台) */ setTrackEndListener(entry : sp.spine.TrackEntry, listener : Function) : void; /** !#en Set the dispose event listener for specified TrackEntry (only supported on Web). !#zh 用来为指定的 TrackEntry 设置动画即将被销毁的事件监听。(只支持 Web 平台) */ setTrackDisposeListener(entry : sp.spine.TrackEntry, listener : Function) : void; /** !#en Set the complete event listener for specified TrackEntry (only supported on Web). !#zh 用来为指定的 TrackEntry 设置动画一次循环播放结束的事件监听。(只支持 Web 平台) */ setTrackCompleteListener(entry : sp.spine.TrackEntry, listener : Function) : void; /** !#en Set the event listener for specified TrackEntry (only supported on Web). !#zh 用来为指定的 TrackEntry 设置动画帧事件的监听。(只支持 Web 平台) */ setTrackEventListener(entry : sp.spine.TrackEntry, listener : Function) : void; } /** !#en The skeleton data of spine. !#zh Spine 的 骨骼数据。 */ export class SkeletonData extends Asset { /** !#en See http://en.esotericsoftware.com/spine-json-format !#zh 可查看 Spine 官方文档 http://zh.esotericsoftware.com/spine-json-format */ skeletonJson : any; atlasText : string; textures : Texture2D; /** !#en A scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. This can be useful when using different sized images than were used when designing the skeleton in Spine. For example, if using images that are half the size than were used in Spine, a scale of 0.5 can be used. This is commonly used for games that can run with either low or high resolution texture atlases. see http://en.esotericsoftware.com/spine-using-runtimes#Scaling !#zh 可查看 Spine 官方文档: http://zh.esotericsoftware.com/spine-using-runtimes#Scaling */ scale : number; /** !#en Get the included SkeletonData used in spine runtime.<br> Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.SkeletonData object. !#zh 获取 Spine Runtime 使用的 SkeletonData。<br> 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.SkeletonData 对象。 */ getRuntimeData(quiet? : boolean) : sp.spine.SkeletonData; } /** !#en The event type of spine skeleton animation. !#zh 骨骼动画事件类型。 */ export enum AnimationEventType { START = 0, END = 0, COMPLETE = 0, EVENT = 0, } } /** !#en `sp.spine` is the namespace for official Spine Runtime, which officially implemented and maintained by Spine.<br> Please refer to the official documentation for its detailed usage: [http://en.esotericsoftware.com/spine-using-runtimes](http://en.esotericsoftware.com/spine-using-runtimes) !#zh sp.spine 模块是 Spine 官方运行库的 API 入口,由 Spine 官方统一实现和维护,具体用法请参考:[http://zh.esotericsoftware.com/spine-using-runtimes](http://zh.esotericsoftware.com/spine-using-runtimes) */ declare module sp.spine { } /** !#en The global main namespace of DragonBones, all classes, functions, properties and constants of DragonBones are defined in this namespace !#zh DragonBones 的全局的命名空间, 与 DragonBones 相关的所有的类,函数,属性,常量都在这个命名空间中定义。 */ declare module dragonBones { /** !#en The Armature Display of DragonBones <br/> <br/> (Armature Display has a reference to a DragonBonesAsset and stores the state for ArmatureDisplay instance, which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible. <br/> Multiple Armature Display can use the same DragonBonesAsset which includes all animations, skins, and attachments.) <br/> !#zh DragonBones 骨骼动画 <br/> <br/> (Armature Display 具有对骨骼数据的引用并且存储了骨骼实例的状态, 它由当前的骨骼动作,slot 颜色,和可见的 slot attachments 组成。<br/> 多个 Armature Display 可以使用相同的骨骼数据,其中包括所有的动画,皮肤和 attachments。)<br/> */ export class ArmatureDisplay extends _RendererUnderSG { /** !#en The DragonBones data contains the armatures information (bind pose bones, slots, draw order, attachments, skins, etc) and animations but does not hold any state.<br/> Multiple ArmatureDisplay can share the same DragonBones data. !#zh 骨骼数据包含了骨骼信息(绑定骨骼动作,slots,渲染顺序, attachments,皮肤等等)和动画但不持有任何状态。<br/> 多个 ArmatureDisplay 可以共用相同的骨骼数据。 */ dragonAsset : DragonBonesAsset; /** !#en The atlas asset for the DragonBones. !#zh 骨骼数据所需的 Atlas Texture 数据。 */ dragonAtlasAsset : DragonBonesAtlasAsset; /** !#en The name of current armature. !#zh 当前的 Armature 名称。 */ armatureName : string; /** !#en The name of current playing animation. !#zh 当前播放的动画名称。 */ animationName : string; _defaultArmatureIndex : number; /** !#en The time scale of this armature. !#zh 当前骨骼中所有动画的时间缩放率。 */ timeScale : number; /** !#en The play times of the default animation. -1 means using the value of config file; 0 means repeat for ever >0 means repeat times !#zh 播放默认动画的循环次数 -1 表示使用配置文件中的默认值; 0 表示无限循环 >0 表示循环次数 */ playTimes : number; /** !#en Indicates whether open debug bones. !#zh 是否显示 bone 的 debug 信息。 */ debugBones : boolean; /** !#en Play the specified animation. Parameter animName specify the animation name. Parameter playTimes specify the repeat times of the animation. -1 means use the value of the config file. 0 means play the animation for ever. >0 means repeat times. !#zh 播放指定的动画. animName 指定播放动画的名称。 playTimes 指定播放动画的次数。 -1 为使用配置文件中的次数。 0 为无限循环播放。 >0 为动画的重复次数。 */ playAnimation(animName : string, playTimes : number) : dragonBones.AnimationState; /** !#en Get the all armature names in the DragonBones Data. !#zh 获取 DragonBones 数据中所有的 armature 名称 */ getArmatureNames() : any[]; /** !#en Get the all animation names of specified armature. !#zh 获取指定的 armature 的所有动画名称。 */ getAnimationNames(armatureName : string) : any[]; /** !#en Add event listener for the DragonBones Event. !#zh 添加 DragonBones 事件监听器。 */ addEventListener(eventType : dragonBones.EventObject, listener : Function, target : any) : void; /** !#en Remove the event listener for the DragonBones Event. !#zh 移除 DragonBones 事件监听器。 */ removeEventListener(eventType : dragonBones.EventObject, listener : Function, target : any) : void; /** !#en Build the armature for specified name. !#zh 构建指定名称的 armature 对象 */ buildArmature(armatureName : string) : dragonBones.Armature; /** !#en Get the current armature object of the ArmatureDisplay. !#zh 获取 ArmatureDisplay 当前使用的 Armature 对象 */ armature() : any; } /** !#en The skeleton data of dragonBones. !#zh dragonBones 的 骨骼数据。 */ export class DragonBonesAsset extends Asset { /** !#en See http://developer.egret.com/cn/github/egret-docs/DB/dbLibs/dataFormat/index.html !#zh 可查看 DragonBones 官方文档 http://developer.egret.com/cn/github/egret-docs/DB/dbLibs/dataFormat/index.html */ dragonBonesJson : string; } /** !#en The skeleton atlas data of dragonBones. !#zh dragonBones 的骨骼纹理数据。 */ export class DragonBonesAtlasAsset extends Asset { atlasJson : string; texture : Texture2D; } } /** This module provides some JavaScript utilities. All members can be accessed with cc.js */ declare module js { /** Check the obj whether is number or not If a number is created by using 'new Number(10086)', the typeof it will be "object"... Then you can use this function if you care about this case. */ export function isNumber(obj : any) : boolean; /** Check the obj whether is string or not. If a string is created by using 'new String("blabla")', the typeof it will be "object"... Then you can use this function if you care about this case. */ export function isString(obj : any) : boolean; /** This method is deprecated, use cc.js.mixin please.<br> Copy all properties not defined in obj from arguments[1...n] @param obj object to extend its properties @param sourceObj source object to copy properties from */ export function addon(obj : any, sourceObj : any) : any; /** copy all properties from arguments[1...n] to obj */ export function mixin(obj : any, sourceObj : any) : any; /** Derive the class from the supplied base class. Both classes are just native javascript constructors, not created by cc.Class, so usually you will want to inherit using {{#crossLink "cc/Class:method"}}cc.Class {{/crossLink}} instead. @param base the baseclass to inherit */ export function extend(cls : Function, base : Function) : Function; /** Removes all enumerable properties from object */ export function clear(obj : any) : void; /** Get property descriptor in object and all its ancestors */ export function getPropertyDescriptor(obj : any, name : string) : any; /** Get class name of the object, if object is just a {} (and which class named 'Object'), it will return null. (modified from <a href="http://stackoverflow.com/questions/1249531/how-to-get-a-javascript-objects-class">the code from this stackoverflow post</a>) @param obj instance or constructor */ export function getClassName(obj : any|Function) : string; /** Register the class by specified name manually */ export function setClassName(className : string, constructor : Function) : void; /** Unregister a class from fireball. If you dont need a registered class anymore, you should unregister the class so that Fireball will not keep its reference anymore. Please note that its still your responsibility to free other references to the class. @param constructor the class you will want to unregister, any number of classes can be added */ export function unregisterClass(constructor : Function) : void; /** Get the registered class by name */ export function getClassByName(classname : string) : Function; /** Define get set accessor, just help to call Object.defineProperty(...) */ export function getset(obj : any, prop : string, getter : Function, setter : Function, enumerable? : boolean) : void; /** Define get accessor, just help to call Object.defineProperty(...) */ export function get(obj : any, prop : string, getter : Function, enumerable? : boolean) : void; /** Define set accessor, just help to call Object.defineProperty(...) */ export function set(obj : any, prop : string, setter : Function, enumerable? : boolean) : void; /** Defines a polyfill field for obsoleted codes. @param obj YourObject or YourClass.prototype @param obsoleted "OldParam" or "YourClass.OldParam" @param newPropName "NewParam" */ export function obsolete(obj : any, obsoleted : string, newPropName : string, writable? : boolean) : void; /** Defines all polyfill fields for obsoleted codes corresponding to the enumerable properties of props. @param obj YourObject or YourClass.prototype @param objName "YourObject" or "YourClass" */ export function obsoletes(obj : any, objName : any, props : any, writable? : boolean) : void; /** A string tool to construct a string with format string. for example: cc.js.formatStr("a: %s, b: %s", a, b); cc.js.formatStr(a, b, c); */ export function formatStr() : string; /** undefined */ export class array { /** Removes the array item at the specified index. */ removeAt(array : any[], index : number) : void; /** Removes the array item at the specified index. It's faster but the order of the array will be changed. */ fastRemoveAt(array : any[], index : number) : void; /** Removes the first occurrence of a specific object from the array. */ remove(array : any[], value : any) : boolean; /** Removes the first occurrence of a specific object from the array. It's faster but the order of the array will be changed. */ fastRemove(array : any[], value : number) : void; /** Verify array's Type */ verifyType(array : any[], type : Function) : boolean; /** Removes from array all values in minusArr. For each Value in minusArr, the first matching instance in array will be removed. @param array Source Array @param minusArr minus Array */ removeArray(array : any[], minusArr : any[]) : void; /** Inserts some objects at index */ appendObjectsAt(array : any[], addObjs : any[], index : number) : any[]; /** Exact same function as Array.prototype.indexOf. HACK: ugliy hack for Baidu mobile browser compatibility, stupid Baidu guys modify Array.prototype.indexOf for all pages loaded, their version changes strict comparison to non-strict comparison, it also ignores the second parameter of the original API, and this will cause event handler enter infinite loop. Baidu developers, if you ever see this documentation, here is the standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf Seriously ! @param searchElement Element to locate in the array. @param fromIndex The index to start the search at */ indexOf(searchElement : any, fromIndex? : number) : number; /** Determines whether the array contains a specific value. */ contains(array : any[], value : any) : boolean; /** Copy an array's item to a new array (its performance is better than Array.slice) */ copy(array : any[]) : any[]; } }<|fim▁end|>
@param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.