text
stringlengths
1
1.05M
import { KeyboardEvent } from 'react'; const clickOnEnter = <T extends HTMLElement>(event: KeyboardEvent<T>): void => { if (event.key === 'Enter') { const target = event.target as T; target.click(); } }; export default clickOnEnter;
prime_list = [] # loop through numbers 0-50 for num in range(0,51): # check if number is prime if num > 1: for i in range(2,num): if (num % i) == 0: break else: prime_list.append(num) # print prime list print(prime_list) # prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
<reponame>bradpurchase/grocerytime-backend<filename>internal/pkg/gql/resolvers/recipes.go<gh_stars>1-10 package resolvers import ( "github.com/bradpurchase/grocerytime-backend/internal/pkg/auth" "github.com/bradpurchase/grocerytime-backend/internal/pkg/meals" "github.com/graphql-go/graphql" ) // RecipesResolver resolves the recipes query func RecipesResolver(p graphql.ResolveParams) (interface{}, error) { header := p.Info.RootValue.(map[string]interface{})["Authorization"] user, err := auth.FetchAuthenticatedUser(header.(string)) if err != nil { return nil, err } userID := user.ID recipes, err := meals.RetrieveRecipes(userID, p.Args) if err != nil { return nil, err } return recipes, nil } // RecipeResolver resolves the recipe query func RecipeResolver(p graphql.ResolveParams) (interface{}, error) { recipeID := p.Args["id"] recipe, err := meals.RetrieveRecipe(recipeID) if err != nil { return nil, err } return recipe, nil }
package com.mera.callcenter.entities; import java.util.UUID; /** * It represents the call */ public class Call { private UUID id; private long duration; public static long MIN_DURATION = 5; public Call(long duration) { this.duration = duration; this.id = UUID.randomUUID(); } public UUID getId() { return id; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } @Override public String toString(){ return String.format("Call [id: %s, duration: %s sec]", this.id, this.duration); } }
const getItem = (arr, index) => arr[index]; getItem([10, 15, 20], 1); // returns 15;
<gh_stars>0 'use strict'; const structure = require('./stacks-and-queues'); const Queue = structure.Queue; class AnimalShelter { constructor(){ this.number = 0; this.dogs = new Queue(); this.cats = new Queue(); } enqueueAnimal(animal){ if(animal.type === 'cat'){ this.cats.enqueue({animal:animal, number:this.number +1}); } if(animal.type === 'dog'){ this.dogs.enqueue({animal:animal, number:this.number +1}); } } dequeueAnimal(pref){ if(pref !== 'cat' && pref !== 'dog'){ return null; }else{ const cat = this.cats.dequeue(); const dog = this.dogs.dequeue(); console.log(cat, dog); return dog.number > cat.number ? cat : dog; } } } module.exports = AnimalShelter;
<reponame>flvani/site-hostinger /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; window.dataLayer = window.dataLayer || []; SITE.ga = function () { if( ga && ( window.location.href.indexOf( 'diatonicmap.com.br') >= 0 || window.location.href.indexOf( 'androidplatform') >= 0 ) && SITE.getVersion('mainSITE', '' ) !== 'debug' && SITE.getVersion('mainSITE', '' ) !== 'unknown' ) { //console.log("GA desabilitado!"); if(SITE.debug) console.log( 'App is in Debug mode' ) else ga.apply(this, arguments); /* if (window.AnalyticsApplication) { // Call Android interface window.AnalyticsApplication.logEvent(JSON.stringify(arguments)); } else { // No Android interface found //console.log("No native APIs found."); } */ } else { console.log('Funcao ga não definida.'); } }; SITE.findGetParameter = function(parameterName) { var result = null, tmp = []; var items = window.location.search.substr(1).split("&"); for (var index = 0; index < items.length; index++) { tmp = items[index].split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); } return result; }; SITE.getDate = function (){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); return yyyy*10000+mm*100+dd; }; SITE.getVersion = function(tag, label) { var el = document.getElementById(tag); if(!el) return 'unknown'; var res = el.src.match(/\_[0-9]*\.[0-9]*[\.[0-9]*]*/g); return res ? label+res[0].substr(1) : 'debug'; }; SITE.getLanguage = function ( ) { var language = window.navigator.userLanguage || window.navigator.language; if( language.indexOf( '-' ) >= 0 ) { language = language.replace('-', '_' ); for( var id in SITE.properties.known_languages ) { if( id.toLowerCase() === language.toLocaleLowerCase() ) { return id; } } } // não encontrou a linguagem exata, então tenta apenas pelo prefixo. for( var id in SITE.properties.known_languages ) { if( id.substr(0,2) === language.substr(0,2) ) { return id; } } return 'en_US'; }; SITE.LoadProperties = function() { var salvar = false; //FILEMANAGER.removeLocal('diatonic-map.site.properties' ); // usdo para forçar reset da propriedades try{ SITE.properties = JSON.parse( FILEMANAGER.loadLocal('diatonic-map.site.properties' ) ); } catch(e) { waterbug.log( 'Could not load the properties.'); waterbug.show( 'Could not save the properties'); SITE.ga('send', 'event', 'Error', 'html5storage', 'loadingLocal', { nonInteraction: true } ); // SITE.myGtag('event', 'html5storage', { // send_to : 'outros', // event_category: 'Error', // event_action: 'html5storage', // event_label: 'loadingLocal', // event_value: 0, // nonInteraction: true // }); } var ver = SITE.getVersion('mainSITE', '' ); if( ! SITE.properties ) { SITE.ResetProperties(); } else if( ver === 'debug' ) { SITE.properties.options.showConsole = true; } else if( ! SITE.properties.version || SITE.properties.version === 'debug' || parseFloat( SITE.properties.version ) < parseFloat( ver ) ) { SITE.properties.version = ver; salvar = true; } if( !SITE.properties.known_languages ) { SITE.properties.known_languages = { de_DE: { file: 'languages/de_DE.lang', image: "images/de_DE.png", name: 'Deustch' } ,en_US: { file: 'languages/en_US.lang', image: "images/en_US.png", name: 'US English' } ,es_ES: { file: 'languages/es_ES.lang', image: "images/es_ES.png", name: 'Español' } ,fr_FR: { file: 'languages/fr_FR.lang', image: "images/fr_FR.png", name: 'Français' } ,it_IT: { file: 'languages/it_IT.lang', image: "images/it_IT.png", name: 'Italiano' } ,pt_BR: { file: 'languages/pt_BR.lang', image: "images/pt_BR.png", name: 'Português do Brasil' } }; SITE.properties.options.language = SITE.getLanguage() ; SITE.properties.colors.highLight = '#ff0000'; SITE.properties.options.showWarnings = false; SITE.properties.options.showConsole = false; SITE.properties.options.pianoSound = false; SITE.properties.options.autoRefresh = false; SITE.properties.options.keyboardRight = false; SITE.properties.options.suppressTitles = false; salvar = true; } if( ! SITE.properties.studio.media ) { SITE.properties.studio.media = { visible: false ,top: "20px" ,left: "1200px" ,width: 100 ,height: 200 }; SITE.properties.partGen.media = { visible: false ,top: "20px" ,left: "1200px" ,width: 100 ,height: 200 }; salvar = true; } if(!SITE.properties.partEdit) { SITE.properties.partEdit = { media: { visible: false ,top: "20px" ,left: "1200px" ,width: 100 ,height: 200 } , editor : { visible: true ,floating: false ,maximized: false ,top: "40px" ,left: "50px" ,width: "700px" ,height: "480px" } , keyboard: { visible: false ,top: "65px" ,left: "1200px" ,scale: 1 ,mirror: true ,transpose: false ,label: false } }; salvar = true; } if( SITE.properties.options.tabFormat === undefined ) { salvar = true; SITE.properties.options.tabFormat = 0; } if( SITE.properties.options.tabShowOnlyNumbers === undefined ) { salvar = true; SITE.properties.options.tabShowOnlyNumbers=false; } if( salvar ) { SITE.SaveProperties(); } }; SITE.SaveProperties = function() { try{ FILEMANAGER.saveLocal('diatonic-map.site.properties', JSON.stringify(SITE.properties)); } catch(e) { waterbug.log( 'Could not save the properties'); waterbug.show( 'Could not save the properties'); SITE.ga('send', 'event', 'Error', 'html5storage', 'savingLocal', { nonInteraction: true } ); } }; SITE.ResetProperties = function() { SITE.properties = {}; SITE.properties.known_languages = { de_DE: { file: 'languages/de_DE.lang', image: "images/de_DE.png", name: 'Deustch' } ,en_US: { file: 'languages/en_US.lang', image: "images/en_US.png", name: 'US English' } ,es_ES: { file: 'languages/es_ES.lang', image: "images/es_ES.png", name: 'Español' } ,fr_FR: { file: 'languages/fr_FR.lang', image: "images/fr_FR.png", name: 'Français' } ,it_IT: { file: 'languages/it_IT.lang', image: "images/it_IT.png", name: 'Italiano' } ,pt_BR: { file: 'languages/pt_BR.lang', image: "images/pt_BR.png", name: 'Português do Brasil' } }; SITE.properties.version = SITE.getVersion( 'mainSITE', '' ); SITE.properties.colors = { useTransparency: true ,highLight: '#ff0000' ,fill: 'white' ,background: 'none' ,close: '#ff3a3a' ,open: '#ffba3b' }; SITE.properties.options = { language: SITE.getLanguage() ,showWarnings: false ,showConsole: false ,pianoSound: false ,autoRefresh: false ,keyboardRight: false ,suppressTitles: false ,tabFormat: 0 ,tabShowOnlyNumbers: false }; SITE.properties.mediaDiv = { visible: true ,top: "20px" ,left: "1200px" ,width: 100 ,height: 200 }; SITE.properties.tabGen = { abcEditor : { floating: false ,maximized: false ,top: "70px" ,left: "25px" ,width: "940px" ,height: "560px" } , tabEditor : { floating: false ,maximized: false ,top: "140px" ,left: "75px" ,width: "940px" ,height: "560px" } }; SITE.properties.partEdit = { media: { visible: false ,top: "20px" ,left: "1200px" ,width: 100 ,height: 200 } , editor : { visible: true ,floating: false ,maximized: false ,top: "40px" ,left: "50px" ,width: "700px" ,height: "480px" } , keyboard: { visible: false ,top: "65px" ,left: "1200px" ,scale: 1 ,mirror: true ,transpose: false ,label: false } }; SITE.properties.partGen = { showABCText:false , convertFromClub:false , convertToClub:false , media: { visible: false ,top: "20px" ,left: "1200px" ,width: 100 ,height: 200 } , editor : { visible: true ,floating: false ,maximized: false ,top: "40px" ,left: "50px" ,width: "700px" ,height: "480px" } , keyboard: { visible: false ,top: "65px" ,left: "1200px" ,scale: 1 ,mirror: true ,transpose: false ,label: false } }; SITE.properties.studio = { mode: 'normal' ,timerOn: false ,trebleOn: true ,bassOn: true , media: { visible: false ,top: "20px" ,left: "1200px" ,width: 100 ,height: 200 } ,editor : { visible: true ,floating: false ,maximized: false ,top: "40px" ,left: "50px" ,width: "700px" ,height: "480px" } , keyboard: { visible: false ,top: "65px" ,left: "1200px" ,scale: 1 ,mirror: true ,transpose: false ,label: false } }; FILEMANAGER.saveLocal( 'ultimaTablaturaEditada', '' ); FILEMANAGER.saveLocal( 'ultimaPartituraEditada', '' ); SITE.SaveProperties(); }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; if (!window.SITE.lang) window.SITE.lang = {}; SITE.Translator = function(options) { options = options || {}; if( ! options.language ) { options.language = 'pt_BR'; } this.language = null; this.loadLanguage(options.language, options.callback); }; SITE.Translator.prototype.loadLanguage = function(lang, callback) { var toLoad = 1; var that = this; FILEMANAGER.register('LANG'); if( ! SITE.properties || ! SITE.properties.known_languages ) { SITE.ResetProperties(); } if( ! SITE.properties.known_languages[lang] ) { that.log( "Unknown language: "+ lang +". Loading English..." ); lang='en_US'; SITE.properties.options.language = lang; SITE.SaveProperties(); } var arq = SITE.properties.known_languages[lang].file; $.getJSON( arq, { format: "json" }) .done(function( data ) { FILEMANAGER.deregister('LANG', true); that.language = data; //that.log( data.langName + ": ok.."); }) .fail(function( data, textStatus, error ) { FILEMANAGER.deregister('LANG', false); that.log( "Failed to load language "+ lang +":\nLoading: " + data.responseText.substr(1,40) + '...\nError:\n ' + textStatus + ", " + error +'.' ); }) .always(function() { toLoad --; if( toLoad === 0 ) { callback && callback(); } }); }; SITE.Translator.prototype.menuPopulate = function(menu, ddmId ) { var m, toSel; menu.emptySubMenu( ddmId ); for( var id in SITE.properties.known_languages ) { var tt = '<img src="'+ SITE.properties.known_languages[id].image +'" />&#160;' + SITE.properties.known_languages[id].name; m = menu.addItemSubMenu( ddmId, tt + '|' + id ); if( this.language && this.language.id===id) { toSel = m; } } if( toSel ) menu.setSubMenuTitle( ddmId, menu.selectItem( ddmId, toSel )); }; SITE.Translator.prototype.getResource = function(id) { if(!this.language) return null; var res = this.language.resources[id]; (!res) && this.log( 'Missing translation for "' + id + '" in "' + this.language.langName + '".' ); return res; }; SITE.Translator.prototype.translate = function(container) { if(!this.language) return; container = container || document; var translables = container.querySelectorAll('[data-translate]'); var translablesArray = Array.prototype.slice.apply(translables); // for( var item of translablesArray ) { for( var i=0; i < translablesArray.length; i ++ ) { var item = translablesArray[i]; var vlr = this.language.resources[item.getAttribute("data-translate")]; if( vlr ) { switch( item.nodeName ) { case 'INPUT': if( item.type === 'text' ) { item.title = vlr.tip; item.value = vlr.val; } break; case 'BUTTON': case 'DIV': case 'I': item.title = vlr; break; default: item.innerHTML = vlr; } } else { this.log( 'Missing translatation for "' +item.getAttribute("data-translate") + '" in "' + this.language.langName + '".' ); } } }; SITE.Translator.prototype.sortLanguages = function () { this.languages.sort( function(a,b) { return parseInt(a.menuOrder) - parseInt(b.menuOrder); }); }; SITE.Translator.prototype.log = function(msg) { if( msg.substr( 27, 7 ) === 'CORONA_' ) return; if( msg.substr( 27, 7 ) === 'HOHNER_' ) return; if( msg.substr( 27, 6 ) === 'GAITA_' ) return; if( msg.substr( 27, 11 ) === 'CONCERTINA_' ) return; waterbug.log( msg ); (SITE.properties.options.showConsole) && waterbug.show(); }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; SITE.Media = function( parent, btShowMedia, props ) { var that = this; this.Div = parent || null; this.proportion = 0.55666667; this.youTubeURL = false; this.properties = props; if(btShowMedia) { this.showMediaButton = document.getElementById( btShowMedia ); this.showMediaButton.addEventListener('click', function () { that.callback('OPEN'); }, false ); } this.mediaWindow = new DRAGGABLE.ui.Window( this.Div , null , {title: 'showMedia', translator: SITE.translator , alternativeResize: true , top: this.properties.top , left: this.properties.left } , {listener: this, method: 'callback'} ); }; SITE.Media.prototype.callback = function( e ) { switch(e) { case 'RESIZE': this.resize(); var m = this.mediaWindow.dataDiv; this.properties.width = m.clientWidth; this.properties.height = m.clientHeight; SITE.SaveProperties(); break; case 'MOVE': var m = this.mediaWindow.topDiv; this.properties.top = m.style.top; this.properties.left = m.style.left; SITE.SaveProperties(); break; case 'OPEN': this.properties.visible = true; SITE.SaveProperties(); this.mediaWindow.setVisible(true); this.resize(); this.posiciona(); if(this.showMediaButton) this.showMediaButton.style.display = 'none'; break; case 'CLOSE': this.pause(); this.properties.visible = false; SITE.SaveProperties(); if(this.showMediaButton) { this.mediaWindow.setVisible(false); this.showMediaButton.style.display = 'block'; } break; } return false; }; SITE.Media.prototype.pause = function() { if(!this.mediaWindow || !this.currTab ) return; var iframe = this.currTab.div.getElementsByTagName("iframe")[0]; if(!iframe) return; iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo", "args":""}', '*'); //iframe.postMessage('{"event":"command","func":"playVideo", "args":""}', '*'); }; SITE.Media.prototype.show = function(tab) { var that = this; var url, embed; if(tab.abc && tab.abc.metaText.url ) { url = tab.abc.metaText.url; } if(url) { var width = 300; var maxTitle=17; if( url !== this.url ) { this.url = url; if(this.properties.width > 100 ) { width = this.properties.width; maxTitle = Math.round((width-100)/11); // aproximação } else if( window.innerWidth >= 1200 ) { width = 600; maxTitle=46; } else if( window.innerWidth >= 950 ) { width = 400; maxTitle=27; } var height = width * this.proportion; this.mediaWindow.dataDiv.style.width = width + 'px'; this.mediaWindow.topDiv.style.width = width + 'px'; this.mediaWindow.dataDiv.style.height = height + 'px'; this.mediaWindow.topDiv.style.height = height + 'px'; if( ! this.tabDiv ) { this.tabDiv = document.createElement('div'); this.tabDiv.className='media-tabs'; this.mediaWindow.topDiv.appendChild(this.tabDiv); } else { this.tabDiv.innerHTML = ""; this.mediaWindow.dataDiv.innerHTML = ""; } var aUrl = url.split('\n'); this.tabs = {}; this.currTab = null; for( var r = 0; r < aUrl.length && r < 10; r ++ ) { var mId = (this.mediaWindow.id*10 + r); this.youTubeURL = (aUrl[r].match(/www.youtube-nocookie.com/g)!== null); this.isPDF = (aUrl[r].match(/.*pdf/)!== null); var par=aUrl[r].match(/\&.*\;/g); var cleanedUrl = aUrl[r]; var tit = ""; if( par ){ cleanedUrl = aUrl[r].replace( par[0], ""); tit = par[0].substring( 3, par[0].length-1); if( tit.length > maxTitle ) { tit = tit.substring(0, maxTitle) + '...'; } } var dv = document.createElement('div'); dv.className='media-content'; this.mediaWindow.dataDiv.appendChild(dv); if( this.youTubeURL ) { embed = '<iframe id="e'+ mId + '" src="'+cleanedUrl+'?rel=0&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" allowfullscreen="allowfullscreen" ></iframe>'; } else { embed = '<embed id="e'+ mId +'" src="'+cleanedUrl+'" "></embed>'; } dv.innerHTML = embed; this.embed = document.getElementById( 'e' + mId ); this.embed.style.width = '100%'; this.embed.style.height = ( this.youTubeURL? '100%' : (this.isPDF? 'calc(100% - 4px)': 'auto' ) ); this.tabs['w'+mId] = {div:dv, tit:tit, u2be: this.youTubeURL}; if( aUrl.length > 1 ) { var el = document.createElement('input'); el.id = 'w'+mId; el.type = 'radio'; el.name = 'mediaControl' + this.mediaWindow.id; el.className = 'tab-selector-' + r; this.tabDiv.appendChild(el); var el = document.createElement('label'); el.htmlFor = 'w'+mId; el.className = 'media-tab-label-' + r; el.innerHTML = '#'+(r+1); this.tabDiv.appendChild(el); } } this.showTab = function( id ) { this.pause(); for( var m in this.tabs ) { this.tabs[m].div.className = 'media-content'; if(!id) { // mostra o primeiro id = m; var chk = document.getElementById(id); if(chk) chk.checked = true; } } this.tabs[id].div.className = 'media-visible'; this.currTab = this.tabs[id]; this.mediaWindow.dataDiv.style.overflow = this.currTab.u2be? 'hidden':'auto'; this.mediaWindow.setSubTitle( this.currTab.tit? '- ' + this.currTab.tit: "" ); this.resize(); //this.currTab.div.addEventListener('click', function() {alert(that.currTab.tit);} ); //var iframe = this.currTab.div.getElementsByTagName("iframe")[0]; //this.mediaWindow.dataDiv.addEventListener('focus', function() {alert(that.currTab.tit);} ); }; if( aUrl.length > 1 ) { // tab control var radios = document.getElementsByName( 'mediaControl'+ this.mediaWindow.id ); for( var r=0; r < radios.length; r ++ ) { radios[r].addEventListener('change', function() { that.showTab( this.id ); }); } } that.showTab(); // mostra a primeira aba } if(this.showMediaButton) this.showMediaButton.style.display = (this.properties.visible ? 'none' : 'inline'); this.mediaWindow.setVisible( this.properties.visible ); if( this.properties.visible ) { this.resize(); this.posiciona(); } else { this.pause(); } } else { this.pause(); this.mediaWindow.setVisible(false); if(this.showMediaButton) this.showMediaButton.style.display = 'none'; } }; // posiciona a janela de mídia, se disponível SITE.Media.prototype.posiciona = function () { if( ! this.mediaWindow.topDiv || this.mediaWindow.topDiv.style.display === 'none' ) return; //var w = window.innerWidth; var w = document.body.clientWidth || document.documentElement.clientWidth || window.innerWidth; // linha acrescentada para tratar layout da app w = Math.min(w, this.mediaWindow.parent.clientWidth); var k = this.mediaWindow.topDiv; var x = parseInt(k.style.left.replace('px', '')); var xi = x; if( x + k.offsetWidth > w ) { x = (w - (k.offsetWidth + 30)); } if(x < 0) x = 10; if( x !== xi ) { k.style.left = x+"px"; this.properties.left = x+"px"; SITE.SaveProperties(); } }; SITE.Media.prototype.resize = function() { var d = this.mediaWindow.menuDiv.clientHeight + (this.mediaWindow.bottomBar? this.mediaWindow.bottomBar.clientHeight : 0 ); this.mediaWindow.dataDiv.style.width = this.mediaWindow.topDiv.clientWidth + 'px'; this.mediaWindow.dataDiv.style.height = (this.mediaWindow.topDiv.clientHeight - d ) + 'px'; if( this.currTab.u2be ) { var h = (this.mediaWindow.topDiv.clientWidth*this.proportion); this.mediaWindow.dataDiv.style.height = h + 'px'; this.mediaWindow.topDiv.style.height = (h + d ) + 'px'; } }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; SITE.Mapa = function( interfaceParams, tabParams, playerParams ) { document.body.style.overflow = 'hidden'; var that = this; this.ypos = 0; // esta variável é usada para ajustar o scroll durante a execução do midi this.lastStaffGroup = -1; // também auxilia no controle de scroll ABCXJS.write.color.useTransparency = SITE.properties.colors.useTransparency; ABCXJS.write.color.highLight = SITE.properties.colors.highLight; DIATONIC.map.color.fill = SITE.properties.colors.fill; DIATONIC.map.color.background = SITE.properties.colors.background; DIATONIC.map.color.close = SITE.properties.colors.close; DIATONIC.map.color.open = SITE.properties.colors.open; this.loadByIdx = this.songId = interfaceParams.songId; // debug = '2054'; this.keyboardDiv = interfaceParams.keyboardDiv; this.fileLoadMap = document.getElementById('fileLoadMap'); this.fileLoadRepertoire = document.getElementById('fileLoadRepertoire'); this.settingsMenu = document.getElementById(interfaceParams.settingsMenu); this.mapDiv = document.getElementById(interfaceParams.mapDiv); this.accordion = new window.ABCXJS.tablature.Accordion( interfaceParams.accordion_options , SITE.properties.options.tabFormat ,!SITE.properties.options.tabShowOnlyNumbers ); this.abcParser = new ABCXJS.parse.Parse( null, this.accordion ); this.midiParser = new ABCXJS.midi.Parse(); this.midiPlayer = new ABCXJS.midi.Player(this); this.menu = new DRAGGABLE.ui.DropdownMenu( interfaceParams.mapMenuDiv , { listener: that, method:'menuCallback', translate: true } , [{title: 'Acordeões', ddmId: 'menuGaitas', itens: [] } ,{title: 'Repertório', ddmId: 'menuRepertorio', itens: [ 'Índice|IDXREPERTOIRE', 'Restaurar o original|RESTOREREPERTOIRE', 'Carregar do drive local|LOADREPERTOIRE', 'Exportar para drive local|EXPORTREPERTOIRE', '---', 'Extrair tablatura|PART2TAB', 'Tablatura&nbsp;&nbsp;<i class="ico-open-right"></i> Partitura|TAB2PART', 'ABC&nbsp;&nbsp;<i class="ico-open-right"></i> Partitura|ABC2PART' ]} ,{title: 'Informações', ddmId: 'menuInformacoes', itens: [ 'Mapas para acordeões|MAPS', 'Tablaturas para acordeões|TABS', //'Tablaturas para gaita transportada <img src="images/novo.png">|TABSTRANSPORTADA', 'Tablaturas para gaita transportada|TABSTRANSPORTADA', 'Símbolos de Repetição|JUMPS', 'Estúdio ABCX|ESTUDIO', 'Formato ABCX|ABCX', 'Vídeo Tutoriais|TUTORIAL', 'Sobre|ABOUT' ]} ]); this.menu.disableSubItem( 'menuInformacoes', 'ESTUDIO' ); this.menu.disableSubItem( 'menuInformacoes', 'ABCX' ); this.menu.disableSubItem( 'menuInformacoes', 'TUTORIAL' ); this.accordionSelector = new ABCXJS.edit.AccordionSelector( 'menuGaitas', this.menu, { listener:this, method: 'menuCallback' }, [ '---', 'Salvar mapa corrente|SAVEMAP', 'Carregar mapa do disco local|LOADMAP' ] ); // tab control var radios = document.getElementsByName( tabParams.tabRadioGroup); for( var r=0; r < radios.length; r ++ ) { radios[r].addEventListener('change', function() { that.showTab(this.id); }); } this.tuneContainerDiv = document.getElementById(tabParams.tuneContainerDiv); this.renderedTune = {text:undefined, abc:undefined, title:undefined, tab:'songs' ,div: document.getElementById(tabParams.songSelectorParms.tabDiv) ,selector: document.getElementById(tabParams.songSelectorParms.menuDiv) }; this.renderedChord = {text:undefined, abc:undefined, title:undefined, tab: 'chords' ,div: document.getElementById(tabParams.chordSelectorParms.tabDiv) ,selector: document.getElementById(tabParams.chordSelectorParms.menuDiv) }; this.renderedPractice = {text:undefined, abc:undefined, title:undefined, tab: 'practices' ,div: document.getElementById(tabParams.practiceSelectorParms.tabDiv) ,selector: document.getElementById(tabParams.practiceSelectorParms.menuDiv) }; // player control this.playButton = document.getElementById(playerParams.playBtn); this.stopButton = document.getElementById(playerParams.stopBtn); this.currentPlayTimeLabel = document.getElementById(playerParams.currentPlayTimeLabel); // screen control this.media = new SITE.Media( this.mapDiv, interfaceParams.btShowMedia, SITE.properties.mediaDiv ); this.buttonChangeNotation = document.getElementById(interfaceParams.btChangeNotation); this.printButton = document.getElementById(interfaceParams.printBtn); this.toolsButton = document.getElementById(interfaceParams.toolsBtn); this.gaitaNamePlaceHolder = document.getElementById(interfaceParams.accordionNamePlaceHolder); this.gaitaImagePlaceHolder = document.getElementById(interfaceParams.accordionImagePlaceHolder); //this.printButton.addEventListener("touchstart", function(event) { that.printPartiture(this, event); }, false); this.printButton.addEventListener("click", function(event) { that.printPartiture(this, event); }, false); //this.toolsButton.addEventListener("touchstart", function(event) { that.openEstudio(this, event); }, false); this.toolsButton.addEventListener("click", function(event) { that.openEstudio(this, event); }, false); this.fileLoadMap.addEventListener('change', function(event) { that.loadMap(event); }, false); this.fileLoadRepertoire.addEventListener('change', function(event) { that.carregaRepertorioLocal(event); }, false); this.settingsMenu.addEventListener("click", function(evt) { evt.preventDefault(); this.blur(); that.showSettings(); }, false ); this.buttonChangeNotation.addEventListener("click", function(evt) { evt.preventDefault(); this.blur(); that.accordion.changeNotation(); }, false ); this.playerCallBackOnScroll = function( player ) { that.setScrolling( player ); }; this.playerCallBackOnPlay = function( player ) { var strTime = player.getTime().cTime; if(that.gotoMeasureButton) that.gotoMeasureButton.value = player.currentMeasure; if(that.currentPlayTimeLabel) that.currentPlayTimeLabel.innerHTML = strTime; }; this.playerCallBackOnEnd = function( player ) { var currentABC = that.getActiveTab(); that.playButton.title = SITE.translator.getResource("playBtn"); that.playButton.innerHTML = '<i class="ico-play"></i>'; currentABC.abc.midi.printer.clearSelection(); that.accordion.clearKeyboard(true); }; this.playButton.addEventListener("click", function(evt) { evt.preventDefault(); //timeout para garantir o inicio da execucao window.setTimeout(function(){ that.startPlay( 'normal' );}, 0 ); }, false); this.stopButton.addEventListener("click", function(evt) { evt.preventDefault(); if(that.currentPlayTimeLabel) that.currentPlayTimeLabel.innerHTML = "00:00"; that.midiPlayer.stopPlay(); }, false); this.midiPlayer.defineCallbackOnPlay( that.playerCallBackOnPlay ); this.midiPlayer.defineCallbackOnEnd( that.playerCallBackOnEnd ); this.midiPlayer.defineCallbackOnScroll( that.playerCallBackOnScroll ); //DR.addAgent( this ); // register for translate this.defineInstrument(true); this.showAccordionName(); this.showAccordionImage(); this.accordionSelector.populate(false); this.accordion.printKeyboard( this.keyboardDiv ); this.loadOriginalRepertoire(); SITE.translator.translate(); this.resize(); }; SITE.Mapa.prototype.setup = function (tabParams) { if( this.accordion.accordionIsCurrent(tabParams.accordionId) ) { if( tabParams.songId ) { this.showTab('songsTab'); this.showABC('songs#'+tabParams.songId); } return; } if( tabParams.songId ) { this.songId = tabParams.songId; } this.midiPlayer.reset(); this.accordion.loadById(tabParams.accordionId); this.showAccordionName(); this.showAccordionImage(); this.accordionSelector.populate(false); SITE.translator.translate(this.menu.container); this.accordion.printKeyboard( this.keyboardDiv ); this.loadOriginalRepertoire(); this.resize(); if (!this.accordion.loaded.localResource) { // não salva informação para acordeão local FILEMANAGER.saveLocal('property.accordion', this.accordion.getId()); } }; SITE.Mapa.prototype.resize = function() { // redimensiona a tela partitura var winH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var s1 = document.getElementById( 'section1' ); var s2 = document.getElementById( 'section2' ); // -paddingTop 78 -margins 14 -shadow 2 var h = (winH - s1.clientHeight - (s2.clientHeight - this.tuneContainerDiv.clientHeight) -78 -14 -2 ); this.tuneContainerDiv.style.height = Math.max(h,200) +"px"; this.renderedTune.div.style.height = (Math.max(h,200)-5) +"px"; (this.renderedTune.ps) && this.renderedTune.ps.update(); this.renderedChord.div.style.height = (Math.max(h,200)-5) +"px"; (this.renderedChord.ps) && this.renderedChord.ps.update(); this.renderedPractice.div.style.height = (Math.max(h,200)-5) +"px"; (this.renderedPractice.ps) && this.renderedPractice.ps.update(); this.media.posiciona(); }; SITE.Mapa.prototype.menuCallback = function (ev) { switch(ev) { case 'LOADMAP': this.fileLoadMap.click(); break; case 'SAVEMAP': this.save(); break; case 'RESTOREREPERTOIRE': this.restauraRepertorio(); break; case 'LOADREPERTOIRE': this.fileLoadRepertoire.click(); break; case 'EXPORTREPERTOIRE': this.exportaRepertorio(); break; case 'PART2TAB': this.openPart2Tab(); break; case 'TAB2PART': this.openTab2Part(); break; case 'ABC2PART': this.openABC2Part(); break; case 'IDXREPERTOIRE': if(! this.repertoireWin ) { this.repertoireWin = new SITE.Repertorio(); } this.repertoireWin.geraIndex(this); break; case 'JUMPS': this.showHelp('HelpTitle', 'JUMPS', '/html/sinaisRepeticao.pt_BR.html', { width: '1024', height: '600' } ); break; case 'ABCX': this.showHelp('HelpTitle', 'ABCX', '/html/formatoABCX.pt_BR.html', { width: '1024', height: '600' } ); break; case 'ESTUDIO': this.showHelp('HelpTitle', 'ESTUDIO', '/html/estudioABCX.pt_BR.html', { width: '1024', height: '600' } ); break; case 'TABS': this.showHelp('HelpTitle', 'TABS', '/html/tablatura.pt_BR.html', { width: '1024', height: '600' } ); break; case 'TABSTRANSPORTADA': this.showHelp('HelpTitle', 'TABSTRANSPORTADA', '/html/tablaturaTransportada.pt_BR.html', { width: '1024', height: '600' } ); break; case 'MAPS': this.showHelp('HelpTitle', 'MAPS', '/html/mapas.pt_BR.html', { width: '1024', height: '600' } ); break; case 'TUTORIAL': this.showHelp('HelpTitle', 'TUTORIAL', '/html/tutoriais.pt_BR.html', { width: '1024', height: '600', print:false } ); break; case 'ABOUT': this.showHelp('AboutTitle', '', '/html/about.pt_BR.html', { width: '800', print:false } ); break; case 'GAITA_MINUANO_GC': case 'CONCERTINA_PORTUGUESA': case 'GAITA_HOHNER_CORONA_SERIES': case 'GAITA_HOHNER_CLUB_IIIM_BR': case 'GAITA_MINUANO_BC_TRANSPORTADA': default: // as gaitas conhecidas e outras carregadas sob demanda this.setup({accordionId:ev}); } }; SITE.Mapa.prototype.loadOriginalRepertoire = function () { if (this.accordion.loaded.localResource) return; var self = this; var loader = this.startLoader( "LoadRepertoire", this.tuneContainerDiv ); loader.start( function() { self.doLoadOriginalRepertoire(loader); }, '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); }; SITE.Mapa.prototype.doLoadOriginalRepertoire = function (loader) { this.renderedChord.title = FILEMANAGER.loadLocal('property.' + this.accordion.getId() + '.chords.title') || this.accordion.loaded.getFirstChord(); this.loadABCList(this.renderedChord.tab); this.renderedPractice.title = FILEMANAGER.loadLocal('property.' + this.accordion.getId() + '.practices.title') || this.accordion.loaded.getFirstPractice(); this.loadABCList(this.renderedPractice.tab); var title; if( this.songId ) { title = this.accordion.loaded.songs.ids[this.songId]; this.accordion.loaded.songs.details[title].hidden = false; // carrega mesmo invisivel delete this.songId; // load once } this.renderedTune.title = title || FILEMANAGER.loadLocal('property.' + this.accordion.getId() + '.songs.title') || this.accordion.loaded.getFirstSong(); this.loadABCList(this.renderedTune.tab); this.showTab('songsTab'); loader.stop(); if( this.loadByIdx ) { SITE.ga('send', 'event', 'Mapa5', 'index', this.getActiveTab().title); // SITE.myGtag( 'event', 'index', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'index', // event_label: this.getActiveTab().title, // event_value: 0, // nonInteraction: false // }); if(! this.repertoireWin ) { this.repertoireWin = new SITE.Repertorio(); } this.repertoireWin.geraIndex(this); delete this.loadByIdx; } }; SITE.Mapa.prototype.printPartiture = function (button, event) { var currentABC = this.getActiveTab(); event.preventDefault(); button.blur(); if( currentABC.div.innerHTML ) { SITE.ga('send', 'event', 'Mapa5', 'print', currentABC.title); // SITE.myGtag( 'event', 'print', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'print', // event_label: currentABC.title, // event_value: 0, // nonInteraction: false // }); this.printPreview(currentABC.div.innerHTML, ["#topBar","#mapaDiv"], currentABC.abc.formatting.landscape ); } }; SITE.Mapa.prototype.openMapa = function (newABCText) { var tab = this.getActiveTab(); this.menu.enableSubMenu('menuGaitas'); this.menu.enableSubMenu('menuRepertorio'); this.setVisible(true); this.accordion.printKeyboard( this.keyboardDiv ); this.resize(); if( newABCText !== undefined ) { if( newABCText === tab.text ) { return; } else { tab.text = newABCText; this.accordion.loaded.setSong(tab.title, tab.text ); this.renderTAB( tab ); } } }; SITE.Mapa.prototype.closeMapa = function () { this.media.pause(); this.midiPlayer.stopPlay(); this.setVisible(false); this.menu.disableSubMenu('menuGaitas'); this.menu.disableSubMenu('menuRepertorio'); }; SITE.Mapa.prototype.openPart2Tab = function () { if( ! this.part2tab ) { this.part2tab = new SITE.TabGen( this ,{ // interfaceParams tabGenDiv: 'tabGenDiv' ,controlDiv: 'p2tControlDiv-raw' ,saveBtn:'p2tSaveBtn' ,updateBtn:'p2tForceRefresh' ,openBtn: 'p2tOpenInGenerator' } ); } this.part2tab.setup(this.activeTab.text); }; SITE.Mapa.prototype.openABC2Part = function () { if( ! this.ABC2part ) { this.ABC2part = new SITE.PartEdit( this ,{ // interfaceParams partEditDiv: 'partEditDiv' ,controlDiv: 'a2pControlDiv-raw' ,showEditorBtn: 'a2pShowEditorBtn' ,showMapBtn: 'a2pShowMapBtn' ,updateBtn:'a2pForceRefresh' ,loadBtn:'a2pLoadBtn' ,saveBtn:'a2pSaveBtn' ,printBtn:'a2pPrintBtn' ,playBtn: "a2pPlayBtn" ,stopBtn: "a2pStopBtn" ,btShowMedia: 'a2pbuttonShowMedia' ,currentPlayTimeLabel: "a2pCurrentPlayTimeLabel" ,generate_tablature: 'accordion' ,accordion_options: { id: this.accordion.getId() ,accordionMaps: DIATONIC.map.accordionMaps ,translator: SITE.translator ,render_keyboard_opts:{ transpose:false ,mirror: false ,scale:0.8 ,draggable:true ,show:false ,label:false } } }); } this.ABC2part.setup({accordionId: this.accordion.getId()}); }; SITE.Mapa.prototype.openTab2Part = function () { if( ! this.tab2part ) { this.tab2part = new SITE.PartGen( this ,{ // interfaceParams partGenDiv: 'partGenDiv' ,controlDiv: 't2pControlDiv-raw' ,showMapBtn: 't2pShowMapBtn' //,printBtn:'t2pPrintBtn' ,showEditorBtn: 't2pShowEditorBtn' ,updateBtn:'t2pForceRefresh' ,loadBtn:'t2pLoadBtn' ,saveBtn:'t2pSaveBtn' ,editPartBtn:'t2pOpenInPartEditBtn' ,savePartBtn:'t2pSavePartBtn' ,gotoMeasureBtn: "t2pGotoMeasureBtn" ,playBtn: "t2pPlayBtn" ,stopBtn: "t2pStopBtn" ,currentPlayTimeLabel: "t2pCurrentPlayTimeLabel" ,btShowMedia: 't2pbuttonShowMedia' ,ckShowABC:'ckShowABC' ,ckConvertToClub:'ckConvertToClub' ,ckConvertFromClub:'ckConvertFromClub' ,generate_tablature: 'accordion' ,accordion_options: { id: this.accordion.getId() ,accordionMaps: DIATONIC.map.accordionMaps ,translator: SITE.translator ,render_keyboard_opts:{ transpose:false ,mirror: false ,scale:0.8 ,draggable:true ,show:false ,label:false } } }); } this.tab2part.setup({accordionId: this.accordion.getId()}); }; SITE.Mapa.prototype.openEstudio = function (button, event) { var self = this; var tab = self.getActiveTab(); if(event) { event.preventDefault(); button.blur(); } if( ! this.studio ) { this.studio = new SITE.Estudio( this ,{ // interfaceParams studioDiv: 'studioDiv' ,studioControlDiv: 'studioControlDiv' ,studioCanvasDiv: 'studioCanvasDiv' ,generate_tablature: 'accordion' ,showMapBtn: 'showMapBtn' ,showEditorBtn: 'showEditorBtn' ,showTextBtn: 'showTextBtn' ,printBtn:'printBtn' ,saveBtn:'saveBtn' ,forceRefresh:'forceRefresh' ,btShowMedia: 'buttonShowMedia2' ,accordion_options: { id: this.accordion.getId() ,accordionMaps: DIATONIC.map.accordionMaps ,translator: SITE.translator ,render_keyboard_opts:{ transpose:false ,mirror:false ,scale:0.8 ,draggable:true ,show:false ,label:false } } ,onchange: function( studio ) { studio.onChange(); } } , { // playerParams modeBtn: "modeBtn" , timerBtn: "timerBtn" , playBtn: "playBtn2" , stopBtn: "stopBtn2" , clearBtn: "clearBtn" , gotoMeasureBtn: "gotoMeasureBtn" , untilMeasureBtn: "untilMeasureBtn" , stepBtn: "stepBtn" , repeatBtn: "repeatBtn" , stepMeasureBtn: "stepMeasureBtn" , tempoSld: "tempoSld" , GClefBtn: "GClefBtn" , FClefBtn: "FClefBtn" , currentPlayTimeLabel: "currentPlayTimeLabel2" } ); } if( tab.text ) { SITE.ga('send', 'event', 'Mapa5', 'tools', tab.title); // SITE.myGtag( 'event', 'tools', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'tools', // event_label: tab.title, // event_value: 0, // nonInteraction: false // }); var loader = this.startLoader( "OpenEstudio" ); loader.start( function() { self.studio.setup( tab, self.accordion.getId() ); loader.stop(); }, '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); } }; SITE.Mapa.prototype.startPlay = function( type, value ) { var currentABC = this.getActiveTab(); this.ypos = this.tuneContainerDiv.scrollTop; this.lastStaffGroup = -1; if( this.midiPlayer.playing) { if (type === "normal" ) { this.playButton.title = SITE.translator.getResource("playBtn"); this.playButton.innerHTML = '<i class="ico-play"></i>'; this.midiPlayer.pausePlay(); } else { this.midiPlayer.pausePlay(true); } } else { this.accordion.clearKeyboard(); if(type==="normal") { if( this.midiPlayer.startPlay(currentABC.abc.midi) ) { SITE.ga('send', 'event', 'Mapa5', 'play', currentABC.title); // SITE.myGtag( 'event', 'play', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'play', // event_label: currentABC.title, // event_value: 0, // nonInteraction: false // }); this.playButton.title = SITE.translator.getResource("pause"); this.playButton.innerHTML = '<i class="ico-pause"></i>'; } } else { if( this.midiPlayer.startDidacticPlay(currentABC.abc.midi, type, value ) ) { SITE.ga('send', 'event', 'Mapa5', 'didactic-play', currentABC.title); // SITE.myGtag( 'event', 'didactic-play', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'didactic-play', // event_label: currentABC.title, // event_value: 0, // nonInteraction: false // }); } } } }; SITE.Mapa.prototype.setScrolling = function(player) { if( !this.activeTab || player.currAbsElem.staffGroup === this.lastStaffGroup ) return; this.lastStaffGroup = player.currAbsElem.staffGroup; var fixedTop = player.printer.staffgroups[0].top; var vp = this.activeTab.div.clientHeight - fixedTop; var top = player.printer.staffgroups[player.currAbsElem.staffGroup].top-12; var bottom = top + player.printer.staffgroups[player.currAbsElem.staffGroup].height; if( bottom > vp+this.ypos || this.ypos > top-fixedTop ) { this.ypos = top; this.activeTab.div.scrollTop = this.ypos; } }; SITE.Mapa.prototype.exportaRepertorio = function() { if ( FILEMANAGER.requiredFeaturesAvailable() ) { var accordion = this.accordion.loaded; var name = accordion.getId().toLowerCase() + ".repertorio.abcx"; var conteudo = ""; for( var title in accordion.songs.items) { conteudo += accordion.songs.items[title] + '\n\n'; } FILEMANAGER.download( name, conteudo ); } else { alert( SITE.translator.getResource("err_saving") ); } }; SITE.Mapa.prototype.save = function() { var accordion = this.accordion.loaded; var txtAccordion = '{\n'+ ' "id":'+JSON.stringify(accordion.id)+'\n'+ ' ,"menuOrder":'+JSON.stringify(accordion.menuOrder+100)+'\n'+ ' ,"model":'+JSON.stringify(accordion.model)+'\n'+ ' ,"tuning":'+JSON.stringify(accordion.tuning)+'\n'+ ' ,"buttons":'+JSON.stringify(accordion.buttons)+'\n'+ ' ,"pedal":'+JSON.stringify(accordion.keyboard.pedalInfo)+'\n'+ ' ,"keyboard":\n'+ ' {\n'+ ' "layout":'+JSON.stringify(accordion.keyboard.layout)+'\n'+ ' ,"keys":\n'+ ' {\n'+ ' "close":'+JSON.stringify(accordion.keyboard.keys.close)+'\n'+ ' ,"open":'+JSON.stringify(accordion.keyboard.keys.open)+'\n'+ ' }\n'+ ' ,"basses":\n'+ ' {\n'+ ' "close":'+JSON.stringify(accordion.keyboard.basses.close)+'\n'+ ' ,"open":'+JSON.stringify(accordion.keyboard.basses.open)+'\n'+ ' }\n'+ ' }\n'+ '}\n'; FILEMANAGER.download( accordion.getId().toLowerCase() + '.accordion', txtAccordion ); }; SITE.Mapa.prototype.loadMap = function(evt) { var that = this; evt.preventDefault(); FILEMANAGER.loadLocalFiles(evt, function() { var loader = that.startLoader( "LoadRepertoire", that.tuneContainerDiv ); loader.start( function() { that.doLoadMap(FILEMANAGER.files, loader ); } , '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); evt.target.value = ""; }); }; SITE.Mapa.prototype.doLoadMap = function( files, loader ) { var newAccordionJSON, newImage; var newTunes = "", newChords = "", newPractices = ""; for(var f = 0; f < files.length; f++ ){ if( files[f].type === 'image' ) { newImage = files[f].content; } else { switch(files[f].extension.toLowerCase()) { case 'accordion': newAccordionJSON = JSON.parse( files[f].content ); break; case 'abcx': case 'tunes': newTunes += files[f].content; break; case 'chords': newChords += files[f].content; break; case 'practices': newPractices += files[f].content; break; } } } if( newAccordionJSON === undefined ) { loader.stop(); console.log( 'O arquivo principal .accordion não foi encontrado!' ); return; } newAccordionJSON.image = newImage || 'images/accordion.default.gif'; if( ! this.accordion.accordionExists(newAccordionJSON.id) ) { DIATONIC.map.accordionMaps.push( new DIATONIC.map.AccordionMap( newAccordionJSON, true ) ); DIATONIC.map.sortAccordions(); } this.setup({accordionId:newAccordionJSON.id}); var accordion = this.accordion.loaded; if( newChords ) { var objRet = { items:{}, ids: {}, details:{}, sortedIndex: [] }; var tunebook = new ABCXJS.TuneBook(newChords); for (var t = 0; t < tunebook.tunes.length; t++) { var tune = tunebook.tunes[t]; var id = tune.id; var hidden = false; if( id.toLowerCase().charAt(0) === 'h' ) { id = id.substr(1); hidden = true; } objRet.ids[id] = tune.title; objRet.items[tune.title] = tune.abc; objRet.details[tune.title] = { composer: tune.composer, id: id, hidden: hidden }; objRet.sortedIndex.push( tune.title ); } accordion.chords = objRet; accordion.chords.sortedIndex.sort(); this.renderedChord.title = accordion.getFirstChord();; this.loadABCList(this.renderedChord.tab); } if( newPractices ) { var objRet = { items:{}, ids: {}, details:{}, sortedIndex: [] }; var tunebook = new ABCXJS.TuneBook(newPractices); for (var t = 0; t < tunebook.tunes.length; t++) { var tune = tunebook.tunes[t]; var id = tune.id; var hidden = false; if( id.toLowerCase().charAt(0) === 'h' ) { id = id.substr(1); hidden = true; } objRet.ids[id] = tune.title; objRet.items[tune.title] = tune.abc; objRet.details[tune.title] = { composer: tune.composer, id: id, hidden: hidden }; objRet.sortedIndex.push( tune.title ); } accordion.practices = objRet; accordion.practices.sortedIndex.sort(); this.renderedPractice.title = accordion.getFirstPractice(); this.loadABCList(this.renderedPractice.tab); } if( newTunes ) { var objRet = { items:{}, ids: {}, details:{}, sortedIndex: [] }; var tunebook = new ABCXJS.TuneBook(newTunes); for (var t = 0; t < tunebook.tunes.length; t++) { var tune = tunebook.tunes[t]; var id = tune.id; var hidden = false; if( id.toLowerCase().charAt(0) === 'h' ) { id = id.substr(1); hidden = true; } objRet.ids[id] = tune.title; objRet.items[tune.title] = tune.abc; objRet.details[tune.title] = { composer: tune.composer, id: id, hidden: hidden }; objRet.sortedIndex.push( tune.title ); } accordion.songs = objRet; accordion.songs.sortedIndex.sort(); this.renderedTune.title = accordion.getFirstSong(); this.loadABCList(this.renderedTune.tab); } this.showTab('songsTab'); loader.stop(); }; SITE.Mapa.prototype.restauraRepertorio = function() { var that = this; var accordion = that.accordion.loaded; if( accordion.localResource ) { // não é possível restaurar repertório para acordeão local; return; } accordion.songs = accordion.loadABCX( accordion.songPathList, function() { that.renderedTune.title = accordion.getFirstSong(); that.loadABCList(that.renderedTune.tab); that.showTab('songsTab'); }); }; SITE.Mapa.prototype.carregaRepertorioLocal = function(evt) { var that = this; FILEMANAGER.loadLocalFiles( evt, function() { that.doCarregaRepertorioLocal(FILEMANAGER.files); evt.target.value = ""; }); }; SITE.Mapa.prototype.doCarregaRepertorioLocal = function(files) { var first = false; var accordion = this.accordion.loaded; for (var s = 0; s < files.length; s++) { var tunebook = new ABCXJS.TuneBook(files[s].content); for (var t = 0; t < tunebook.tunes.length; t++) { if( ! accordion.songs.items[tunebook.tunes[t].title] ) { // adiciona novo index accordion.songs.sortedIndex.push(tunebook.tunes[t].title); } // add or replace content var id = tunebook.tunes[t].id; var hidden = false; if( id.toLowerCase().charAt(0) === 'h' ) { id = id.substr(1); // neste caso, mostra mesmo que marcado como hidden. hidden = false; } accordion.songs.items[tunebook.tunes[t].title] = tunebook.tunes[t].abc; accordion.songs.details[tunebook.tunes[t].title] = { composer: tunebook.tunes[t].composer, id: id, hidden: hidden }; accordion.songs.ids[id] = tunebook.tunes[t].title; if(! first ) { // marca a primeira das novas canções para ser selecionada this.renderedTune.title = tunebook.tunes[t].title; first = true; } SITE.ga('send', 'event', 'Mapa5', 'loadSong', tunebook.tunes[t].title); // SITE.myGtag( 'event', 'loadSong', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'loadSong', // event_label: tunebook.tunes[t].title, // event_value: 0, // nonInteraction: false // }); } } // reordena a lista accordion.songs.sortedIndex.sort(); this.loadABCList(this.renderedTune.tab); this.showTab('songsTab'); }; SITE.Mapa.prototype.showTab = function(tabString) { var tab = this.getActiveTab(); if( tab ) { tab.selector.style.display = 'none'; this.silencia(true); } tab = this.setActiveTab(tabString); tab.selector.style.display = 'block'; this.media.show(tab); }; SITE.Mapa.prototype.showABC = function(action) { var type, title, self = this; var tab = self.getActiveTab(); var a = action.split('#'); if( action.indexOf('#') >= 0 && parseInt(a[1]) > 0 ) { type = a[0]; title = this.accordion.loaded[type].ids[ a[1] ]; } else { waterbug.logError( 'ABCX not found!'); waterbug.show(); return; } if( tab.title !== title && tab.menu.selectItem( tab.ddmId, action ) ) { tab.title = title; tab.text = this.accordion.loaded.getAbcText( tab.tab, tab.title ); var cleanedTitle = title.replace(/\(.*\)/g,"").trim(); tab.menu.setSubMenuTitle( tab.ddmId, (cleanedTitle.length>43 ? cleanedTitle.substr(0,40) + "..." : cleanedTitle) ); if( !this.accordion.loaded.localResource) FILEMANAGER.saveLocal( 'property.'+this.accordion.getId()+'.'+type+'.title', tab.title ); var loader = this.startLoader( "TABLoader" + type, this.tuneContainerDiv ); loader.start( function() { self.midiPlayer.stopPlay(); self.renderTAB( tab ); self.media.show( tab ); self.tuneContainerDiv.scrollTop = 0; loader.stop(); }, '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); } else { console.log( 'Song title not found!'); } }; SITE.Mapa.prototype.loadABCList = function(type) { var tab, items; switch( type ) { case 'songs': tab = this.renderedTune; tab.ddmId = 'songsMenu'; items = this.accordion.loaded.songs; break; case 'practices': tab = this.renderedPractice; tab.ddmId = 'practicesMenu'; items = this.accordion.loaded.practices; break; case 'chords': tab = this.renderedChord; tab.ddmId = 'chordsMenu'; items = this.accordion.loaded.chords; break; }; tab.abc = tab.text = undefined; tab.div.innerHTML = ""; tab.menu = new DRAGGABLE.ui.DropdownMenu( tab.selector , {listener:this, method: 'showABC', translate:false } , [{title: '...', ddmId: tab.ddmId, itens: []}] ); var achou = false; for( var i = 0; i < items.sortedIndex.length; i++) { var title = items.sortedIndex[i]; var cleanedTitle = title.replace(/\(.*\)/g,"").trim(); var vid = 0; if( ! items.details[title] || isNaN(parseInt(items.details[title].id)) ) { waterbug.logError( 'Missing or incorrect ID (X:nnn) for "' + title +'"' ); waterbug.show(); } else { vid = items.details[title].id; } if(items.details[title].hidden){ continue; } var m = tab.menu.addItemSubMenu( tab.ddmId, cleanedTitle +'|'+type+'#'+vid); if(title === tab.title ) { achou = true; tab.menu.setSubMenuTitle( tab.ddmId, cleanedTitle ); tab.menu.selectItem(tab.ddmId, m); tab.text = this.accordion.loaded.getAbcText(type, title); } } if( !achou && items.sortedIndex.length > 0 ) { var title = items.sortedIndex[0]; var cleanedTitle = title.replace(/\(.*\)/g,"").trim(); tab.menu.setSubMenuTitle( tab.ddmId, cleanedTitle ); tab.menu.selectItem(tab.ddmId, type+'#'+items.details[title].id); tab.text = this.accordion.loaded.getAbcText(type, title); } this.setActiveTab(type+'Tab'); this.renderTAB( tab ); }; SITE.Mapa.prototype.renderTAB = function( tab ) { if (tab.title === undefined || tab.text === undefined ) { tab.text = undefined; tab.title = undefined; return; } this.abcParser.parse( tab.text, this.parserparams ); tab.abc = this.abcParser.getTune(); tab.text = this.abcParser.getStrTune(); if ( this.midiParser ) { this.midiParser.parse( tab.abc, this.accordion.loadedKeyboard ); } var paper = new SVG.Printer( tab.div ); tab.printer = new ABCXJS.write.Printer(paper, this.printerparams, this.accordion.loadedKeyboard ); //tab.printer.printTune( tab.abc, {color:'black', backgroundColor:'#ffd' } ); tab.printer.printTune( tab.abc ); tab.printer.addSelectListener(this); this.accordion.clearKeyboard(true); tab.div.scrollTop = 0; if( tab.ps ) tab.ps.update(); else tab.ps = new PerfectScrollbar( tab.div, { handlers: ['click-rail', 'drag-thumb', 'keyboard', 'wheel', 'touch'], wheelSpeed: 1, wheelPropagation: false, suppressScrollX: false, minScrollbarLength: 100, swipeEasing: true, scrollingThreshold: 500 }); }; SITE.Mapa.prototype.setActiveTab = function(tab) { document.getElementById(tab).checked = true; if( this.activeTab ) this.activeTab.selector.style.display = 'none'; switch(tab) { case 'songsTab': this.activeTab = this.renderedTune; break; case 'practicesTab': this.activeTab = this.renderedPractice; break; case 'chordsTab': this.activeTab = this.renderedChord; break; } return this.activeTab; }; SITE.Mapa.prototype.getActiveTab = function() { return this.activeTab; }; SITE.Mapa.prototype.setVisible = function ( visible ) { this.mapDiv.style.display = (visible? 'inline':'none'); }; SITE.Mapa.prototype.showAccordionImage = function() { this.gaitaImagePlaceHolder.innerHTML = '<img src="'+this.accordion.loaded.image +'" alt="'+this.accordion.getFullName() + ' ' + SITE.translator.getResource('keys') + '" style="height:200px; width:200px;" />'; }; SITE.Mapa.prototype.showAccordionName = function() { this.gaitaNamePlaceHolder.innerHTML = this.accordion.getFullName() + ' <span data-translate="keys">' + SITE.translator.getResource('keys') + '</span>'; }; SITE.Mapa.prototype.highlight = function(abcelem) { if(!this.midiPlayer.playing) { this.accordion.clearKeyboard(true); this.midiParser.setSelection(abcelem); } }; //// neste caso não precisa fazer nada pq o texto abcx está escondido //SITE.Mapa.prototype.unhighlight = function(abcelem) { //}; SITE.Mapa.prototype.startLoader = function(id, container, start, stop) { var loader = new window.widgets.Loader({ id: id ,bars: 0 ,radius: 0 ,lineWidth: 20 ,lineHeight: 70 ,timeout: 1 // maximum timeout in seconds. ,background: "rgba(0,0,0,0.5)" ,container: container? container: document.body ,onstart: start // call function once loader has started ,oncomplete: stop // call function once loader has started }); return loader; }; SITE.Mapa.prototype.defineInstrument = function(onlySet) { var instrument = SITE.properties.options.pianoSound ? "acoustic_grand_piano" : "accordion" ; var setInstrument = function () { var instrumentId = SITE.properties.options.pianoSound? 0: 21; // accordion MIDI.programChange( 0, instrumentId ); MIDI.programChange( 1, instrumentId ); MIDI.programChange( 2, instrumentId ); MIDI.programChange( 3, instrumentId ); MIDI.programChange( 4, instrumentId ); MIDI.programChange( 5, instrumentId ); }; if( onlySet ) { setInstrument(); return; } MIDI.widget = new sketch.ui.Timer({ size:180 //, container: document.getElementById('mapaDiv') , cor1:SITE.properties.colors.close, cor2: SITE.properties.colors.open}); MIDI.widget.setFormat( SITE.translator.getResource('loading')); MIDI.loadPlugin({ soundfontUrl: "./soundfont/" ,instruments: instrument ,onprogress: function( total, done, currentPercent ) { var percent = ((done*100)+currentPercent)/(total); MIDI.widget.setValue(Math.round(percent)); } ,callback: function() { setInstrument(); } }); }; SITE.Mapa.prototype.showSettings = function() { //window.waterbug && window.waterbug.show(); var width = 620; var winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var x = winW/2 - width/2; if(!this.settings) { this.settings = {}; this.settings.window = new DRAGGABLE.ui.Window( null , null , {title: 'PreferencesTitle', translator: SITE.translator, statusbar: false, top: "300px", left: x+"px", height:'480px', width: width+'px', zIndex: 50} , {listener: this, method: 'settingsCallback'} ); this.settings.window.topDiv.style.zIndex = 101; var cookieValue = document.cookie.match(/(;)?cookiebar=([^;]*);?/)[2]; var cookieSets = "" if (cookieValue ) { // CookieAllowed cookieSets = '&nbsp;<a href="#" onclick="document.cookie=\'cookiebar=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/\'; setupCookieBar(); return false;"><span data-translate="cookiePrefs" >'+SITE.translator.getResource('cookiePrefs')+'</span></a>' } this.settings.window.dataDiv.innerHTML= '\ <div class="menu-group">\ <table>\ <tr>\ <th colspan="2"><span data-translate="PrefsIdiom" >'+SITE.translator.getResource('PrefsIdiom')+'</span></th>\ <th><div id="settingsLanguageMenu" class="topMenu"></div></th>\ </tr>\ <tr style="display:none;">\ <th colspan="2"><br><span data-translate="PrefsTabFormat" >'+SITE.translator.getResource('PrefsTabFormat')+'</span></th>\ <th><br><div id="settingsTabMenu" class="topMenu"></div></th>\ </tr>\ <tr style="display:none;">\ <td> </td><td colspan="2"><input id="chkOnlyNumbers" type="checkbox">&nbsp;<span data-translate="PrefsPropsOnlyNumbers" >'+SITE.translator.getResource('PrefsPropsOnlyNumbers')+'</span></td>\ </tr>\ <tr>\ <th colspan="2"><br><span data-translate="PrefsColor" >'+SITE.translator.getResource('PrefsColor')+'</span></th><td></td>\ </tr>\ <tr>\ <td style="width:15px;"></td><td data-translate="PrefsColorHighlight" >' +SITE.translator.getResource('PrefsColorHighlight') +'</td><td><input id="corRealce" type="text" ><input id="chkTransparency" type="checkbox">&nbsp;<span data-translate="PrefsColorTransparency" >' +SITE.translator.getResource('PrefsColorTransparency')+'</span></td>\ </tr>\ <tr>\ <td></td><td data-translate="PrefsColorClosingBellows" >'+SITE.translator.getResource('PrefsColorClosingBellows')+'</td><td><input id="foleFechando" type="text" ></td>\ </tr>\ <tr>\ <td></td><td data-translate="PrefsColorOpeningBellows" >'+SITE.translator.getResource('PrefsColorOpeningBellows')+'</td><td><input id="foleAbrindo" type="text" ></td>\ </tr>\ <tr>\ <th colspan="2"><br><span data-translate="PrefsProps" >'+SITE.translator.getResource('PrefsProps')+'</span></th><td></td>\ </tr>\ <tr>\ <td> </td><td colspan="2"><input id="chkPiano" type="checkbox">&nbsp;<span data-translate="PrefsPropsCKPiano" >'+SITE.translator.getResource('PrefsPropsCKPiano')+'</span></td>\ </tr>\ <tr>\ <td> </td><td colspan="2"><input id="chkWarnings" type="checkbox">&nbsp;<span data-translate="PrefsPropsCKShowWarnings" >'+SITE.translator.getResource('PrefsPropsCKShowWarnings')+'</span></td>\ </tr>\ <tr>\ <td> </td><td colspan="2"><input id="chkAutoRefresh" type="checkbox">&nbsp;<span data-translate="PrefsPropsCKAutoRefresh" >'+SITE.translator.getResource('PrefsPropsCKAutoRefresh')+'</span></td>\ </tr>\ <tr><td></td><td colspan="2">'+ cookieSets +'</td></tr>\ </table>\ </div>\ <div id="pg" class="pushbutton-group" style="right: 0; bottom: 0;" >\ <div id="botao1"></div>\n\ <div id="botao2"></div>\n\ <div id="botao3"></div>\n\ </div>' ; this.settings.window.addPushButtons([ 'botao1|apply', 'botao2|reset|PrefsReset', 'botao3|cancel' ]); // var selector = new ABCXJS.edit.AccordionSelector( // 'sel2', 'settingsAcordeonsMenu', {listener: this, method: 'settingsCallback'} ); // // selector.populate(true, 'GAITA_HOHNER_CLUB_IIIM_BR'); this.settings.menu = new DRAGGABLE.ui.DropdownMenu( 'settingsLanguageMenu' , { listener:this, method: 'settingsCallback', translate: false } , [ {title: 'Idioma', ddmId: 'menuIdiomas', itens: [] } ] ); this.settings.tabMenu = new DRAGGABLE.ui.DropdownMenu( 'settingsTabMenu' , { listener:this, method:'settingsCallback', translate: true } , [{title: '...', ddmId: 'menuFormato', itens: [ '&#160;Modelo Alemão|0TAB', '&#160;Numérica 1 (se disponível)|1TAB', '&#160;Numérica 2 (se disponível)|2TAB' ]}] ); this.settings.tabFormat = SITE.properties.options.tabFormat; this.settings.tabMenu.setSubMenuTitle( 'menuFormato', this.settings.tabMenu.selectItem( 'menuFormato', this.settings.tabFormat.toString()+"TAB" )); this.picker = new DRAGGABLE.ui.ColorPicker(['corRealce', 'foleFechando', 'foleAbrindo'], {translator: SITE.translator}); SITE.translator.menuPopulate(this.settings.menu, 'menuIdiomas'); this.settings.lang = SITE.properties.options.language; this.settings.useTransparency = document.getElementById( 'chkTransparency'); this.settings.corRealce = document.getElementById( 'corRealce'); this.settings.closeColor = document.getElementById( 'foleFechando'); this.settings.openColor = document.getElementById( 'foleAbrindo'); this.settings.showWarnings = document.getElementById( 'chkWarnings'); this.settings.autoRefresh = document.getElementById( 'chkAutoRefresh'); this.settings.pianoSound = document.getElementById( 'chkPiano'); this.settings.chkOnlyNumbers = document.getElementById( 'chkOnlyNumbers'); } this.settings.corRealce.style.backgroundColor = this.settings.corRealce.value = SITE.properties.colors.highLight; this.settings.closeColor.style.backgroundColor = this.settings.closeColor.value = SITE.properties.colors.close; this.settings.openColor.style.backgroundColor = this.settings.openColor.value = SITE.properties.colors.open ; this.settings.chkOnlyNumbers.checked = SITE.properties.options.tabShowOnlyNumbers; this.settings.showWarnings.checked = SITE.properties.options.showWarnings; this.settings.autoRefresh.checked = SITE.properties.options.autoRefresh; this.settings.pianoSound.checked = SITE.properties.options.pianoSound; this.settings.useTransparency.checked = SITE.properties.colors.useTransparency; this.settings.window.setVisible(true); }; SITE.Mapa.prototype.settingsCallback = function (action, elem) { switch (action) { case '0TAB': case '1TAB': case '2TAB': this.settings.tabFormat = action; this.settings.tabMenu.setSubMenuTitle( 'menuFormato', this.settings.tabMenu.selectItem( 'menuFormato', action )); break; case 'de_DE': case 'en_US': case 'es_ES': case 'fr_FR': case 'it_IT': case 'pt_BR': this.settings.lang = action; this.settings.menu.setSubMenuTitle( 'menuIdiomas', this.settings.menu.selectItem( 'menuIdiomas', action )); break; case 'MOVE': break; case 'CLOSE': case 'CANCEL': this.picker.close(); this.settings.window.setVisible(false); break; case 'APPLY': SITE.properties.colors.highLight = this.settings.corRealce.value; SITE.properties.colors.close = this.settings.closeColor.value; SITE.properties.colors.open = this.settings.openColor.value; SITE.properties.options.showWarnings = this.settings.showWarnings.checked; SITE.properties.options.autoRefresh = this.settings.autoRefresh.checked; SITE.properties.colors.useTransparency = this.settings.useTransparency.checked; this.picker.close(); this.settings.window.setVisible(false); this.applySettings(); SITE.SaveProperties(); break; case 'RESET': this.alert = new DRAGGABLE.ui.Alert( this.settings.window, action, '<br>'+SITE.translator.getResource('resetMsgTitle'), '<br>'+SITE.translator.getResource('resetMsgDescription'), {translator: SITE.translator} ); break; case 'RESET-YES': this.alert.close(); this.picker.close(); this.settings.window.setVisible(false); SITE.ResetProperties(); SITE.ga('send', 'event', 'Configuration', 'reset', SITE.properties.version ); this.applySettings(); break; case 'RESET-NO': case 'RESET-CANCEL': this.alert.close(); break; } }; SITE.Mapa.prototype.applySettings = function() { if( parseInt(this.settings.tabFormat) !== SITE.properties.options.tabFormat || this.settings.chkOnlyNumbers.checked !== SITE.properties.options.tabShowOnlyNumbers ) { SITE.properties.options.tabShowOnlyNumbers= this.settings.chkOnlyNumbers.checked; SITE.properties.options.tabFormat = parseInt(this.settings.tabFormat); this.accordion.setFormatoTab(SITE.properties.options.tabFormat,!SITE.properties.options.tabShowOnlyNumbers) this.accordion.loadedKeyboard.reprint(); this.renderTAB( this.getActiveTab() ); if (this.studio) { this.studio.accordion.setFormatoTab(SITE.properties.options.tabFormat,!SITE.properties.options.tabShowOnlyNumbers) this.studio.accordion.loadedKeyboard.reprint(); this.studio.renderedTune.printer.printTune( this.studio.renderedTune.abc ); } if (this.tab2part) { this.tab2part.accordion.setFormatoTab(SITE.properties.options.tabFormat,!SITE.properties.options.tabShowOnlyNumbers) this.tab2part.renderedTune.printer.printABC(this.renderedTune.abc); } if (this.ABC2part) { this.ABC2part.accordion.setFormatoTab(SITE.properties.options.tabFormat,!SITE.properties.options.tabShowOnlyNumbers) this.ABC2part.renderedTune.printer.printABC(this.renderedTune.abc); } //tratar também outros locais onde hajam teclado (tab editor, part editor) } if( this.settings.lang !== SITE.properties.options.language ) { SITE.properties.options.language = this.settings.lang; SITE.ga('send', 'event', 'Configuration', 'changeLang', SITE.properties.options.language); SITE.translator.loadLanguage( this.settings.lang, function () { SITE.translator.translate(); } ); } if( this.settings.pianoSound.checked !== SITE.properties.options.pianoSound ) { SITE.properties.options.pianoSound = this.settings.pianoSound.checked; SITE.ga('send', 'event', 'Configuration', 'changeInstrument', SITE.properties.options.pianoSound?'piano':'accordion'); this.defineInstrument(); } this.media.show(this.getActiveTab()); if (this.studio) { this.studio.setAutoRefresh(SITE.properties.options.autoRefresh); this.studio.warningsDiv.style.display = SITE.properties.options.showWarnings ? 'block' : 'none'; } if (this.part2tab) { this.part2tab.warningsDiv.style.display = SITE.properties.options.showWarnings ? 'block' : 'none'; } if (this.tab2part) { this.tab2part.warningsDiv.style.display = SITE.properties.options.showWarnings ? 'block' : 'none'; } if (this.ABC2part) { this.ABC2part.warningsDiv.style.display = SITE.properties.options.showWarnings ? 'block' : 'none'; } this.resizeActiveWindow(); ABCXJS.write.color.useTransparency = SITE.properties.colors.useTransparency; ABCXJS.write.color.highLight = SITE.properties.colors.highLight; DIATONIC.map.color.close = SITE.properties.colors.close; DIATONIC.map.color.open = SITE.properties.colors.open; this.accordion.loadedKeyboard.legenda.setOpen(); this.accordion.loadedKeyboard.legenda.setClose(); }; SITE.Mapa.prototype.changePageOrientation = function (orientation) { var style = document.createElement('style'); document.head.appendChild(style); style.innerHTML = '@page {margin: 1cm; size: ' + orientation + '}'; }; SITE.Mapa.prototype.printPreview = function (html, divsToHide, landscape ) { var dv = document.getElementById('printPreviewDiv'); var savedDisplays = {}; divsToHide.forEach( function( div ) { var hd = document.getElementById(div.substring(1)); savedDisplays[div.substring(1)] = hd.style.display; hd.style.display = "none"; }); this.changePageOrientation(landscape? 'landscape': 'portrait'); dv.innerHTML = html; dv.style.display = 'block'; setTimeout( function () { window.print(); dv.style.display = 'none'; divsToHide.forEach( function( div ) { var hd = document.getElementById(div.substring(1)); hd.style.display = savedDisplays[div.substring(1)]; }); }); }; SITE.Mapa.prototype.resizeActiveWindow = function() { if(this.studio && window.getComputedStyle(this.studio.Div.parent).display !== 'none') { this.studio.resize(); } else if(this.tab2part && window.getComputedStyle(this.tab2part.Div.parent).display !== 'none') { this.tab2part.resize(); } else if(this.ABC2part && window.getComputedStyle(this.ABC2part.Div.parent).display !== 'none') { this.ABC2part.resize(); } else if(this.part2tab && window.getComputedStyle(this.part2tab.Div.parent).display !== 'none') { this.part2tab.resize(); } else { this.resize(); } }; SITE.Mapa.prototype.silencia = function(force) { if(this.studio && window.getComputedStyle(this.studio.Div.parent).display !== 'none') { if( this.studio.midiPlayer.playing) { if(force ) this.studio.midiPlayer.stopPlay(); else this.studio.startPlay('normal'); // pause } } else if(this.tab2part && window.getComputedStyle(this.tab2part.Div.parent).display !== 'none') { if( this.tab2part.midiPlayer.playing) { if(force ) this.tab2part.midiPlayer.stopPlay(); else this.tab2part.startPlay('normal'); // pause } } else { if( this.midiPlayer.playing) { if(force ) this.midiPlayer.stopPlay(); else this.startPlay('normal'); // pause } } }; SITE.Mapa.prototype.setFocus = function() { if(this.studio && window.getComputedStyle(this.studio.Div.parent).display !== 'none') { this.studio.editorWindow.aceEditor.focus(); } else if(this.tab2part && window.getComputedStyle(this.tab2part.Div.parent).display !== 'none') { this.tab2part.editorWindow.aceEditor.focus(); } else if(this.ABC2part && window.getComputedStyle(this.ABC2part.Div.parent).display !== 'none') { this.ABC2part.editorWindow.aceEditor.focus(); } else { } } SITE.Mapa.prototype.showHelp = function ( title, subTitle, url, options ) { var that = this; options = options || {}; options.width = typeof options.width === 'undefined'? '800' : options.width; options.height = typeof options.height === 'undefined'? undefined : options.height; options.print = typeof options.print === 'undefined'? true : options.print; var winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var x = winW/2 - options.width/2; if( ! this.helpWindow ) { this.helpWindow = new DRAGGABLE.ui.Window( null , ['print|printBtn'] , {title: '', translator: SITE.translator, draggable: true, statusbar: false, top: "200px", left: x+"px", height:"auto", zIndex: 70} , { listener: this, method:'helpCallback' } ); this.helpWindow.dataDiv.style.height = "auto"; } this.helpWindow.setTitle(title, SITE.translator); this.helpWindow.setSubTitle(subTitle, SITE.translator); this.helpWindow.setButtonVisible('PRINT', options.print ); this.helpWindow.dataDiv.innerHTML = '<object data="'+url+'" type="text/html" ></object>'; this.iframe = this.helpWindow.dataDiv.getElementsByTagName("object")[0]; var loader = this.startLoader( "About" ); this.iframe.style.width = options.width+"px"; this.iframe.style.height = (options.height?options.height:400)+"px"; that.helpWindow.topDiv.style.opacity = "0"; that.helpWindow.setVisible(true); loader.start( function() { if( options.height ) { that.iframe.addEventListener("load", function () { that.helpWindow.topDiv.style.opacity = "1"; that.iframe.style.height = options.height+"px"; var header = this.contentDocument.getElementById('helpHeader'); var frm = this.contentDocument.getElementById('helpFrame'); var container = this.contentDocument.getElementById('helpContainer'); if( header ) header.style.display = 'none'; if( frm ) frm.style.overflow = 'hidden'; if( container ) { container.style.top = '0'; container.style.height = (options.height-18)+"px";; container.style.overflow = 'hidden'; container.style.border = '1px solid rgba(255, 153, 34, 0.2)'; var v = new PerfectScrollbar( container, { handlers: ['click-rail', 'drag-thumb', 'keyboard', 'wheel', 'touch'], wheelSpeed: 1, wheelPropagation: false, suppressScrollX: false, minScrollbarLength: 100, swipeEasing: true, scrollingThreshold: 500 }); } loader.stop(); }); } else { // auto determina a altura that.iframe.addEventListener("load", function () { this.contentDocument.body.style.overflow ="hidden"; var info = this.contentDocument.getElementById('siteVerI'); if( info ) info.innerHTML=SITE.siteVersion; that.iframe.style.height = this.contentDocument.body.clientHeight+"px"; that.helpWindow.topDiv.style.opacity = "1"; that.helpWindow.dataDiv.style.overflow = "hidden"; loader.stop(); }); } }, '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); }; SITE.Mapa.prototype.helpCallback = function ( action ) { if( action === 'CLOSE' ) { this.helpWindow.setVisible(false); } else if( action === 'PRINT' ) { var container = this.iframe.contentDocument.getElementById('helpContainer'); if( container ) { //var t = container.style.top; //container.style.top = '0'; this.printPreview( container.innerHTML, [ "#"+this.helpWindow.topDiv.id, "#topBar","#mapaDiv"], false ); //var header = this.iframe.contentDocument.getElementById('helpHeader'); //if( header ) header.style.display = 'none'; //container.style.top = t; } } // console.log( action ); }; if (!window.SITE) window.SITE = {}; SITE.Estudio = function (mapa, interfaceParams, playerParams) { this.mapa = mapa; this.ypos = 0; // controle de scrollf this.lastStaffGroup = -1; // controle de scroll this.lastYpos = 0; // controle de scroll var that = this; var canvas_id = 'canvasDiv'; var warnings_id = 'warningsDiv'; this.warnings = []; this.renderedTune = {text:undefined, abc:undefined, title:undefined ,tab: undefined, div: undefined ,selector: undefined }; this.Div = new DRAGGABLE.ui.Window( interfaceParams.studioDiv , null , {translator: SITE.translator, statusbar: false, draggable: false, top: "3px", left: "1px", width: '100%', height: "100%", title: 'EstudioTitle'} , {listener: this, method: 'studioCallback'} ); this.Div.setVisible(true); this.Div.dataDiv.style.overflow = 'hidden'; if (interfaceParams.generate_tablature) { if (interfaceParams.generate_tablature === 'accordion') { this.accordion = new window.ABCXJS.tablature.Accordion( interfaceParams.accordion_options , SITE.properties.options.tabFormat ,!SITE.properties.options.tabShowOnlyNumbers ); if (interfaceParams.accordionNameSpan) { this.accordionNameSpan = document.getElementById(interfaceParams.accordionNameSpan); this.accordionNameSpan.innerHTML = this.accordion.getFullName(); } } else { throw new Error('Tablatura para ' + interfaceParams.generate_tablature + ' não suportada!'); } } this.editorWindow = new ABCXJS.edit.EditArea( this.Div.dataDiv ,{listener : this, method: 'editorCallback' } ,{ draggable:SITE.properties.studio.editor.floating ,toolbar: true, statusbar:true, translator: SITE.translator ,title: 'EstudioEditorTitle' ,compileOnChange: SITE.properties.options.autoRefresh } ); this.editorWindow.setVisible(false); this.controlDiv = document.createElement("DIV"); this.controlDiv.setAttribute("id", 'controlDiv' ); this.controlDiv.setAttribute("class", 'controlDiv btn-group' ); this.Div.dataDiv.appendChild(this.controlDiv); this.controlDiv.innerHTML = document.getElementById(interfaceParams.studioControlDiv).innerHTML; document.getElementById(interfaceParams.studioControlDiv).innerHTML = ""; this.media = new SITE.Media( this.Div.dataDiv, interfaceParams.btShowMedia, SITE.properties.studio.media ); this.keyboardWindow = new DRAGGABLE.ui.Window( this.Div.dataDiv ,[ 'move', 'rotate', 'zoom', 'globe'] ,{title: '', translator: SITE.translator, statusbar: false , top: SITE.properties.studio.keyboard.top , left: SITE.properties.studio.keyboard.left } ,{listener: this, method: 'keyboardCallback'} ); this.accordion.setRenderOptions({ draggable: true ,show: SITE.properties.studio.keyboard.visible ,transpose: SITE.properties.studio.keyboard.transpose ,mirror: SITE.properties.studio.keyboard.mirror ,scale: SITE.properties.studio.keyboard.scale ,label: SITE.properties.studio.keyboard.label }); this.warningsDiv = document.createElement("DIV"); this.warningsDiv.setAttribute("id", warnings_id); this.warningsDiv.setAttribute("class", "warningsDiv" ); this.Div.dataDiv.appendChild(this.warningsDiv); this.studioCanvasDiv = document.createElement("DIV"); this.studioCanvasDiv.setAttribute("id", interfaceParams.studioCanvasDiv ); this.studioCanvasDiv.setAttribute("class", "studioCanvasDiv" ); this.canvasDiv = document.createElement("DIV"); this.canvasDiv.setAttribute("id", canvas_id); this.canvasDiv.setAttribute("class", "canvasDiv" ); this.studioCanvasDiv.appendChild(this.canvasDiv); this.renderedTune.div = this.canvasDiv; this.Div.dataDiv.appendChild(this.studioCanvasDiv); if(this.ps) this.ps.destroy(); this.ps = new PerfectScrollbar( this.studioCanvasDiv, { handlers: ['click-rail', 'drag-thumb', 'keyboard', 'wheel', 'touch'], wheelSpeed: 1, wheelPropagation: false, suppressScrollX: false, minScrollbarLength: 100, swipeEasing: true, scrollingThreshold: 500 }); if( interfaceParams.onchange ) { this.onchangeCallback = interfaceParams.onchange; } this.saveButton = document.getElementById(interfaceParams.saveBtn); this.forceRefreshButton = document.getElementById(interfaceParams.forceRefresh); this.printButton = document.getElementById(interfaceParams.printBtn); this.showMapButton = document.getElementById(interfaceParams.showMapBtn); this.showEditorButton = document.getElementById(interfaceParams.showEditorBtn); // player control this.modeButton = document.getElementById(playerParams.modeBtn); this.timerButton = document.getElementById(playerParams.timerBtn); this.FClefButton = document.getElementById(playerParams.FClefBtn); this.GClefButton = document.getElementById(playerParams.GClefBtn); this.playButton = document.getElementById(playerParams.playBtn); this.stopButton = document.getElementById(playerParams.stopBtn); this.gotoMeasureButton = document.getElementById(playerParams.gotoMeasureBtn); this.untilMeasureButton = document.getElementById(playerParams.untilMeasureBtn); this.currentPlayTimeLabel = document.getElementById(playerParams.currentPlayTimeLabel); this.stepButton = document.getElementById(playerParams.stepBtn); this.stepMeasureButton = document.getElementById(playerParams.stepMeasureBtn); this.repeatButton = document.getElementById(playerParams.repeatBtn); this.clearButton = document.getElementById(playerParams.clearBtn); this.tempoButton = document.getElementById(playerParams.tempoSld); this.showMapButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.showKeyboard(); }, false); this.showEditorButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.showEditor(); }, false); this.forceRefreshButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.fireChanged(0, {force:true, showProgress:true } ); }, false); this.saveButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.salvaMusica(); }, false); this.printButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); SITE.ga('send', 'event', 'Mapa5', 'print', that.renderedTune.title); that.mapa.printPreview(that.renderedTune.div.innerHTML, ["#topBar","#studioDiv"], that.renderedTune.abc.formatting.landscape); return; }, false); this.modeButton.addEventListener('click', function (evt) { evt.preventDefault(); this.blur(); that.changePlayMode(); }, false); this.timerButton.addEventListener('click', function (evt) { evt.preventDefault(); this.blur(); SITE.properties.studio.timerOn = ! SITE.properties.studio.timerOn; that.setTimerIcon( 0 ); }, false); this.FClefButton.addEventListener('click', function (evt) { evt.preventDefault(); this.blur(); SITE.properties.studio.bassOn = ! SITE.properties.studio.bassOn; that.setBassIcon(); }, false); this.GClefButton.addEventListener('click', function (evt) { evt.preventDefault(); this.blur(); SITE.properties.studio.trebleOn = ! SITE.properties.studio.trebleOn; that.setTrebleIcon(); }, false); this.playButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); window.setTimeout(function(){ that.startPlay( 'normal' );}, 0 ); }, false); this.stopButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.blockEdition(false); if(that.currentPlayTimeLabel) that.currentPlayTimeLabel.innerHTML = "00:00"; that.studioStopPlay(); }, false); this.clearButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.renderedTune.printer.clearSelection(); that.accordion.clearKeyboard(true); that.currentPlayTimeLabel.innerHTML = "00:00"; that.blockEdition(false); that.studioStopPlay(); }, false); this.stepButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.startPlay('note'); }, false); this.stepMeasureButton.addEventListener("click", function (evt) { evt.preventDefault(); that.startPlay('measure'); }, false); this.repeatButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); if(!that.midiPlayer.playing) that.startPlay('repeat', that.gotoMeasureButton.value, that.untilMeasureButton.value ); }, false); this.slider = new DRAGGABLE.ui.Slider( this.tempoButton, { min: 25, max: 200, start:100, step:25, speed:100, color: 'white', bgcolor:'red', size:{w:150, h:23, tw:48}, callback: function(v) { that.midiPlayer.setAndamento(v); } } ); this.gotoMeasureButton.addEventListener("keypress", function (evt) { if (evt.keyCode === 13) { that.startPlay('goto', this.value, that.untilMeasureButton.value); } }, false); this.gotoMeasureButton.addEventListener("focus", function (evt) { if (this.value === SITE.translator.getResource("gotoMeasure").val) { this.value = ""; } }, false); this.gotoMeasureButton.addEventListener("blur", function (evt) { if (this.value === "") { this.value = SITE.translator.getResource("gotoMeasure").val; } }, false); this.untilMeasureButton.addEventListener("keypress", function (evt) { if (evt.keyCode === 13) { that.startPlay('goto', that.gotoMeasureButton.value, this.value); } }, false); this.untilMeasureButton.addEventListener("focus", function (evt) { if (this.value === SITE.translator.getResource("untilMeasure").val) { this.value = ""; } }, false); this.untilMeasureButton.addEventListener("blur", function (evt) { if (this.value === "") { this.value = SITE.translator.getResource("untilMeasure").val; } }, false); this.playerCallBackOnScroll = function( player ) { that.setScrolling(player); }; this.playerCallBackOnPlay = function( player ) { var strTime = player.getTime().cTime; if(that.gotoMeasureButton && ! parseInt(that.untilMeasureButton.value)) that.gotoMeasureButton.value = player.currentMeasure; if(that.currentPlayTimeLabel) that.currentPlayTimeLabel.innerHTML = strTime; that.midiPlayer.setPlayableClefs( (SITE.properties.studio.trebleOn?"T":"")+(SITE.properties.studio.bassOn?"B":"") ); }; this.playerCallBackOnEnd = function( player ) { var warns = that.midiPlayer.getWarnings(); that.playButton.title = SITE.translator.getResource("playBtn"); that.playButton.innerHTML = '&#160;<i class="ico-play"></i>&#160;'; that.renderedTune.printer.clearSelection(); that.accordion.clearKeyboard(true); that.blockEdition(false); if( warns ) { var wd = document.getElementById("warningsDiv"); var txt = ""; warns.forEach(function(msg){ txt += msg + '<br/>'; }); wd.style.color = 'blue'; wd.innerHTML = txt; } }; this.midiParser = new ABCXJS.midi.Parse(); this.midiPlayer = new ABCXJS.midi.Player(this); this.midiPlayer.defineCallbackOnPlay( this.playerCallBackOnPlay ); this.midiPlayer.defineCallbackOnEnd( this.playerCallBackOnEnd ); this.midiPlayer.defineCallbackOnScroll( this.playerCallBackOnScroll ); }; SITE.Estudio.prototype.setup = function( tab, accordionId) { if(this.mapa) this.mapa.closeMapa(); this.accordion.loadById(accordionId); this.renderedTune.abc = tab.abc; this.renderedTune.text = tab.text; this.renderedTune.title = tab.title; this.changePlayMode(SITE.properties.studio.mode); this.setBassIcon(); this.setTrebleIcon(); this.setTimerIcon( 0 ); this.setVisible(true); this.setString(tab.text); this.fireChanged(0, {force:true} ); this.Div.setSubTitle( '- ' + this.accordion.getTxtModel() ); this.studioCanvasDiv.scrollTop = 0; this.warningsDiv.style.display = SITE.properties.options.showWarnings? 'block':'none'; this.showEditor(SITE.properties.studio.editor.visible); this.editorWindow.container.setSubTitle( '- ' + tab.title ); this.editorWindow.restartUndoManager(); if(SITE.properties.studio.editor.floating) { if( SITE.properties.studio.editor.maximized ) { this.editorWindow.setFloating(true); this.editorWindow.container.dispatchAction('MAXIMIZE'); } else { this.editorWindow.container.dispatchAction('POPOUT'); } } else { this.editorWindow.container.dispatchAction('POPIN'); } this.showKeyboard(SITE.properties.studio.keyboard.visible); this.keyboardWindow.setTitle(this.accordion.getTxtTuning() + ' - ' + this.accordion.getTxtNumButtons() ); SITE.translator.translate( this.Div.topDiv ); }; SITE.Estudio.prototype.resize = function( ) { // redimensiona a workspace var winH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // -paddingTop 78 var h = (winH -78 - 10 ); var w = (winW - 8 ); this.Div.topDiv.style.left = "3px"; this.Div.topDiv.style.top = "82px"; this.Div.topDiv.style.height = Math.max(h,200) +"px"; this.Div.topDiv.style.width = Math.max(w,400) +"px"; var w = 0, e = 0; var c = this.controlDiv.clientHeight; var t = this.Div.dataDiv.clientHeight; if(! SITE.properties.showWarnings) { w = this.warningsDiv.clientHeight; } if(! SITE.properties.studio.editor.floating) { e = this.editorWindow.container.topDiv.clientHeight+4; } this.studioCanvasDiv.style.height = t-(w+e+c+6) +"px"; this.posicionaTeclado(); this.editorWindow.resize(); (this.ps) && this.ps.update(); }; SITE.Estudio.prototype.showKeyboard = function(show) { SITE.properties.studio.keyboard.visible = (typeof show === 'undefined'? ! SITE.properties.studio.keyboard.visible : show ); this.accordion.render_opts.show = SITE.properties.studio.keyboard.visible; if(SITE.properties.studio.keyboard.visible) { this.keyboardWindow.setVisible(true); this.accordion.printKeyboard(this.keyboardWindow.dataDiv); document.getElementById('I_showMap').setAttribute('class', 'ico-folder-open' ); this.posicionaTeclado(); } else { this.accordion.render_opts.show = false; this.keyboardWindow.setVisible(false); document.getElementById('I_showMap').setAttribute('class', 'ico-folder' ); } }; SITE.Estudio.prototype.showEditor = function(show) { SITE.properties.studio.editor.visible = (typeof show === 'undefined'? ! SITE.properties.studio.editor.visible : show ); if(SITE.properties.studio.editor.visible) { this.editorWindow.setVisible(true); this.editorWindow.resize(); document.getElementById('I_showEditor').setAttribute('class', 'ico-folder-open' ); } else { document.getElementById('I_showEditor').setAttribute('class', 'ico-folder' ); this.editorWindow.setVisible(false); } this.resize(); }; SITE.Estudio.prototype.editorCallback = function (action, elem) { switch(action) { case '0': break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '10': case '11': case '-1': case '-2': case '-3': case '-4': case '-5': case '-6': case '-7': case '-8': case '-9': case '-10': case '-11': this.fireChanged( parseInt(action), {force:true} ); break; case 'OCTAVEUP': this.fireChanged(12, {force:true} ); break; case 'OCTAVEDOWN': this.fireChanged(-12, {force:true} ); break; case 'REFRESH': this.fireChanged(0, {force:true} ); break; case 'DOWNLOAD': this.salvaMusica(); break; case 'MAXIMIZE': this.editorWindow.maximizeWindow( true, SITE.properties.studio.editor ); break; case 'RESTORE': this.editorWindow.maximizeWindow( false, SITE.properties.studio.editor ); break; case 'POPIN': this.editorWindow.dockWindow(true, SITE.properties.studio.editor, 0, 0, "calc(100% - 5px)", "200px" ); this.resize(); break; case 'POPOUT': this.editorWindow.dockWindow(false, SITE.properties.studio.editor ); this.resize(); break; case 'RESIZE': case 'MOVE': this.editorWindow.retrieveProps( SITE.properties.studio.editor ); break; case 'CLOSE': this.showEditor(false); break; } }; SITE.Estudio.prototype.studioCallback = function( e ) { switch(e) { case 'CLOSE': this.closeEstudio(true); break; } }; SITE.Estudio.prototype.studioStopPlay = function( e ) { this.midiPlayer.stopPlay(); }; SITE.Estudio.prototype.closeEstudio = function(save) { var self = this; if(!this.mapa){ self.setVisible(false); self.studioStopPlay(); } else { var loader = this.mapa.startLoader( "CloseStudio" ); loader.start( function() { (save) && SITE.SaveProperties(); self.setVisible(false); self.studioStopPlay(); self.mapa.openMapa( self.getString() ); loader.stop(); }, '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); } }; SITE.Estudio.prototype.setVisible = function( visible ) { this.Div.parent.style.display = visible?'block':'none'; }; SITE.Estudio.prototype.setAutoRefresh = function( value ) { this.editorWindow.setCompileOnChange(value); }; SITE.Estudio.prototype.getString = function() { return this.editorWindow.getString(); }; SITE.Estudio.prototype.setString = function(str) { this.editorWindow.setString(str); }; SITE.Estudio.prototype.keyboardCallback = function( e ) { switch(e) { case 'MOVE': var k = this.keyboardWindow.topDiv.style; SITE.properties.studio.keyboard.left = k.left; SITE.properties.studio.keyboard.top = k.top; break; case 'ROTATE': this.accordion.rotateKeyboard(this.keyboardWindow.dataDiv); SITE.properties.studio.keyboard.transpose = this.accordion.render_opts.transpose; SITE.properties.studio.keyboard.mirror = this.accordion.render_opts.mirror; break; case 'ZOOM': this.accordion.scaleKeyboard(this.keyboardWindow.dataDiv); SITE.properties.studio.keyboard.scale = this.accordion.render_opts.scale; break; case 'GLOBE': this.accordion.changeNotation(); SITE.properties.studio.keyboard.label = this.accordion.render_opts.label; break; case 'CLOSE': this.showKeyboard(false); break; } }; SITE.Estudio.prototype.setScrolling = function(player) { if( !this.studioCanvasDiv || !player.currAbsElem || player.currAbsElem.staffGroup === this.lastStaffGroup ) return; this.lastStaffGroup = player.currAbsElem.staffGroup; var fixedTop = player.printer.staffgroups[0].top; var vp = this.studioCanvasDiv.clientHeight - fixedTop; var top = player.printer.staffgroups[player.currAbsElem.staffGroup].top-12; var bottom = top + player.printer.staffgroups[player.currAbsElem.staffGroup].height; if( bottom > vp+this.ypos || this.ypos > top-fixedTop ) { this.ypos = top; this.studioCanvasDiv.scrollTop = this.ypos; } }; SITE.Estudio.prototype.salvaMusica = function () { if (FILEMANAGER.requiredFeaturesAvailable()) { this.fireChanged(0, {force:false, showProgress:true } ); //this.parseABC(0, true ); var name = this.renderedTune.abc.metaText.title + ".abcx"; var conteudo = this.getString(); FILEMANAGER.download(name, conteudo); } else { alert(SITE.translator.getResource("err_saving")); } }; SITE.Estudio.prototype.changePlayMode = function(mode) { SITE.properties.studio.mode = mode? mode : (SITE.properties.studio.mode==="normal"? "learning":"normal"); this.midiPlayer.setAndamento( this.slider.getValue() ); if( SITE.properties.studio.mode === "normal" ) { $("#divDidacticPlayControls" ).hide(); SITE.properties.studio.mode = "normal"; this.modeButton.innerHTML = '<i class="ico-listening" ></i>'; $("#divNormalPlayControls" ).fadeIn(); } else { $("#divNormalPlayControls" ).hide(); SITE.properties.studio.mode = "learning"; this.modeButton.innerHTML = '<i class="ico-learning" ></i>'; $("#divDidacticPlayControls" ).fadeIn(); } }; SITE.Estudio.prototype.posicionaTeclado = function() { if( ! SITE.properties.studio.keyboard.visible ) return; var w = window.innerWidth; var k = this.keyboardWindow.topDiv; var x = parseInt(k.style.left.replace('px', '')); if( x + k.offsetWidth > w ) { x = (w - (k.offsetWidth + 50)); } if(x < 0) x = 10; k.style.left = x+"px"; }; SITE.Estudio.prototype.blockEdition = function( block ) { this.editorWindow.setReadOnly(!block); this.editorWindow.container.dispatchAction('READONLY'); if( block ) { this.editorWindow.setEditorHighLightStyle(); } else { this.editorWindow.clearEditorHighLightStyle(); this.editorWindow.aceEditor.focus(); } }; SITE.Estudio.prototype.startPlay = function( type, value, valueF ) { this.ypos = this.studioCanvasDiv.scrollTop; this.lastStaffGroup = -1; var that = this; if( this.midiPlayer.playing) { if (type === "normal" ) { this.playButton.title = SITE.translator.getResource("playBtn"); this.playButton.innerHTML = '&#160;<i class="ico-play"></i>&#160;'; this.midiPlayer.pausePlay(); } else { this.midiPlayer.pausePlay(true); } this.blockEdition(false); } else { this.accordion.clearKeyboard(); if (type === "normal" ) { this.blockEdition(true); } // esse timeout é só para garantir o tempo para iniciar o play window.setTimeout(function(){that.StartPlayWithTimer(that.renderedTune.abc.midi, type, value, valueF, SITE.properties.studio.timerOn ? 10 : 0); }, 0 ); } }; SITE.Estudio.prototype.setBassIcon = function() { if( SITE.properties.studio.bassOn ) { this.FClefButton.innerHTML = '<i class="ico-clef-bass" ></i>'; } else { this.FClefButton.innerHTML = '<i class="ico-clef-bass" style="opacity:0.5;"></i>'+ '<i class="ico-forbidden" style="position:absolute;left:4px;top:3px"></i>'; } }; SITE.Estudio.prototype.setTrebleIcon = function() { if( SITE.properties.studio.trebleOn ) { this.GClefButton.innerHTML = '<i class="ico-clef-treble" ></i>'; } else { this.GClefButton.innerHTML = '<i class="ico-clef-treble" style="opacity:0.5;"></i>'+ '<i class="ico-forbidden" style="position:absolute;left:4px;top:3px"></i>'; } }; SITE.Estudio.prototype.setTimerIcon = function( value ) { value = value || 0; var ico = '00'; if( SITE.properties.studio.timerOn ) { switch( value ) { case 0: ico = '00'; break; case 1: ico = '05'; break; case 2: ico = '15'; break; case 3: ico = '20'; break; case 6: ico = '30'; break; case 9: ico = '45'; break; default: ico = ''; } if( ico !== '' ) { if( ico !== '00' ) { MIDI.noteOn(0, 90, 100, 0 ); MIDI.noteOff(0, 90, value > 3 ? 0.10 : 0.05 ); } this.timerButton.innerHTML = '<i class="ico-timer-'+ico+'" ></i>'; } } else { this.timerButton.innerHTML = '<i class="ico-timer-00" style="opacity:0.5;"></i>'+ '<i class="ico-forbidden" style="position:absolute;left:4px;top:4px"></i>'; } }; SITE.Estudio.prototype.StartPlayWithTimer = function(midi, type, value, valueF, counter ) { var that = this; if( type !== 'note' && SITE.properties.studio.timerOn && counter > 0 ) { that.setTimerIcon( counter ); counter -= 1; window.setTimeout(function(){that.StartPlayWithTimer(midi, type, value, valueF, counter); }, 1000.0/3 ); } else { that.setTimerIcon( 0 ); if(type==="normal") { this.midiPlayer.setPlayableClefs('TB'); if( this.midiPlayer.startPlay(this.renderedTune.abc.midi) ) { SITE.ga('send', 'event', 'Mapa5', 'play', this.renderedTune.title); // SITE.myGtag( 'event', 'play', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'play', // event_label: this.renderedTune.title, // event_value: 0, // nonInteraction: false // }); this.playButton.title = SITE.translator.getResource("pause"); this.playButton.innerHTML = '&#160;<i class="ico-pause"></i>&#160;'; } } else { this.midiPlayer.setPlayableClefs( (SITE.properties.studio.trebleOn?"T":"")+(SITE.properties.studio.bassOn?"B":"") ); SITE.ga('send', 'event', 'Mapa5', 'didactic-play', this.renderedTune.title); // SITE.myGtag( 'event', 'didactic-play', { // send_to : 'acessos', // event_category: 'Mapa5', // event_action: 'didactic-play', // event_label: this.renderedTune.title, // event_value: 0, // nonInteraction: false // }); this.midiPlayer.startDidacticPlay(this.renderedTune.abc.midi, type, value, valueF ); } } }; SITE.Estudio.prototype.parseABC = function (transpose, force) { var text = this.getString(); this.warnings = []; if (text === "") { this.renderedTune.text = this.initialText = this.renderedTune.abc = undefined; return true; } if (text === this.initialText && !force) { this.updateSelection(); return false; } if (typeof transpose !== "undefined") { if (this.transposer) this.transposer.reset(transpose); else this.transposer = new ABCXJS.parse.Transposer(transpose); } if (!this.abcParser) this.abcParser = new ABCXJS.parse.Parse(this.transposer, this.accordion); try { this.abcParser.parse(text, this.parserparams); this.renderedTune.abc = this.abcParser.getTune(); this.renderedTune.text = this.initialText = this.abcParser.getStrTune(); } catch(e) { waterbug.log( 'Could not parse ABC.' ); waterbug.show(); } // transposição e geracao de tablatura podem ter alterado o texto ABC if (text !== this.initialText) this.setString(this.renderedTune.text); if (this.transposer && this.editorWindow.keySelector) { this.editorWindow.keySelector.populate(this.transposer.keyToNumber(this.transposer.getKeyVoice(0))); } var warnings = this.abcParser.getWarnings() || []; for (var j = 0; j < warnings.length; j++) { this.warnings.push(warnings[j]); } if (this.midiParser) { this.midiParser.parse(this.renderedTune.abc, this.accordion.loadedKeyboard); this.midiPlayer.reset(); this.midiPlayer.setAndamento( this.slider.getValue() ); var warnings = this.midiParser.getWarnings(); for (var j = 0; j < warnings.length; j++) { this.warnings.push(warnings[j]); } } return true; }; SITE.Estudio.prototype.onChange = function() { this.studioCanvasDiv.scrollTop = this.lastYpos; this.resize(); }; SITE.Estudio.prototype.fireChanged = function (transpose, _opts) { if( this.changing ) return; this.lastYpos = this.studioCanvasDiv.scrollTop || 0; this.changing = true; var opts = _opts || {}; var force = opts.force || false; var showProgress = opts.showProgress || false; if (this.parseABC(transpose, force)) { this.modelChanged(showProgress); } else { delete this.changing; } }; SITE.Estudio.prototype.modelChanged = function(showProgress) { var self = this; if(showProgress) { var loader = this.mapa.startLoader( "ModelChanged" ); loader.start( function() { self.onModelChanged(loader); }, '<br>&nbsp;&nbsp;&nbsp;Gerando partitura...<br><br>' ); } else { self.onModelChanged(); } }; SITE.Estudio.prototype.onModelChanged = function(loader) { this.renderedTune.div.innerHTML = ""; this.renderedTune.div.style.display = "none"; if (this.renderedTune.abc === undefined) { delete this.changing; return; } this.renderedTune.div.style.display = ""; var paper = new SVG.Printer( this.renderedTune.div ); this.renderedTune.printer = new ABCXJS.write.Printer(paper, this.printerparams, this.accordion.loadedKeyboard ); //this.renderedTune.printer.printTune( this.renderedTune.abc, {color:'black', backgroundColor:'#ffd'} ); this.renderedTune.printer.printTune( this.renderedTune.abc ); if (this.warningsDiv) { this.warningsDiv.style.color = this.warnings.length > 0 ? "red" : "green"; this.warningsDiv.innerHTML = (this.warnings.length > 0 ? this.warnings.join("<br/>") : "No warnings or errors.") ; } this.renderedTune.printer.addSelectListener(this); this.updateSelection(); if (this.onchangeCallback) { this.onchangeCallback(this); } if( loader ) { loader.update( false, '<br>&nbsp;&nbsp;&nbsp;Gerando tablatura...<br><br>' ); loader.stop(); } this.media.show(this.renderedTune); delete this.changing; }; SITE.Estudio.prototype.highlight = function(abcelem) { if( !this.midiPlayer.playing) { if(SITE.properties.studio.keyboard.visible ) { this.accordion.clearKeyboard(true); this.midiParser.setSelection(abcelem); } if(SITE.properties.studio.editor.visible) { this.editorWindow.setSelection(abcelem); } } }; // limpa apenas a janela de texto. Os demais elementos são controlados por tempo SITE.Estudio.prototype.unhighlight = function(abcelem) { if(SITE.properties.studio.editor.visible) { this.editorWindow.clearSelection(abcelem); } }; SITE.Estudio.prototype.updateSelection = function (force) { var that = this; if( force ) { var selection = that.editorWindow.getSelection(); try { that.renderedTune.printer.rangeHighlight(selection); } catch (e) { } // maybe printer isn't defined yet? delete this.updating; } else { if( this.updating ) return; this.updating = true; setTimeout( that.updateSelection(true), 300 ); } }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; SITE.PartGen = function( mapa, interfaceParams ) { this.mapa = mapa; var that = this; this.Div = new DRAGGABLE.ui.Window( interfaceParams.partGenDiv , ['help'] , {translator: SITE.translator, statusbar: false, draggable: false, top: "3px", left: "1px", width: '100%', height: "100%", title: 'PartGenTitle'} , {listener: this, method: 't2pCallback'} ); this.Div.setVisible(true); this.Div.dataDiv.style.overflow = 'hidden'; this.midiParser = new ABCXJS.midi.Parse(); this.midiPlayer = new ABCXJS.midi.Player(this); var toClub = (interfaceParams.accordion_options.id === 'GAITA_HOHNER_CLUB_IIIM_BR' ); var fromClub = (interfaceParams.accordion_options.id === 'GAITA_MINUANO_GC' ); var canvas_id = 't2pCanvasDiv'; var warnings_id = 't2pWarningsDiv'; this.renderedTune = {text:undefined, abc:undefined, title:undefined ,tab: undefined, div: undefined ,selector: undefined }; this.tabParser = new ABCXJS.Tab2Part(toClub, fromClub, this); if (interfaceParams.generate_tablature) { if (interfaceParams.generate_tablature === 'accordion') { this.accordion = new window.ABCXJS.tablature.Accordion( interfaceParams.accordion_options , SITE.properties.options.tabFormat ,!SITE.properties.options.tabShowOnlyNumbers ); if (interfaceParams.accordionNameSpan) { this.accordionNameSpan = document.getElementById(interfaceParams.accordionNameSpan); this.accordionNameSpan.innerHTML = this.accordion.getFullName(); } } else { throw new Error('Tablatura para ' + interfaceParams.generate_tablature + ' não suportada!'); } } this.editorWindow = new ABCXJS.edit.EditArea( this.Div.dataDiv ,{listener : this, method: 'editorCallback' } ,{ draggable:SITE.properties.partGen.editor.floating ,toolbar: true, statusbar:true, translator: SITE.translator ,title: 'PartGenEditorTitle' ,compileOnChange: false /*SITE.properties.options.autoRefresh*/ } ); this.editorWindow.setVisible(false); this.editorWindow.container.setButtonVisible( 'OCTAVEUP', false); this.editorWindow.container.setButtonVisible( 'OCTAVEDOWN', false); this.editorWindow.keySelector.setVisible(false); this.editorWindow.showHiddenChars(true); this.controlDiv = document.createElement("DIV"); this.controlDiv.setAttribute("id", 't2pcontrolDiv' ); this.controlDiv.setAttribute("class", 'controlDiv btn-group' ); this.Div.dataDiv.appendChild(this.controlDiv); this.controlDiv.innerHTML = document.getElementById(interfaceParams.controlDiv).innerHTML; document.getElementById(interfaceParams.controlDiv).innerHTML = ""; this.media = new SITE.Media( this.Div.dataDiv, interfaceParams.btShowMedia, SITE.properties.partGen.media ); this.keyboardWindow = new DRAGGABLE.ui.Window( this.Div.dataDiv ,[ 'move', 'rotate', 'zoom', 'globe'] ,{title: '', translator: SITE.translator, statusbar: false , top: SITE.properties.partGen.keyboard.top , left: SITE.properties.partGen.keyboard.left } ,{listener: this, method: 'keyboardCallback'} ); this.accordion.setRenderOptions({ draggable: true ,show: false // SITE.properties.partGen.keyboard.visible ,transpose: SITE.properties.partGen.keyboard.transpose ,mirror: SITE.properties.partGen.keyboard.mirror ,scale: SITE.properties.partGen.keyboard.scale ,label: SITE.properties.partGen.keyboard.label }); this.warningsDiv = document.createElement("DIV"); this.warningsDiv.setAttribute("id", warnings_id); this.warningsDiv.setAttribute("class", "warningsDiv" ); this.Div.dataDiv.appendChild(this.warningsDiv); this.abcDiv = document.createElement("DIV"); this.abcDiv.style.display = SITE.properties.partGen.showABCText ? '' : 'none'; this.ckShowABC = document.getElementById(interfaceParams.ckShowABC); this.ckShowABC.checked = SITE.properties.partGen.showABCText; this.ckConvertToClub = document.getElementById(interfaceParams.ckConvertToClub); this.convertToClub = document.getElementById('convertToClub'); this.ckConvertFromClub = document.getElementById(interfaceParams.ckConvertFromClub); this.convertFromClub = document.getElementById('convertFromClub'); //this.ckConvertToClub.checked = SITE.properties.partGen.convertToClub; this.ckConvertToClub.checked = false; this.convertToClub.style.display = toClub ? 'inline' : 'none'; //this.ckConvertFromClub.checked = SITE.properties.partGen.convertFromClub; this.ckConvertFromClub.checked = false; this.convertFromClub.style.display = fromClub ? 'inline' : 'none'; this.studioCanvasDiv = document.createElement("DIV"); this.studioCanvasDiv.setAttribute("id", 't2pStudioCanvasDiv' ); this.studioCanvasDiv.setAttribute("class", "studioCanvasDiv" ); this.canvasDiv = document.createElement("DIV"); this.canvasDiv.setAttribute("id", canvas_id); this.canvasDiv.setAttribute("class", "canvasDiv" ); this.studioCanvasDiv.appendChild(this.abcDiv); this.studioCanvasDiv.appendChild(this.canvasDiv); this.renderedTune.div = this.canvasDiv; this.Div.dataDiv.appendChild(this.studioCanvasDiv); if( this.ps ) this.ps.destroy(); this.ps = new PerfectScrollbar( this.studioCanvasDiv, { handlers: ['click-rail', 'drag-thumb', 'keyboard', 'wheel', 'touch'], wheelSpeed: 1, wheelPropagation: false, suppressScrollX: false, minScrollbarLength: 100, swipeEasing: true, scrollingThreshold: 500 }); this.showMapButton = document.getElementById(interfaceParams.showMapBtn); //this.printButton = document.getElementById(interfaceParams.printBtn); this.fileLoadTab = document.getElementById('fileLoadTab'); this.fileLoadTab.addEventListener('change', function(event) { that.carregaTablatura(event); }, false); this.showEditorButton = document.getElementById(interfaceParams.showEditorBtn); this.updateButton = document.getElementById(interfaceParams.updateBtn); this.loadButton = document.getElementById(interfaceParams.loadBtn); this.saveButton = document.getElementById(interfaceParams.saveBtn); this.editPartButton = document.getElementById(interfaceParams.editPartBtn); this.savePartButton = document.getElementById(interfaceParams.savePartBtn); // player control this.gotoMeasureButton = document.getElementById(interfaceParams.gotoMeasureBtn); this.playButton = document.getElementById(interfaceParams.playBtn); this.stopButton = document.getElementById(interfaceParams.stopBtn); this.currentPlayTimeLabel = document.getElementById(interfaceParams.currentPlayTimeLabel); this.gotoMeasureButton.addEventListener("keypress", function (evt) { if (evt.keyCode === 13) { that.startPlay('repeat', this.value, 200 ); } }, false); this.gotoMeasureButton.addEventListener("focus", function (evt) { if (this.value === SITE.translator.getResource("gotoMeasure").val) { this.value = ""; } }, false); this.gotoMeasureButton.addEventListener("blur", function (evt) { if (this.value === "") { this.value = SITE.translator.getResource("gotoMeasure").val; } }, false); this.showEditorButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.showEditor(); }, false); this.showMapButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.showKeyboard(); }, false); // this.printButton.addEventListener("click", function(evt) { // evt.preventDefault(); // this.blur(); // that.mapa.printPreview(that.renderedTune.div.innerHTML, ["#topBar","#mapaDiv","#partGenDiv"], that.renderedTune.abc.formatting.landscape); // }, false); this.ckConvertToClub.addEventListener("click", function() { SITE.properties.partGen.convertToClub = !!this.checked; that.fireChanged(); }, false); this.ckConvertFromClub.addEventListener("click", function() { SITE.properties.partGen.convertFromClub = !!this.checked; that.fireChanged(); }, false); this.ckShowABC.addEventListener("click", function() { SITE.properties.partGen.showABCText = !!this.checked; that.abcDiv.style.display = this.checked ? '' : 'none'; }, false); this.updateButton.addEventListener("click", function() { that.fireChanged(); }, false); this.loadButton.addEventListener("click", function() { that.fileLoadTab.click(); }, false); this.saveButton.addEventListener("click", function() { that.salvaTablatura(); }, false); this.editPartButton.addEventListener("click", function() { var text = that.renderedTune.text; if(text !== "" ) { that.setVisible(false); SITE.SaveProperties(); FILEMANAGER.saveLocal( 'ultimaPartituraEditada', text ); that.mapa.menu.dispatchAction('menuRepertorio','ABC2PART'); } }, false); this.savePartButton.addEventListener("click", function() { that.salvaPartitura(); }, false); this.playerCallBackOnScroll = function( player ) { that.setScrolling(player); }; this.playerCallBackOnPlay = function( player ) { var strTime = player.getTime().cTime; //if(that.gotoMeasureButton && ! parseInt(that.untilMeasureButton.value)) if(that.gotoMeasureButton) that.gotoMeasureButton.value = player.currentMeasure; if(that.currentPlayTimeLabel) that.currentPlayTimeLabel.innerHTML = strTime; }; this.playerCallBackOnEnd = function( player ) { var warns = that.midiPlayer.getWarnings(); that.playButton.title = SITE.translator.getResource("playBtn"); that.playButton.innerHTML = '&#160;<i class="ico-play"></i>&#160;'; that.renderedTune.printer.clearSelection(); //that.accordion.clearKeyboard(true); that.blockEdition(false); if( warns ) { var txt = ""; warns.forEach(function(msg){ txt += msg + '<br>'; }); that.warningsDiv.style.color = 'blue'; that.warningsDiv.innerHTML = '<hr>'+txt+'<hr>'; } }; this.playButton.addEventListener("click", function() { window.setTimeout(function(){ that.startPlay( 'normal' );}, 0 ); }, false); this.stopButton.addEventListener("click", function(evt) { evt.preventDefault(); this.blur(); that.blockEdition(false); if(that.currentPlayTimeLabel) that.gotoMeasureButton.value = SITE.translator.getResource("gotoMeasure").val; that.currentPlayTimeLabel.innerHTML = "00:00"; that.midiPlayer.stopPlay(); }, false); this.midiPlayer.defineCallbackOnPlay( that.playerCallBackOnPlay ); this.midiPlayer.defineCallbackOnEnd( that.playerCallBackOnEnd ); this.midiPlayer.defineCallbackOnScroll( that.playerCallBackOnScroll ); }; SITE.PartGen.prototype.setup = function(options) { this.mapa.closeMapa(); this.accordion.loadById(options.accordionId); var toClub = (options.accordionId === 'GAITA_HOHNER_CLUB_IIIM_BR' ); var fromClub = (options.accordionId === 'GAITA_MINUANO_GC' ); this.convertToClub.style.display = toClub ? 'inline' : 'none'; this.convertFromClub.style.display = fromClub ? 'inline' : 'none'; this.setVisible(true); if( this.editorWindow.getString() === "" ) { var text = FILEMANAGER.loadLocal("ultimaTablaturaEditada"); if( ! text ) { text = this.getDemoText(); } this.editorWindow.setString(text); } this.warningsDiv.style.display = SITE.properties.options.showWarnings? 'block':'none'; this.fireChanged(); this.editorWindow.restartUndoManager(); this.Div.setSubTitle( '- ' + this.accordion.getTxtModel() ); this.showEditor(SITE.properties.partGen.editor.visible); if(SITE.properties.partGen.editor.floating) { if( SITE.properties.partGen.editor.maximized ) { this.editorWindow.container.dispatchAction('MAXIMIZE'); } else { this.editorWindow.container.dispatchAction('POPOUT'); } } else { this.editorWindow.container.dispatchAction('POPIN'); } this.showKeyboard(SITE.properties.partGen.keyboard.visible); this.keyboardWindow.setTitle(this.accordion.getTxtTuning() + ' - ' + this.accordion.getTxtNumButtons() ); this.resize(); }; SITE.PartGen.prototype.resize = function( ) { // redimensiona a workspace var winH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // -paddingTop 78 var h = (winH -78 - 10 ); var w = (winW - 8 ); this.Div.topDiv.style.left = "3px"; this.Div.topDiv.style.top = "82px"; this.Div.topDiv.style.height = Math.max(h,200) +"px"; this.Div.topDiv.style.width = Math.max(w,400) +"px"; var w = 0, e = 0; var c = this.controlDiv.clientHeight; var t = this.Div.dataDiv.clientHeight; if(! SITE.properties.showWarnings) { w = this.warningsDiv.clientHeight; } if(! SITE.properties.partGen.editor.floating) { e = this.editorWindow.container.topDiv.clientHeight+4; } this.studioCanvasDiv.style.height = t-(w+e+c+6) +"px"; this.posicionaTeclado(); this.editorWindow.resize(); (this.ps) && this.ps.update(); }; SITE.PartGen.prototype.posicionaTeclado = function() { if( ! SITE.properties.partGen.keyboard.visible ) return; var w = window.innerWidth; var k = this.keyboardWindow.topDiv; var x = parseInt(k.style.left.replace('px', '')); if( x + k.offsetWidth > w ) { x = (w - (k.offsetWidth + 50)); } if(x < 0) x = 10; k.style.left = x+"px"; }; SITE.PartGen.prototype.closePartGen = function(save) { var self = this; var loader = this.mapa.startLoader( "ClosePartGen" ); loader.start( function() { var text = self.editorWindow.getString(); self.setVisible(false); self.editorWindow.setString(""); self.midiPlayer.stopPlay(); (save) && SITE.SaveProperties(); if(text !== "" ) FILEMANAGER.saveLocal( 'ultimaTablaturaEditada', text ); self.mapa.openMapa(); loader.stop(); }, '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); }; SITE.PartGen.prototype.showEditor = function(show) { SITE.properties.partGen.editor.visible = (typeof show === 'undefined'? ! SITE.properties.partGen.editor.visible : show ); if(SITE.properties.partGen.editor.visible) { this.editorWindow.setVisible(true); document.getElementById('t2pI_showEditor').setAttribute('class', 'ico-folder-open' ); } else { document.getElementById('t2pI_showEditor').setAttribute('class', 'ico-folder' ); this.editorWindow.setVisible(false); } this.resize(); }; SITE.PartGen.prototype.showKeyboard = function(show) { SITE.properties.partGen.keyboard.visible = (typeof show === 'undefined'? ! SITE.properties.partGen.keyboard.visible : show ); this.accordion.render_opts.show = SITE.properties.partGen.keyboard.visible; if(SITE.properties.partGen.keyboard.visible) { this.keyboardWindow.setVisible(true); this.accordion.printKeyboard(this.keyboardWindow.dataDiv); document.getElementById('t2pI_showMap').setAttribute('class', 'ico-folder-open' ); this.posicionaTeclado(); } else { this.accordion.render_opts.show = false; this.keyboardWindow.setVisible(false); document.getElementById('t2pI_showMap').setAttribute('class', 'ico-folder' ); } }; SITE.PartGen.prototype.editorCallback = function (action, elem) { switch(action) { case 'REFRESH': this.fireChanged(); break; case 'DOWNLOAD': this.salvaTablatura(); break; case 'MAXIMIZE': this.editorWindow.maximizeWindow( true, SITE.properties.partGen.editor ); break; case 'RESTORE': this.editorWindow.maximizeWindow( false, SITE.properties.partGen.editor ); break; case 'POPIN': this.editorWindow.dockWindow(true, SITE.properties.partGen.editor, 0, 0, "calc(100% - 5px)", "200px" ); this.resize(); break; case 'POPOUT': this.editorWindow.dockWindow(false, SITE.properties.partGen.editor ); this.resize(); break; case 'RESIZE': case 'MOVE': this.editorWindow.retrieveProps( SITE.properties.partGen.editor ); break; case 'CLOSE': this.showEditor(false); break; } }; SITE.PartGen.prototype.t2pCallback = function( e ) { switch(e) { case 'CLOSE': this.closePartGen(true); break; case 'HELP': this.mapa.showHelp('HelpTitle', 'PartGenTitle', '/html/geradorPartitura.pt_BR.html', { width: '1024', height: '600' } ); } }; SITE.PartGen.prototype.setVisible = function( visible ) { this.Div.parent.style.display = visible?'block':'none'; }; SITE.PartGen.prototype.fireChanged = function() { var text = this.editorWindow.getString(); if(text !== "" ) { FILEMANAGER.saveLocal( 'ultimaTablaturaEditada', text ); this.renderedTune.text = this.tabParser.parse( text ,this.accordion.loadedKeyboard ,this.ckConvertToClub.checked ,this.ckConvertFromClub.checked ); this.printABC(); } else { this.editorWindow.container.setSubTitle( "" ); this.warningsDiv.innerHTML = ""; this.abcDiv.innerHTML = ""; this.renderedTune.div.innerHTML = ""; delete this.renderedTune.abc.midi; } this.resize(); }; SITE.PartGen.prototype.printABC = function() { this.abcDiv.innerHTML = this.renderedTune.text.replace(/\n/g,'\<br\>'); var warns = this.tabParser.getWarnings(); if(warns) { this.warningsDiv.innerHTML = warns; this.warningsDiv.style.color = 'red'; } else { this.warningsDiv.innerHTML = 'Partitura gerada com sucesso!'; this.warningsDiv.style.color = 'green'; } this.parseABC(); this.renderedTune.printer = new ABCXJS.write.Printer( new SVG.Printer( this.renderedTune.div), {}, this.accordion.loadedKeyboard ); this.renderedTune.printer.printABC(this.renderedTune.abc); this.renderedTune.printer.addSelectListener(this); this.media.show(this.renderedTune); }; SITE.PartGen.prototype.parseABC = function() { var transposer = null; var abcParser = new ABCXJS.parse.Parse( transposer, this.accordion ); abcParser.parse(this.renderedTune.text, this.parserparams ); this.renderedTune.abc = abcParser.getTune(); this.renderedTune.title = this.renderedTune.abc.metaText.title ; if(this.renderedTune.title) { this.editorWindow.container.setSubTitle('- ' + this.renderedTune.abc.metaText.title ); if( ! this.GApartGen || this.GApartGen !== this.renderedTune.abc.metaText.title ) { this.GApartGen = this.renderedTune.abc.metaText.title; SITE.ga('send', 'event', 'Mapa5', 'partGen', this.GApartGen ); } } else this.editorWindow.container.setSubTitle( "" ); if ( this.midiParser ) { this.midiParser.parse( this.renderedTune.abc, this.accordion.loadedKeyboard ); } }; SITE.PartGen.prototype.keyboardCallback = function( e ) { switch(e) { case 'MOVE': var k = this.keyboardWindow.topDiv.style; SITE.properties.partEdit.keyboard.left = k.left; SITE.properties.partEdit.keyboard.top = k.top; break; case 'ROTATE': this.accordion.rotateKeyboard(this.keyboardWindow.dataDiv); SITE.properties.partEdit.keyboard.transpose = this.accordion.render_opts.transpose; SITE.properties.partEdit.keyboard.mirror = this.accordion.render_opts.mirror; break; case 'ZOOM': this.accordion.scaleKeyboard(this.keyboardWindow.dataDiv); SITE.properties.partEdit.keyboard.scale = this.accordion.render_opts.scale; break; case 'GLOBE': this.accordion.changeNotation(); SITE.properties.partEdit.keyboard.label = this.accordion.render_opts.label; break; case 'CLOSE': this.showKeyboard(false); break; } }; SITE.PartGen.prototype.highlight = function(abcelem) { // não é possível, por hora, selecionar o elemento da tablatura a partir da partitura //if(SITE.properties.partGen.editor.visible) { // this.editorWindow.setSelection(abcelem); //} // if(SITE.properties.partGen.keyboard.visible && !this.midiPlayer.playing) { // this.accordion.clearKeyboard(true); // this.midiParser.setSelection(abcelem); // } }; // limpa apenas a janela de texto. Os demais elementos são controlados por tempo SITE.PartGen.prototype.unhighlight = function(abcelem) { if(SITE.properties.partGen.editor.visible) { this.editorWindow.clearSelection(abcelem); } }; SITE.PartGen.prototype.updateSelection = function (force) { // não é possível, por hora, selecionar o elemento da partitura a partir da tablatura return; }; SITE.PartGen.prototype.salvaPartitura = function() { if (FILEMANAGER.requiredFeaturesAvailable()) { var name = this.renderedTune.abc.metaText.title + ".abcx"; var conteudo = this.renderedTune.text; FILEMANAGER.download(name, conteudo); } else { alert(SITE.translator.getResource("err_saving")); } }; SITE.PartGen.prototype.salvaTablatura = function() { if (FILEMANAGER.requiredFeaturesAvailable()) { var name = this.renderedTune.abc.metaText.title + ".tab"; var conteudo = this.editorWindow.getString(); FILEMANAGER.download(name, conteudo); } else { alert(SITE.translator.getResource("err_saving")); } }; SITE.PartGen.prototype.carregaTablatura = function(evt) { var that = this; FILEMANAGER.loadLocalFiles( evt, function() { that.doCarregaTablatura(FILEMANAGER.files); evt.target.value = ""; }); }; SITE.PartGen.prototype.doCarregaTablatura = function(file) { this.editorWindow.setString(file[0].content); this.fireChanged(); }; SITE.PartGen.prototype.blockEdition = function( block ) { this.editorWindow.setReadOnly(!block); this.editorWindow.container.dispatchAction('READONLY'); if( block ) { this.editorWindow.setEditorHighLightStyle(); } else { this.editorWindow.clearEditorHighLightStyle(); this.editorWindow.aceEditor.focus(); } }; SITE.PartGen.prototype.startPlay = function( type, value, valueF ) { this.ypos = this.studioCanvasDiv.scrollTop; this.lastStaffGroup = -1; if( this.midiPlayer.playing) { if (type === "normal" ) { this.playButton.title = SITE.translator.getResource("playBtn"); this.playButton.innerHTML = '&#160;<i class="ico-play"></i>&#160;'; this.midiPlayer.pausePlay(); } else { this.midiPlayer.pausePlay(true); } this.blockEdition(false); } else { this.accordion.clearKeyboard(); if(type==="normal") { this.blockEdition(true); if( this.midiPlayer.startPlay(this.renderedTune.abc.midi) ) { this.playButton.title = SITE.translator.getResource("pause"); this.playButton.innerHTML = '&#160;<i class="ico-pause"></i>&#160;'; } } else { if( this.midiPlayer.startDidacticPlay(this.renderedTune.abc.midi, type, value, valueF ) ) { } } } }; SITE.PartGen.prototype.setScrolling = function(player) { if( !this.studioCanvasDiv || player.currAbsElem.staffGroup === this.lastStaffGroup ) return; this.lastStaffGroup = player.currAbsElem.staffGroup; var fixedTop = player.printer.staffgroups[0].top; var vp = this.studioCanvasDiv.clientHeight - fixedTop; var top = player.printer.staffgroups[player.currAbsElem.staffGroup].top-12; var bottom = top + player.printer.staffgroups[player.currAbsElem.staffGroup].height; if( bottom > vp+this.ypos || this.ypos > top-fixedTop ) { this.ypos = top; this.studioCanvasDiv.scrollTop = this.ypos; } }; SITE.PartGen.prototype.getDemoText = function() { return "\ %hidefingering\n\ T:Hino do Grêmio\n\ C:<NAME>\n\ C:(adapt. <NAME>)\n\ L:1/8\n\ Q:140\n\ M:4/4\n\ K:C\n\ |: C c C c | G g G g | C c C c | G g G g |\n\ |: 9 7'. 8 6' 8. 7' | | 9 7'. 8 6' 8. 7' | |\n\ |: | 7' 5' z | | 7' z 9. 8' |\n\ + 2 1.5 0.5 2 1.5 0.5 2 2 2 2 2 1.5 0.5 2 1.5 0.5 2 2 2 1.5 0.5\n\ f: 5 3 4 2 4 3 3 2 * 5 3 4 2 4 3 3 3 2\n\ \n\ | C z z A z z | F f F f | C g G g | C c C c :|\n\ | 8' | | 8' | 6' z :|\n\ | 10. 9' 11 9'. 11 | 10' 11 z 9. 8' | 11. 9' 7' 8'. 9 | :|\n\ + 2 1.5 0.5 2 1.5 0.5 2 2 2 1.5 0.5 2 1.5 0.5 2 1.5 0.5 2 2 2 2\n\ f: 2 4 3 5 3 5 4 5 * 2 3 2 5 3 2 3 4 2\n"; }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; SITE.PartEdit = function( mapa, interfaceParams ) { this.mapa = mapa; var that = this; this.Div = new DRAGGABLE.ui.Window( interfaceParams.partEditDiv , ['help'] , {translator: SITE.translator, statusbar: false, draggable: false, top: "3px", left: "1px", width: '100%', height: "100%", title: 'PartEditTitle'} , {listener: this, method: 'a2pCallback'} ); this.Div.setVisible(true); this.Div.dataDiv.style.overflow = 'hidden'; this.midiParser = new ABCXJS.midi.Parse(); this.midiPlayer = new ABCXJS.midi.Player(this); var canvas_id = 'a2pCanvasDiv'; var warnings_id = 'a2pWarningsDiv'; this.renderedTune = {text:undefined, abc:undefined, title:undefined ,tab: undefined, div: undefined ,selector: undefined }; if (interfaceParams.generate_tablature) { if (interfaceParams.generate_tablature === 'accordion') { this.accordion = new window.ABCXJS.tablature.Accordion( interfaceParams.accordion_options , SITE.properties.options.tabFormat ,!SITE.properties.options.tabShowOnlyNumbers ); if (interfaceParams.accordionNameSpan) { this.accordionNameSpan = document.getElementById(interfaceParams.accordionNameSpan); this.accordionNameSpan.innerHTML = this.accordion.getFullName(); } } else { throw new Error('Tablatura para ' + interfaceParams.generate_tablature + ' não suportada!'); } } this.editorWindow = new ABCXJS.edit.EditArea( this.Div.dataDiv ,{listener : this, method: 'editorCallback' } ,{ draggable:SITE.properties.partEdit.editor.floating ,toolbar: true, statusbar:true, translator: SITE.translator ,title: 'PartEditEditorTitle' ,compileOnChange: false /*SITE.properties.options.autoRefresh*/ } ); this.editorWindow.setVisible(false); this.controlDiv = document.createElement("DIV"); this.controlDiv.setAttribute("id", 'a2pcontrolDiv' ); this.controlDiv.setAttribute("class", 'controlDiv btn-group' ); this.Div.dataDiv.appendChild(this.controlDiv); this.controlDiv.innerHTML = document.getElementById(interfaceParams.controlDiv).innerHTML; document.getElementById(interfaceParams.controlDiv).innerHTML = ""; this.media = new SITE.Media( this.Div.dataDiv, interfaceParams.btShowMedia, SITE.properties.partEdit.media ); this.keyboardWindow = new DRAGGABLE.ui.Window( this.Div.dataDiv ,[ 'move', 'rotate', 'zoom', 'globe'] ,{title: '', translator: SITE.translator, statusbar: false , top: SITE.properties.partEdit.keyboard.top , left: SITE.properties.partEdit.keyboard.left } ,{listener: this, method: 'keyboardCallback'} ); this.accordion.setRenderOptions({ draggable: true ,show: SITE.properties.partEdit.keyboard.visible ,transpose: SITE.properties.partEdit.keyboard.transpose ,mirror: SITE.properties.partEdit.keyboard.mirror ,scale: SITE.properties.partEdit.keyboard.scale ,label: SITE.properties.partEdit.keyboard.label }); this.warningsDiv = document.createElement("DIV"); this.warningsDiv.setAttribute("id", warnings_id); this.warningsDiv.setAttribute("class", "warningsDiv" ); this.Div.dataDiv.appendChild(this.warningsDiv); this.studioCanvasDiv = document.createElement("DIV"); this.studioCanvasDiv.setAttribute("id", 'a2pStudioCanvasDiv' ); this.studioCanvasDiv.setAttribute("class", "studioCanvasDiv" ); this.canvasDiv = document.createElement("DIV"); this.canvasDiv.setAttribute("id", canvas_id); this.canvasDiv.setAttribute("class", "canvasDiv" ); this.studioCanvasDiv.appendChild(this.canvasDiv); this.renderedTune.div = this.canvasDiv; this.Div.dataDiv.appendChild(this.studioCanvasDiv); if( this.ps ) this.ps.destroy(); this.ps = new PerfectScrollbar( this.studioCanvasDiv, { handlers: ['click-rail', 'drag-thumb', 'keyboard', 'wheel', 'touch'], wheelSpeed: 1, wheelPropagation: false, suppressScrollX: false, minScrollbarLength: 100, swipeEasing: true, scrollingThreshold: 500 }); this.fileLoadABC = document.getElementById('fileLoadABC'); this.fileLoadABC.addEventListener('change', function(event) { that.carregaPartitura(event); }, false); this.showEditorButton = document.getElementById(interfaceParams.showEditorBtn); this.showMapButton = document.getElementById(interfaceParams.showMapBtn); this.updateButton = document.getElementById(interfaceParams.updateBtn); this.loadButton = document.getElementById(interfaceParams.loadBtn); this.saveButton = document.getElementById(interfaceParams.saveBtn); this.printButton = document.getElementById(interfaceParams.printBtn); // player control this.playButton = document.getElementById(interfaceParams.playBtn); this.stopButton = document.getElementById(interfaceParams.stopBtn); this.currentPlayTimeLabel = document.getElementById(interfaceParams.currentPlayTimeLabel); this.showEditorButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.showEditor(); }, false); this.showMapButton.addEventListener("click", function (evt) { evt.preventDefault(); this.blur(); that.showKeyboard(); }, false); this.updateButton.addEventListener("click", function() { that.fireChanged(); }, false); this.loadButton.addEventListener("click", function() { that.fileLoadABC.click(); }, false); this.saveButton.addEventListener("click", function() { that.salvaPartitura(); }, false); this.printButton.addEventListener("click", function(evt) { evt.preventDefault(); this.blur(); that.mapa.printPreview(that.renderedTune.div.innerHTML, ["#topBar","#mapaDiv","#partEditDiv"], that.renderedTune.abc.formatting.landscape); }, false); this.playerCallBackOnScroll = function( player ) { that.setScrolling(player); }; this.playerCallBackOnPlay = function( player ) { var strTime = player.getTime().cTime; if(that.gotoMeasureButton) that.gotoMeasureButton.value = player.currentMeasure; if(that.currentPlayTimeLabel) that.currentPlayTimeLabel.innerHTML = strTime; }; this.playerCallBackOnEnd = function( player ) { var warns = that.midiPlayer.getWarnings(); that.playButton.title = SITE.translator.getResource("playBtn"); that.playButton.innerHTML = '&#160;<i class="ico-play"></i>&#160;'; that.renderedTune.printer.clearSelection(); that.accordion.clearKeyboard(true); that.blockEdition(false); if( warns ) { var txt = ""; warns.forEach(function(msg){ txt += msg + '<br>'; }); that.warningsDiv.style.color = 'blue'; that.warningsDiv.innerHTML = '<hr>'+txt+'<hr>'; } }; this.playButton.addEventListener("click", function() { window.setTimeout(function(){ that.startPlay( 'normal' );}, 0 ); }, false); this.stopButton.addEventListener("click", function(evt) { evt.preventDefault(); this.blur(); that.blockEdition(false); if(that.currentPlayTimeLabel) that.currentPlayTimeLabel.innerHTML = "00:00"; that.midiPlayer.stopPlay(); }, false); this.midiPlayer.defineCallbackOnPlay( that.playerCallBackOnPlay ); this.midiPlayer.defineCallbackOnEnd( that.playerCallBackOnEnd ); this.midiPlayer.defineCallbackOnScroll( that.playerCallBackOnScroll ); }; SITE.PartEdit.prototype.setup = function(options) { this.mapa.closeMapa(); this.accordion.loadById(options.accordionId); this.setVisible(true); if( this.editorWindow.getString() === "" ) { var text = FILEMANAGER.loadLocal("ultimaPartituraEditada"); if( ! text ) { text = this.getDemoText(); } this.editorWindow.setString(text); } this.warningsDiv.style.display = SITE.properties.options.showWarnings? 'block':'none'; this.fireChanged(); this.editorWindow.restartUndoManager(); this.Div.setSubTitle( '- ' + this.accordion.getTxtModel() ); this.showEditor(SITE.properties.partEdit.editor.visible); if(SITE.properties.partEdit.editor.floating) { if( SITE.properties.partEdit.editor.maximized ) { this.editorWindow.container.dispatchAction('MAXIMIZE'); } else { this.editorWindow.container.dispatchAction('POPOUT'); } } else { this.editorWindow.container.dispatchAction('POPIN'); } this.showKeyboard(SITE.properties.partEdit.keyboard.visible); this.keyboardWindow.setTitle(this.accordion.getTxtTuning() + ' - ' + this.accordion.getTxtNumButtons() ); this.resize(); }; SITE.PartEdit.prototype.resize = function( ) { // redimensiona a workspace var winH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // -paddingTop 78 var h = (winH -78 - 10 ); var w = (winW - 8 ); this.Div.topDiv.style.left = "3px"; this.Div.topDiv.style.top = "82px"; this.Div.topDiv.style.height = Math.max(h,200) +"px"; this.Div.topDiv.style.width = Math.max(w,400) +"px"; var w = 0, e = 0; var c = this.controlDiv.clientHeight; var t = this.Div.dataDiv.clientHeight; if(! SITE.properties.showWarnings) { w = this.warningsDiv.clientHeight; } if(! SITE.properties.partEdit.editor.floating) { e = this.editorWindow.container.topDiv.clientHeight+4; } this.studioCanvasDiv.style.height = t-(w+e+c+6) +"px"; this.posicionaTeclado(); this.editorWindow.resize(); (this.ps) && this.ps.update(); }; SITE.PartEdit.prototype.posicionaTeclado = function() { if( ! SITE.properties.partEdit.keyboard.visible ) return; var w = window.innerWidth; var k = this.keyboardWindow.topDiv; var x = parseInt(k.style.left.replace('px', '')); if( x + k.offsetWidth > w ) { x = (w - (k.offsetWidth + 50)); } if(x < 0) x = 10; k.style.left = x+"px"; }; SITE.PartEdit.prototype.closePartEdit = function(save) { var self = this; var loader = this.mapa.startLoader( "ClosePartEdit" ); loader.start( function() { var text = self.editorWindow.getString(); self.setVisible(false); self.editorWindow.setString(""); self.midiPlayer.stopPlay(); (save) && SITE.SaveProperties(); if(text !== "" ) FILEMANAGER.saveLocal( 'ultimaPartituraEditada', text ); self.mapa.openMapa(); loader.stop(); }, '<br/>&#160;&#160;&#160;'+SITE.translator.getResource('wait')+'<br/><br/>' ); }; SITE.PartEdit.prototype.showEditor = function(show) { SITE.properties.partEdit.editor.visible = (typeof show === 'undefined'? ! SITE.properties.partEdit.editor.visible : show ); if(SITE.properties.partEdit.editor.visible) { this.editorWindow.setVisible(true); document.getElementById('a2pI_showEditor').setAttribute('class', 'ico-folder-open' ); } else { document.getElementById('a2pI_showEditor').setAttribute('class', 'ico-folder' ); this.editorWindow.setVisible(false); } this.resize(); }; SITE.PartEdit.prototype.showKeyboard = function(show) { SITE.properties.partEdit.keyboard.visible = (typeof show === 'undefined'? ! SITE.properties.partEdit.keyboard.visible : show ); this.accordion.render_opts.show = SITE.properties.partEdit.keyboard.visible; if(SITE.properties.partEdit.keyboard.visible) { this.keyboardWindow.setVisible(true); this.accordion.printKeyboard(this.keyboardWindow.dataDiv); document.getElementById('a2pI_showMap').setAttribute('class', 'ico-folder-open' ); this.posicionaTeclado(); } else { this.accordion.render_opts.show = false; this.keyboardWindow.setVisible(false); document.getElementById('a2pI_showMap').setAttribute('class', 'ico-folder' ); } }; SITE.PartEdit.prototype.editorCallback = function (action, elem) { switch(action) { case '0': break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '10': case '11': case '-1': case '-2': case '-3': case '-4': case '-5': case '-6': case '-7': case '-8': case '-9': case '-10': case '-11': this.fireChanged( parseInt(action), {force:true} ); break; case 'OCTAVEUP': this.fireChanged(12, {force:true} ); break; case 'OCTAVEDOWN': this.fireChanged(-12, {force:true} ); break; case 'REFRESH': this.fireChanged(); break; case 'DOWNLOAD': this.salvaPartitura(); break; case 'MAXIMIZE': this.editorWindow.maximizeWindow( true, SITE.properties.partEdit.editor ); break; case 'RESTORE': this.editorWindow.maximizeWindow( false, SITE.properties.partEdit.editor ); break; case 'POPIN': this.editorWindow.dockWindow(true, SITE.properties.partEdit.editor, 0, 0, "calc(100% - 5px)", "200px" ); this.resize(); break; case 'POPOUT': this.editorWindow.dockWindow(false, SITE.properties.partEdit.editor ); this.resize(); break; case 'RESIZE': case 'MOVE': this.editorWindow.retrieveProps( SITE.properties.partEdit.editor ); break; case 'CLOSE': this.showEditor(false); break; } }; SITE.PartEdit.prototype.a2pCallback = function( e ) { switch(e) { case 'CLOSE': this.closePartEdit(true); break; case 'HELP': //this.mapa.showHelp('HelpTitle', 'PartEditTitle', '/html/geradorPartitura.pt_BR.html', { width: '1024', height: '600' } ); alert( 'Not implemented yet!' ); } }; SITE.PartEdit.prototype.setVisible = function( visible ) { this.Div.parent.style.display = visible?'block':'none'; }; SITE.PartEdit.prototype.fireChanged = function(transpose) { var text = this.editorWindow.getString(); if(text !== "" ) { FILEMANAGER.saveLocal( 'ultimaPartituraEditada', text ); this.parseABC(text, transpose); this.printABC(); } else { this.editorWindow.container.setSubTitle( "" ); this.warningsDiv.innerHTML = ""; this.renderedTune.div.innerHTML = ""; delete this.renderedTune.abc.midi; } this.resize(); }; SITE.PartEdit.prototype.parseABC = function(text, transpose) { transpose = transpose || 0; var transposer = new ABCXJS.parse.Transposer(transpose); var abcParser = new ABCXJS.parse.Parse( transposer, this.accordion ); try { abcParser.parse(text, this.parserparams ); this.renderedTune.text = abcParser.getStrTune(); if( this.renderedTune.text !== text ) { this.editorWindow.setString(this.renderedTune.text); //FILEMANAGER.saveLocal( 'ultimaPartituraEditada', this.renderedTune.text ); } } catch(e) { waterbug.log( 'Could not parse ABC.' ); waterbug.show(); } this.renderedTune.abc = abcParser.getTune(); this.renderedTune.title = this.renderedTune.abc.metaText.title ; if (this.editorWindow.keySelector) { this.editorWindow.keySelector.populate(transposer.keyToNumber(transposer.getKeyVoice(0))); } var warnings = abcParser.getWarnings() || []; if(this.renderedTune.title) { this.editorWindow.container.setSubTitle('- ' + this.renderedTune.abc.metaText.title ); if( ! this.GApartEdit || this.GApartEdit !== this.renderedTune.abc.metaText.title ) { this.GApartEdit = this.renderedTune.abc.metaText.title; SITE.ga('send', 'event', 'Mapa5', 'partEdit', this.GApartEdit ); } }else this.editorWindow.container.setSubTitle( "" ); if ( this.midiParser ) { this.midiParser.parse( this.renderedTune.abc, this.accordion.loadedKeyboard ); warnings = warnings.concat(this.midiParser.getWarnings() ); } if(warnings.length>0) { this.warningsDiv.innerHTML = warnings.join('<br>'); this.warningsDiv.style.color = 'red'; } else { this.warningsDiv.innerHTML = 'Partitura gerada com sucesso!'; this.warningsDiv.style.color = 'green'; } }; SITE.PartEdit.prototype.printABC = function() { this.renderedTune.div.innerHTML = ""; this.renderedTune.printer = new ABCXJS.write.Printer( new SVG.Printer( this.renderedTune.div ), {}, this.accordion.loadedKeyboard ); this.renderedTune.printer.printABC(this.renderedTune.abc); this.renderedTune.printer.addSelectListener(this); this.media.show(this.renderedTune); }; SITE.PartEdit.prototype.highlight = function(abcelem) { if( !this.midiPlayer.playing ) { if(SITE.properties.partEdit.keyboard.visible ) { this.accordion.clearKeyboard(true); this.midiParser.setSelection(abcelem); } if(SITE.properties.partEdit.editor.visible ) { this.editorWindow.setSelection(abcelem); } } }; // limpa apenas a janela de texto. Os demais elementos são controlados por tempo SITE.PartEdit.prototype.unhighlight = function(abcelem) { if(SITE.properties.partEdit.editor.visible) { this.editorWindow.clearSelection(abcelem); } }; SITE.PartEdit.prototype.updateSelection = function (force) { var that = this; if( force ) { var selection = that.editorWindow.getSelection(); try { that.renderedTune.printer.rangeHighlight(selection); } catch (e) { } // maybe printer isn't defined yet? delete this.updating; } else { if( this.updating ) return; this.updating = true; setTimeout( that.updateSelection(true), 300 ); } }; SITE.PartEdit.prototype.keyboardCallback = function( e ) { switch(e) { case 'MOVE': var k = this.keyboardWindow.topDiv.style; SITE.properties.partEdit.keyboard.left = k.left; SITE.properties.partEdit.keyboard.top = k.top; break; case 'ROTATE': this.accordion.rotateKeyboard(this.keyboardWindow.dataDiv); SITE.properties.partEdit.keyboard.transpose = this.accordion.render_opts.transpose; SITE.properties.partEdit.keyboard.mirror = this.accordion.render_opts.mirror; break; case 'ZOOM': this.accordion.scaleKeyboard(this.keyboardWindow.dataDiv); SITE.properties.partEdit.keyboard.scale = this.accordion.render_opts.scale; break; case 'GLOBE': this.accordion.changeNotation(); SITE.properties.partEdit.keyboard.label = this.accordion.render_opts.label; break; case 'CLOSE': this.showKeyboard(false); break; } }; SITE.PartEdit.prototype.salvaPartitura = function() { if (FILEMANAGER.requiredFeaturesAvailable()) { var name = this.renderedTune.abc.metaText.title + ".abcx"; var conteudo = this.renderedTune.text; FILEMANAGER.download(name, conteudo); } else { alert(SITE.translator.getResource("err_saving")); } }; SITE.PartEdit.prototype.carregaPartitura = function(evt) { var that = this; FILEMANAGER.loadLocalFiles( evt, function() { that.doCarregaPartitura(FILEMANAGER.files); evt.target.value = ""; }); }; SITE.PartEdit.prototype.doCarregaPartitura = function(file) { this.editorWindow.setString(file[0].content); this.fireChanged(); }; SITE.PartEdit.prototype.blockEdition = function( block ) { this.editorWindow.setReadOnly(!block); this.editorWindow.container.dispatchAction('READONLY'); if( block ) { this.editorWindow.setEditorHighLightStyle(); } else { this.editorWindow.clearEditorHighLightStyle(); this.editorWindow.aceEditor.focus(); } }; SITE.PartEdit.prototype.startPlay = function( type, value ) { this.ypos = this.studioCanvasDiv.scrollTop; this.lastStaffGroup = -1; if( this.midiPlayer.playing) { if (type === "normal" ) { this.playButton.title = SITE.translator.getResource("playBtn"); this.playButton.innerHTML = '&#160;<i class="ico-play"></i>&#160;'; this.midiPlayer.pausePlay(); } else { this.midiPlayer.pausePlay(true); } this.blockEdition(false); } else { this.accordion.clearKeyboard(); if(type==="normal") { this.blockEdition(true); if( this.midiPlayer.startPlay(this.renderedTune.abc.midi) ) { this.playButton.title = SITE.translator.getResource("pause"); this.playButton.innerHTML = '&#160;<i class="ico-pause"></i>&#160;'; } } else { if( this.midiPlayer.startDidacticPlay(this.renderedTune.abc.midi, type, value ) ) { } } } }; SITE.PartEdit.prototype.setScrolling = function(player) { if( !this.studioCanvasDiv || player.currAbsElem.staffGroup === this.lastStaffGroup ) return; this.lastStaffGroup = player.currAbsElem.staffGroup; var fixedTop = player.printer.staffgroups[0].top; var vp = this.studioCanvasDiv.clientHeight - fixedTop; var top = player.printer.staffgroups[player.currAbsElem.staffGroup].top-12; var bottom = top + player.printer.staffgroups[player.currAbsElem.staffGroup].height; if( bottom > vp+this.ypos || this.ypos > top-fixedTop ) { this.ypos = top; this.studioCanvasDiv.scrollTop = this.ypos; } }; SITE.PartEdit.prototype.getDemoText = function() { return '\ X: 1\n\ T:Oh! Susannah\n\ F:/images/susannah.tablatura.png\n\ M:2/4\n\ L:1/4\n\ Q:100\n\ K:G\n\ V:melodia treble\n\ |"C"c c|e/2e/2 -e/2e/2|"G"d/2d/2 B/2G/2|"D7"A3/2G/4A/4|\\\n\ "G"B/2d/2 d3/4e/4|d/2B/2 G/2A/2|"G"B/2B/2 "D7"A/2A/2|"G"G2 |\n\ V:baixos bass\n\ | C, [C,E,G,] | C, z | G,, z | D, z | G,, z | G,, z | D, [D,^F,A,] | G,, z |\n\ V:tablatura accordionTab'; }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; SITE.TabGen = function( mapa, interfaceParams ) { var that = this; this.mapa = mapa; this.accordion = mapa.accordion; var warnings_id = 'p2tWarningsDiv'; this.Div = new DRAGGABLE.ui.Window( interfaceParams.tabGenDiv , null // ['help|Ajuda'] , {translator: SITE.translator, statusbar: false, draggable: false, top: "3px", left: "1px", width: '100%', height: "100%", title: 'TabGenTitle'} , {listener: this, method: 'p2tCallback'} ); this.Div.setVisible(true); this.Div.dataDiv.style.overflow = 'hidden'; this.controlDiv = document.createElement("DIV"); this.controlDiv.setAttribute("id", 'p2tcontrolDiv' ); this.controlDiv.setAttribute("class", 'controlDiv btn-group' ); this.Div.dataDiv.appendChild(this.controlDiv); this.controlDiv.innerHTML = document.getElementById(interfaceParams.controlDiv).innerHTML; document.getElementById(interfaceParams.controlDiv).innerHTML = ""; this.warningsDiv = document.createElement("DIV"); this.warningsDiv.setAttribute("id", warnings_id); this.warningsDiv.setAttribute("class", "warningsDiv" ); this.Div.dataDiv.appendChild(this.warningsDiv); this.abcEditorDiv = document.createElement("DIV"); this.Div.dataDiv.appendChild(this.abcEditorDiv); this.tabEditorDiv = document.createElement("DIV"); this.Div.dataDiv.appendChild(this.tabEditorDiv); this.tabParser = new ABCXJS.Part2Tab(); this.abcEditorWindow = new ABCXJS.edit.EditArea( this.abcEditorDiv ,{listener : this, method: 'abcEditorCallback' } ,{ draggable:SITE.properties.tabGen.abcEditor.floating ,toolbar: true, statusbar:true, translator: SITE.translator ,title: 'TabGenSourceEditorTitle' ,compileOnChange: false /*SITE.properties.options.autoRefresh*/ } ); this.abcEditorWindow.setVisible(true); this.abcEditorWindow.container.setButtonVisible( 'CLOSE', false); this.abcEditorWindow.container.setButtonVisible( 'DOWNLOAD', false); this.abcEditorWindow.container.setButtonVisible( 'OCTAVEUP', false); this.abcEditorWindow.container.setButtonVisible( 'OCTAVEDOWN', false); this.abcEditorWindow.keySelector.setVisible(false); this.tabEditorWindow = new ABCXJS.edit.EditArea( this.tabEditorDiv ,{listener : this, method: 'tabEditorCallback' } ,{ draggable:SITE.properties.tabGen.tabEditor.floating ,toolbar: true, statusbar:true, translator: SITE.translator ,title: 'TabGenTargetEditorTitle' ,compileOnChange: false /*SITE.properties.options.autoRefresh*/ } ); this.tabEditorWindow.setVisible(true); this.tabEditorWindow.container.setButtonVisible( 'CLOSE', false); this.tabEditorWindow.container.setButtonVisible( 'DOWNLOAD', false); this.tabEditorWindow.container.setButtonVisible( 'OCTAVEUP', false); this.tabEditorWindow.container.setButtonVisible( 'OCTAVEDOWN', false); this.tabEditorWindow.container.setButtonVisible( 'REFRESH', false); this.tabEditorWindow.keySelector.setVisible(false); this.updateButton = document.getElementById(interfaceParams.updateBtn); this.openButton = document.getElementById(interfaceParams.openBtn); this.saveButton = document.getElementById(interfaceParams.saveBtn); this.updateButton.addEventListener("click", function() { that.fireChanged(); }, false); this.saveButton.addEventListener("click", function() { that.salvaTablatura(); }, false); this.openButton.addEventListener("click", function() { var text = that.tabEditorWindow.getString(); that.setVisible(false); SITE.SaveProperties(); if(text !== "" ) { FILEMANAGER.saveLocal( 'ultimaTablaturaEditada', text ); that.mapa.menu.dispatchAction('menuRepertorio','TAB2PART'); } }, false); }; SITE.TabGen.prototype.setup = function(abcText) { this.mapa.closeMapa(); this.setVisible(true); this.abcEditorWindow.setString(abcText); this.abcEditorWindow.container.dispatchAction('READONLY'); if(SITE.properties.tabGen.abcEditor.floating) { if( SITE.properties.tabGen.abcEditor.maximized ) { this.abcEditorWindow.container.dispatchAction('MAXIMIZE'); } else { this.abcEditorWindow.container.dispatchAction('POPOUT'); } } else { this.abcEditorWindow.container.dispatchAction('POPIN'); } this.warningsDiv.style.display = SITE.properties.options.showWarnings? 'block':'none'; this.fireChanged(); if(SITE.properties.tabGen.tabEditor.floating) { if( SITE.properties.tabGen.tabEditor.maximized ) { this.tabEditorWindow.container.dispatchAction('MAXIMIZE'); } else { this.tabEditorWindow.container.dispatchAction('POPOUT'); } } else { this.tabEditorWindow.container.dispatchAction('POPIN'); } this.tabEditorWindow.container.dispatchAction('READONLY'); this.tabEditorWindow.restartUndoManager(); this.resize(); }; SITE.TabGen.prototype.setVisible = function( visible ) { this.Div.parent.style.display = visible?'block':'none'; }; SITE.TabGen.prototype.fireChanged = function() { this.title = ""; var abcText = this.tabParser.parse(this.abcEditorWindow.getString(), this.accordion.loadedKeyboard ); this.title = this.tabParser.title; this.printTablature(abcText); }; SITE.TabGen.prototype.salvaTablatura = function() { if (FILEMANAGER.requiredFeaturesAvailable()) { var name = this.title + ".tab"; var conteudo = this.tabEditorWindow.getString(); FILEMANAGER.download(name, conteudo); } else { alert(SITE.translator.getResource("err_saving")); } }; SITE.TabGen.prototype.printTablature = function(abcText) { this.tabEditorWindow.setString(abcText); var warns = this.tabParser.getWarnings(); if(warns) { this.warningsDiv.innerHTML = warns; this.warningsDiv.style.color = 'red'; } else { this.warningsDiv.innerHTML = 'Tablatura extraída com sucesso!'; this.warningsDiv.style.color = 'green'; } }; SITE.TabGen.prototype.resize = function( ) { // redimensiona a workspace var winH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // -paddingTop 78 var h = (winH -78 - 10 ); var w = (winW - 8 ); this.Div.topDiv.style.left = "3px"; this.Div.topDiv.style.top = "82px"; this.Div.topDiv.style.height = Math.max(h,200) +"px"; this.Div.topDiv.style.width = Math.max(w,400) +"px"; }; SITE.TabGen.prototype.updateSelection = function (force) { return; // não é possível, por hora, selecionar o elemento da partitura a partir da tablatura }; SITE.TabGen.prototype.p2tCallback = function( e ) { switch(e) { case 'CLOSE': this.setVisible(false); SITE.SaveProperties(); this.mapa.openMapa(); break; } }; SITE.TabGen.prototype.tabEditorCallback = function (action) { switch(action) { case 'REFRESH': this.fireChanged(); break; case 'MAXIMIZE': this.tabEditorWindow.maximizeWindow( true, SITE.properties.tabGen.tabEditor ); break; case 'RESTORE': this.tabEditorWindow.maximizeWindow( false, SITE.properties.tabGen.tabEditor ); break; case 'POPIN': this.tabEditorWindow.dockWindow(true, SITE.properties.tabGen.tabEditor, 0, 0, "calc(100% - 5px)", "400px" ); this.resize(); break; case 'POPOUT': this.tabEditorWindow.dockWindow(false, SITE.properties.tabGen.tabEditor ); this.resize(); break; case 'RESIZE': case 'MOVE': this.tabEditorWindow.retrieveProps( SITE.properties.tabGen.tabEditor ); break; } }; SITE.TabGen.prototype.abcEditorCallback = function (action) { switch(action) { case 'REFRESH': this.fireChanged(); break; case 'MAXIMIZE': this.abcEditorWindow.maximizeWindow( true, SITE.properties.tabGen.abcEditor ); break; case 'RESTORE': this.abcEditorWindow.maximizeWindow( false, SITE.properties.tabGen.abcEditor ); break; case 'POPIN': this.abcEditorWindow.dockWindow(true, SITE.properties.tabGen.abcEditor, 0, 0, "calc(100% - 5px)", "400px" ); this.resize(); break; case 'POPOUT': this.abcEditorWindow.dockWindow(false, SITE.properties.tabGen.abcEditor ); this.resize(); break; case 'RESIZE': case 'MOVE': this.abcEditorWindow.retrieveProps( SITE.properties.tabGen.abcEditor ); break; } }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.ABCXJS) window.ABCXJS = {}; String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); }; ABCXJS.Tab2PartLine = function () { this.basses = []; this.treble = ""; this.tablature = ""; this.fingeringLine = ""; }; ABCXJS.Tab2Part = function (toClub, fromClub ) { this.toClub = toClub || false; this.fromClub = fromClub || false; this.ties = []; this.keyAcidentals = []; this.barAccidentals = []; this.barBassAccidentals = []; this.startSyms = "|/+%f"; this.barSyms = ":]|["; this.spaces = "-.\ \t"; this.bassOctave = 2; this.inTriplet = false; this.init(); this.addWarning = function ( msg ) { this.warnings.push(msg); }; this.getWarnings = function () { return this.warnings.join('<br>'); }; }; ABCXJS.Tab2Part.prototype.init = function () { this.tabText; this.tabLines; this.endColumn = 0; this.startColumn = null; this.durationLine = null; this.columnDuration = ""; this.barEnding = false; this.trebleStaffs = { open: null, close: null}; this.parsedLines = []; this.currLine = 0; this.abcText = ""; this.updateBarNumberOnNextNote = false; this.alertedBarNumber = 0; this.currBar = 0; this.currStaff = -1; this.warnings = []; }; ABCXJS.Tab2Part.prototype.parse = function (text, keyboard, toClub, fromClub ) { this.init(); this.tabText = text; this.tabLines = this.extractLines(); this.keyboard = keyboard; this.hasErrors = false; this.toClub = toClub; this.fromClub = fromClub; this.directives = { landscape: '%landscape' ,stretchlast: '%stretchlast' ,pagenumbering: '%pagenumbering' ,staffsep: '%staffsep 20' ,barsperstaff: '%barsperstaff 6' ,papersize: '%%papersize A4' ,barnumbers: '%%barnumbers 0' }; while((!this.hasErrors) && this.currLine < this.tabLines.length) { if( this.skipEmptyLines() ) { this.parseLine(); this.currLine++; } } if( ! this.hasErrors ) { //adicionar vozes treble this.addLine( 'V:1 treble' ); var t= ""; this.parsedLines.forEach( function(item) { t += item.treble + '\n'; if( item.fingeringLine ) { t += item.fingeringLine + '\n'; } }); this.addLine( t.slice(0,-1) ); //adicionar vozes bass this.addLine( 'V:2 bass' ); var t= ""; this.parsedLines.forEach( function(item) { t += item.basses[0] + '\n'; }); this.addLine( t.slice(0,-1) ); //adicionar accordionTab this.addLine( 'V:3 accordionTab' ); t= ""; this.parsedLines.forEach( function(item) { t += item.tablature + '\n'; }); this.addLine( t.slice(0,-1) ); } // se restaram diretivas nesta lista for (var d in this.directives) { this.abcText = this.directives[d] + '\n' + this.abcText; } return this.abcText; }; ABCXJS.Tab2Part.prototype.extractLines = function () { var v = this.tabText.split('\n'); v.forEach( function(linha, i) { if( linha.charAt(0) !== '%' ) { var l = linha.split('%'); v[i] = l[0].trim(); } } ); return v; }; ABCXJS.Tab2Part.prototype.parseLine = function () { //var header = lines[l].match(/^([CKLMT]\:*[^\r\n\t]*)/g); - assim não remove comentarios var header = this.tabLines[this.currLine].match(/^([ACRFKLMNTQZ]\:*[^\r\n\t\%]*)/g); var commentOrDirective = this.tabLines[this.currLine].match(/^\%/); if( commentOrDirective ) { var found = false; for (var d in this.directives) { if( this.tabLines[this.currLine].includes( d ) ) { this.directives[d] = this.tabLines[this.currLine]; found = true; break; } } if (!found) { this.addLine( this.tabLines[this.currLine] ); } } else if ( header ) { var key = this.tabLines[this.currLine].match(/^([ACRFKLMNTQZ]\:)/g); switch( key[0] ) { case 'K:': var k = ABCXJS.parse.denormalizeAcc(header[0].trim().substr(2)); if( this.toClub ) { switch( k ) { case 'G': k = 'C'; break; case 'Am': k = 'Dm'; break; case 'C': k = 'F'; } } else if ( this.fromClub ) { switch( k ) { case 'C': k = 'G'; break; case 'Dm': k = 'Am'; break; case 'F': k = 'C'; } } header[0] = 'K:' + k; this.keyAcidentals = ABCXJS.parse.parseKeyVoice.standardKey(k); break; } this.addLine( header[0] ); } else { this.parseStaff(); } }; ABCXJS.Tab2Part.prototype.skipEmptyLines = function () { while(this.currLine < this.tabLines.length) { if( /*this.tabLines[this.currLine].charAt(0) !== '%' && */ this.tabLines[this.currLine].match(/^[\n\r\t]*$/) === null ) { return true; }; this.currLine++; } return false; }; ABCXJS.Tab2Part.prototype.addLine = function (ll) { this.abcText += ll + '\n'; }; ABCXJS.Tab2Part.prototype.parseStaff = function () { var staffs = this.idStaff(); if(!staffs){ this.addWarning('Linha Ínvalida: ['+(this.currLine+1)+'] --> "' + this.tabLines[this.currLine] + '"' ); this.hasErrors = true; return; } var st = 1; // 0 - fim; 1 - barra; 2 dados; - 1 para garantir a entrada var cnt = 1000; // limite de saida para o caso de erro de alinhamento do texto while( st > 0 && --cnt ) { this.posiciona(staffs); st = this.read(staffs); switch(st){ case 1: // incluir a barra na tablatura this.addBar(staffs, staffs[0].token.str ); break; case 2: if(staffs[0].token.type==='triplet'){ this.addTriplet(staffs, staffs[0].token.str); } else { this.addNotes(staffs); } break; } } if( ! cnt ) { this.addWarning('Não pude processar tablatura após 1000 ciclos. Possivel desalinhamento de texto.'); this.hasErrors = true; } }; ABCXJS.Tab2Part.prototype.addBar = function (staffs, bar ) { var startTreble = true; // neste caso, todas as vozes da staff são "bar", mesmo que algumas já terminaram this.addTabElem(bar + ' '); for( var i = 0; i < staffs.length; i ++ ) { if(staffs[i].st !== 'closed') { if(staffs[i].bass) { this.addBassElem(staffs[i].idBass, bar + ' '); } else { if( startTreble ) { this.addTrebleElem(bar + ' '); startTreble = false; } } this.setStaffState(staffs[i]); } } }; ABCXJS.Tab2Part.prototype.addTriplet = function ( staffs, triplet ) { if( triplet.charAt(0) === '(' ) { this.addTrebleElem(triplet + ' ' ); } this.addTabElem(triplet + ' ' ); for( var i = 0; i < staffs.length; i ++ ) { this.setStaffState(staffs[i]); } }; ABCXJS.Tab2Part.prototype.addNotes = function(staffs) { var str; var opening = true; var startTreble = true; var hasTreble = false; for( var i = 0; startTreble && i < staffs.length; i ++ ) { if(staffs[i].st === 'processing' && !staffs[i].bass ){ opening = staffs[i].open; startTreble = false; hasTreble = true; } } if( ! hasTreble ) { if( this.alertedBarNumber !== staffs[0].token.barNumber ) { this.addWarning( 'Compasso '+staffs[0].token.barNumber+': Pelo menos uma pausa deveria ser adicionada à melodia!.'); this.alertedBarNumber = staffs[0].token.barNumber; } } startTreble = true; //flavio - tratar duas notas ou mais de cada vez for( var i = 0; i < staffs.length; i ++ ) { if(staffs[i].st === 'processing' ) { if(staffs[i].bass ){ // para os baixos, sempre espero uma nota simples (sem colchetes) var note = this.handleBassNote(staffs[i].token.str); if( staffs[i].token.added && note.pitch !== "z" ) { str = ">"; } else { staffs[i].token.added = true; str = note.pitch; } this.addTabElem(str); if( staffs[i].token.afinal ) { var bas = this.checkBass(note.pitch, opening); if(!bas){ if( this.alertedBarNumber !== staffs[i].token.barNumber ) { this.addWarning("Compasso "+staffs[i].token.barNumber+": Baixo não encontrado ou não compatível com o movimento do fole."); this.alertedBarNumber = staffs[i].token.barNumber; } } this.addBassElem(staffs[i].idBass, staffs[i], bas ); this.setStaffState(staffs[i]); } } else { if(startTreble){ this.addTabElem(opening?"-":"+"); startTreble = false; } str = ""; for(var j = 0; j < staffs[i].token.aStr.length; j ++ ) { if( staffs[i].token.added && staffs[i].token.aStr[j] !== "z" ) { str += ">"; } else { str += this.toHex(staffs[i].token.aStr[j]); } } staffs[i].token.added = true; if(staffs[i].token.aStr.length > 1) { str = '['+str+']'; } if( (opening && staffs[i].open) || (!opening && !staffs[i].open) ) { if( this.ties.length > 0 ) { var t = this.ties.pop(); if( t !== str ) { this.ties.push(t); } else { str = ""; for(var j = 0; j < staffs[i].token.aStr.length; j ++ ) { str += ">"; } if(staffs[i].token.aStr.length > 1) { str = '['+str+']'; } } } else { if(staffs[i].token.lastChar.indexOf( '-' )>=0) { //staffs[i].token.lastChar = ''; this.ties.push(str); } } this.addTabElem(str); if( (this.trebleStaffs.open && this.trebleStaffs.open.token.afinal) || (this.trebleStaffs.close && this.trebleStaffs.close.token.afinal)){ this.addTrebleElem(staffs[i]); if( this.trebleStaffs.open ) { this.setStaffState(this.trebleStaffs.open); this.trebleStaffs.open.token.afinal = true; } if( this.trebleStaffs.close ) { this.setStaffState(this.trebleStaffs.close); this.trebleStaffs.close.token.afinal = true; } } } else { if( this.alertedBarNumber !== staffs[i].token.barNumber ) { this.addWarning( 'Compasso '+staffs[i].token.barNumber+': Não é possível ter ambos (abrindo e fechando) movimento de fole.'); this.alertedBarNumber = staffs[i].token.barNumber; } } } } } if( this.columnDuration && this.columnDuration.length ) { this.addTabElem(parseFloat(this.columnDuration)); } this.addTabElem(' '); }; ABCXJS.Tab2Part.prototype.addTabElem = function (el) { this.parsedLines[this.currStaff].tablature += el; }; ABCXJS.Tab2Part.prototype.handleBassNote = function (note) { var isChord = false, isMinor = false, isRest = false; if( "@XxZz".indexOf( note.charAt(0)) > 0 ){ isRest = true ; } if( note.charAt(note.length-1) === 'm' ){ isMinor = true; //note = note.slice(0,-1); } if( note === note.toLowerCase() ) { isChord = true; } return {pitch:note, isRest: isRest, isMinor:isMinor, isChord:isChord}; }; ABCXJS.Tab2Part.prototype.addBassElem = function (idx, el, bas ) { if(typeof( el ) === 'string' ) { this.parsedLines[this.currStaff].basses[idx] += el; } else { if( el.hasToken && el.token.afinal ) { var note = this.handleBassNote(el.token.str); var str; if( note.isRest ) { str = note.pitch; } else if( note.isChord ) { str = this.getChord(note.pitch, (bas.isMinor !==undefined? bas.isMinor : note.isMinor ) ); } else { str = this.getTabNote(note.pitch, this.bassOctave, true ); } str += this.handleDuration(el.token.duration*(this.inTriplet?2/3:1)) + (el.token.lastChar.indexOf( '-' ) >=0 ?"-":"") + (el.token.lastChar.indexOf( '.' ) >=0 ?"":" "); this.parsedLines[this.currStaff].basses[idx] += str; } } }; ABCXJS.Tab2Part.prototype.addTrebleElem = function (el) { var str; if(typeof( el ) === 'string' ) { this.parsedLines[this.currStaff].treble += el; } else { str = this.getPitch(el); str += this.handleDuration(el.token.duration) + (el.token.lastChar.indexOf( '-' ) >=0 ?"-":"") + (el.token.lastChar.indexOf( '.' ) >=0 ?"":" "); this.parsedLines[this.currStaff].treble += str; } }; ABCXJS.Tab2Part.prototype.handleDuration = function (nDur) { var cDur = ""; // para duration == 1 a saída é vazia. if ( nDur !== 1 ) { // diferente de 1 cDur = "" + nDur; if( nDur % 1 !== 0 ) { // não inteiro var resto = ""+(nDur-nDur%0.001); switch( resto ) { case '1.499': cDur = '3/2'; break; case '0.666': cDur = '2/3'; break; case '0.499': cDur = '/2'; break; case '0.333': cDur = '/3'; break; case '0.249': cDur = '/4'; break; case '0.166': cDur = '/6'; break; case '0.124': cDur = '/8'; break; } } } return cDur; }; ABCXJS.Tab2Part.prototype.getPitch = function (el) { var pp = ""; for( var i = 0; i < el.token.aStr.length; i++ ) { var p = el.token.aStr[i]; if (p !== 'z') { var b = this.getButton(p); if (b) { var n = el.open ? b.openNote : b.closeNote; p = this.getTabNote(n.key, n.octave, false); } } pp += p; } return el.token.aStr.length > 1 ? '['+pp+']' : pp; }; ABCXJS.Tab2Part.prototype.getChord = function ( pitch, isMinor ) { var p = ABCXJS.parse.normalizeAcc(pitch.toUpperCase().replace('M','')); var base = ABCXJS.parse.key2number[p]; if( !(base >= 0) ) { throw new Error("Acorde não identificado: " + p); } var n2 = base + (isMinor?3:4); var n3 = base + 7; var oct = this.bassOctave + 1; // flavio (base > 4 ? 0 : 1); return '[' + this.getTabNote( ABCXJS.parse.number2keysharp[base%12], oct, true ) + this.getTabNote( ABCXJS.parse.number2keysharp[n2%12], oct+Math.trunc(n2/12), true ) + this.getTabNote( ABCXJS.parse.number2keysharp[n3%12], oct+Math.trunc(n3/12), true ) + ']'; }; ABCXJS.Tab2Part.prototype.getTabNote = function (note, octave, bass) { var noteAcc = note.match(/[♯♭]/g); var n = noteAcc ? note.charAt(0) : note; var keyAcc = this.getKeyAccOffset(n); if (noteAcc && keyAcc === null ) { var newNote, noteAcc2, n2, keyAcc2, base = ABCXJS.parse.key2number[note]; if( noteAcc[0] === '♯' ) { newNote = ABCXJS.parse.number2keyflat[base%12]; } else { newNote = ABCXJS.parse.number2keysharp[base%12]; } noteAcc2 = newNote.match(/[♯♭]/g); n2 = newNote.charAt(0); keyAcc2 = this.getKeyAccOffset(n2); if( keyAcc2 ) { note = newNote; n = n2; keyAcc = keyAcc2; noteAcc = noteAcc2; } } if (noteAcc) { if ((noteAcc[0] === '♯' && keyAcc === 'sharp') || (noteAcc[0] === '♭' && keyAcc === 'flat')) { // anula o acidente - n já está correto } else { n = ((noteAcc[0] === '♯')?'^':'_') + n; //mantem o acidente da nota, convertendo para abc } } else if (keyAcc) { n = '=' + n; // naturaliza esta nota } if(bass){ if(noteAcc) { if( this.barBassAccidentals[ n ] ) { if(this.barBassAccidentals[ n ] === noteAcc[0]){ n = n.charAt(1); } } else { this.barBassAccidentals[ n.charAt(1) ] = noteAcc[0]; } } else { if( this.barBassAccidentals[ n ] ) { n = '=' + n; // naturaliza esta nota } } } else { if(noteAcc) { if( this.barAccidentals[ n ] ) { if(this.barAccidentals[ n ] === noteAcc[0]){ n = n.charAt(1); } } else { this.barAccidentals[ n.charAt(1) ] = noteAcc[0]; } } else { if( this.barAccidentals[ n ] ) { n = '=' + n; // naturaliza esta nota } } } var ret = n; if (octave < 4) { ret = n + Array(5 - octave).join(","); } else if (octave === 5) { ret = n.toLowerCase(); } else if (octave > 5) { ret = n.toLowerCase() + Array(octave - 4).join("'"); } return ret; }; ABCXJS.Tab2Part.prototype.setStaffState = function ( staff ) { staff.hasToken = false; staff.st = (staff.linhas[0].pos < this.tabLines[staff.linhas[0].l].length ? 'waiting for data' : 'closed'); }; ABCXJS.Tab2Part.prototype.idStaff = function () { // remover comentarios var p = [], i = -1, open = true, cntBasses = -1, maior=0, maiorLinha=0; this.endColumn = 0; this.startColumn = null; this.durationLine = null; this.columnDuration = null; this.trebleStaffs = { open: null, close: null}; this.parsedLines[++this.currStaff] = new ABCXJS.Tab2PartLine(); while(this.currLine < this.tabLines.length && this.tabLines[this.currLine].trim().length && this.startSyms.indexOf(this.tabLines[this.currLine].charAt(0)) >= 0 ) { var valid = true; switch( this.tabLines[this.currLine].charAt(0) ) { case '|': if( this.tabLines[this.currLine].match(/[ABCDFEGabcdefg]/) ){ p[++i] = { hasToken:false, bass:true, idBass: ++cntBasses, linhas: [{l:this.currLine, pos:0}], st:'waiting for data' }; this.parsedLines[this.currStaff].basses[cntBasses]=""; } else { open = !open; p[++i] = { hasToken:false, bass:false, open: open, linhas: [{l:this.currLine, pos:0}], st:'waiting for data' }; if(open) { this.trebleStaffs.open = p[i]; } else { this.trebleStaffs.close = p[i]; } } break; case '/': p[i].linhas.push({l:this.currLine, pos:0}); break; case '+': valid = false; this.durationLine = this.currLine; break; case 'f': valid = false; this.parsedLines[this.currStaff].fingeringLine = this.tabLines[this.currLine]; break; case '%': valid = false; // ignora comentario break; } if(valid && maior < this.tabLines[this.currLine].length ) { maior = this.tabLines[this.currLine].length; maiorLinha = this.currLine; } this.currLine++; } if(p.length===0) { return null; } // verifica o alinhamento das barras var k=0, l; while((l=(this.tabLines[maiorLinha].substr(k+1).indexOf("|")))>0) { k += l+1; for( var j = 0; j < p.length; j++ ) { var staff = p[j]; for( var i = 0; i < staff.linhas.length; i ++ ) { var l = this.tabLines[staff.linhas[i].l]; if( l.length > k && l.charAt(k) !== "|" ){ this.addWarning( 'Possível falta de sincronismo na pauta '+(this.currStaff+1)+', linha '+(j+1)+', coluna '+(k+1)+'. Barras desalinhadas.'); } } } } return p; }; ABCXJS.Tab2Part.prototype.posiciona = function(staffs) { var found = false; var qtd = 0; this.startColumn = this.endColumn; this.barEnding = false; // procura a primeira coluna vazia while( ! found ) { found = true; for( var j = 0; found && j < staffs.length; j++ ) { var staff = staffs[j]; qtd += staff.linhas.length; for( var i = 0; found && i < staff.linhas.length; i ++ ) { var l = this.tabLines[staff.linhas[i].l]; if( this.endColumn < l.length && this.spaces.indexOf( l.charAt(this.endColumn) ) < 0 ){ found = false; this.endColumn ++; } } } } // procura a primeira coluna não-vazia this.endColumn ++; found = false; while( ! found ) { for( var j = 0; !found && j < staffs.length; j++ ) { var staff = staffs[j]; qtd += staff.linhas.length; for( var i = 0; !found && i < staff.linhas.length; i ++ ) { var l = this.tabLines[staff.linhas[i].l]; if( this.endColumn >= l.length || this.spaces.indexOf( l.charAt(this.endColumn) ) < 0 ){ if(l.charAt(this.endColumn) && this.barSyms.indexOf( l.charAt(this.endColumn) ) >= 0){ this.barEnding = true; } found = true; } } } if(!found){ this.endColumn ++; } } if( this.durationLine && this.durationLine >= 0 ) { var dur = this.tabLines[this.durationLine].substr( this.startColumn,this.endColumn-this.startColumn).trim(); this.columnDuration = dur.length > 0 ? dur : ""; } }; ABCXJS.Tab2Part.prototype.read = function(staffs) { var st = 0, ret = 0; for( var j = 0; j < staffs.length; j ++ ) { var source = staffs[j]; switch( source.st ) { case "waiting for data": source.token = this.getToken(source); if( source.hasToken) { source.st = (source.token.type === "bar") ? "waiting end of interval" : "processing"; ret = (source.token.type === "bar") ? 1 : 2; } else { ret = 2; } break; case "waiting end of interval": ret = 1; break; case "closed": ret = 0; break; case "processing": this.updateToken(source); ret = 2; break; } st = Math.max(ret, st); } return st; }; ABCXJS.Tab2Part.prototype.getToken = function(staff) { var syms = "():|[]/"; var qtd = staff.linhas.length; var afinal = false; var type = null; var lastChar = ""; var tokens = []; var strToken = ""; this.skipSyms(staff, this.spaces ); for( var i = 0; i < qtd; i ++ ) { var token = ""; var ll = staff.linhas[i]; var found = false; while (ll.pos < Math.min( this.tabLines[ll.l].length, this.endColumn) && ! found ) { var c = this.tabLines[ll.l].charAt(ll.pos); if( c !== ' ' && c !== '.' && c !== '-' ) { token += c; ll.pos++; } else { if(syms.indexOf( token.charAt(0) ) >= 0 ) { for( var j = 1; j < qtd; j ++ ) { staff.linhas[j].pos = ll.pos; } qtd = 1; // força a saida processando so a primeira linha } else { lastChar += c; } found=true; } } if( token.trim().length > 0 ) { // gerar partitura convertendo para clubBR if( this.toClub && syms.indexOf( token.charAt(0) ) < 0 && token !== 'z' ) { if( staff.bass ) { // flavio - transpose bass switch(token) { case 'C': token = 'F'; break; case 'c': token = 'f'; break; case 'D': token = 'G'; break; case 'd': token = 'g'; break; case 'E': token = 'A'; break; case 'e': token = 'a'; break; case 'F': token = 'B♭'; break; case 'f': token = 'b♭'; break; case 'G': token = 'C'; break; case 'g': token = 'c'; break; case 'A': token = 'D'; break; case 'a': token = 'd'; break; case 'am': token = 'dm'; break; } } else { //move para o botão imediatamente abaixo var x = token.match(/^[0-9]*/g); var a = token.replace( x[0], '' ); token = (parseInt(x[0])+1) + a; } } if( this.fromClub && syms.indexOf( token.charAt(0) ) < 0 && token !== 'z' ) { if( staff.bass ) { // flavio - transpose bass switch(token) { case 'A': token = 'E'; break; case 'a': token = 'e'; break; case 'B♭': token = 'F'; break; case 'b♭': token = 'f'; break; case 'C': token = 'G'; break; case 'c': token = 'g'; break; case 'D': token = 'A'; break; case 'd': token = 'a'; break; case 'dm': token = 'am'; break; case 'F': token = 'C'; break; case 'f': token = 'c'; break; case 'G': token = 'D'; break; case 'g': token = 'd'; break; } } else { //move para o botão imediatamente abaixo var x = token.match(/^[0-9]*/g); var a = token.replace( x[0], '' ); token = (parseInt(x[0])-1) + a; } } tokens.push( token ); strToken += token; } var endingChar = this.tabLines[ll.l].charAt(this.endColumn); var endInSpace = this.spaces.indexOf( endingChar ) >= 0; if( this.barEnding || ll.pos >= this.tabLines[ll.l].length || !endInSpace ) { afinal = true; } } staff.hasToken = strToken.trim().length !== 0; //determina o tipo de token if( staff.hasToken ) { if( syms.indexOf( strToken.charAt(0) )>= 0 ) { if(strToken.charAt(0)=== '(' || strToken.charAt(0)=== ')' ) { type='triplet'; this.inTriplet = (strToken.charAt(0)=== '(' ); } else { type='bar'; this.barAccidentals = []; this.barBassAccidentals = []; this.updateBarNumberOnNextNote = true; } } else { type = 'note'; strToken = this.normalizeAcc(strToken); if( this.updateBarNumberOnNextNote ) { this.updateBarNumberOnNextNote = false; this.currBar ++; } if(tokens.length > 1) { strToken = '['+strToken+']'; } } } var dur = 1; if( this.columnDuration && this.columnDuration.length ) { dur = parseFloat(this.columnDuration); } return { str: strToken, aStr: tokens, duration: dur, barNumber: this.currBar, type:type, afinal: afinal, added: false, lastChar: lastChar }; }; ABCXJS.Tab2Part.prototype.normalizeAcc = function(str) { var ret = str.charAt(0); if(str.length > 1) { ret += str.substr(1).replace(new RegExp('#', 'g'),'♯').replace(new RegExp('b', 'g'),'♭'); } return ret; }; ABCXJS.Tab2Part.prototype.updateToken = function(staff) { var afinal = false; var qtd = staff.linhas.length; for( var i = 0; i < qtd; i ++ ) { var ll = staff.linhas[i]; if( this.barEnding || ll.pos >= this.tabLines[ll.l].length || this.spaces.indexOf( this.tabLines[ll.l].charAt(this.endColumn)) < 0 ) { afinal = true; } } var dur = 1; if( this.columnDuration && this.columnDuration.length ) { dur = parseFloat(this.columnDuration); } staff.token.duration += dur; if( afinal ){ staff.token.afinal = true; } }; ABCXJS.Tab2Part.prototype.skipSyms = function( staff, syms ) { for( var i = 0; i < staff.linhas.length; i ++ ) { while (staff.linhas[i].pos < Math.min( this.tabLines[staff.linhas[i].l].length, this.endColumn) && syms.indexOf(this.tabLines[staff.linhas[i].l].charAt(staff.linhas[i].pos)) >= 0) { staff.linhas[i].pos++ ; } } }; ABCXJS.Tab2Part.prototype.getButton = function( b ) { if( b === 'x' || b === ' ' || b === '' || !this.keyboard ) return null; var kb = this.keyboard; var p = parseInt( isNaN(b.substr(0,2)) || b.length === 1 ? 1 : 2 ); var button = b.substr(0, p) -1; var row = b.length - p; if(kb.keyMap[row][button]) return kb.keyMap[row][button]; return null; }; ABCXJS.Tab2Part.prototype.checkBass = function( b, opening ) { if( b === '-->' || !this.keyboard ) return false; if( b === 'z' ) return true; var kb = this.keyboard; var nota = kb.parseNote(b.replace("m", ":m"), true ); for( var j = kb.keyMap.length; j > kb.keyMap.length - 2; j-- ) { for( var i = 0; i < kb.keyMap[j-1].length; i++ ) { var tecla = kb.keyMap[j-1][i]; if( (opening && tecla.openNote.key === nota.key && nota.isMinor === tecla.openNote.isMinor ) || (!opening && tecla.closeNote.key === nota.key && nota.isMinor === tecla.closeNote.isMinor ) ) { return opening ? tecla.openNote: tecla.closeNote.key; } } } return false; // if(tecla.closeNote.key === nota.key && nota.isMinor === tecla.closeNote.isMinor ) return tecla; // if(tecla.openNote.key === nota.key && nota.isMinor === tecla.openNote.isMinor ) return tecla; }; ABCXJS.Tab2Part.prototype.toHex = function( s ) { if( s === 'z' || s === '>') return s; var p = s.indexOf( '\'' ); var s1 = s.substr( 0, p ); var s2 = s.substr( p ); return ( p < 0 ) ? parseInt(s).toString(16) : parseInt(s1).toString(16) + s2; }; ABCXJS.Tab2Part.prototype.getKeyAccOffset = function(note) // recupera os acidentes da clave e retorna um offset no modelo cromatico { for( var a = 0; a < this.keyAcidentals.length; a ++) { if( this.keyAcidentals[a].note.toLowerCase() === note.toLowerCase() ) { return this.keyAcidentals[a].acc; } } return null; }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function toDecimalNote(str) { var r; switch (str) { case '>': r = ' '; // flavio break; case 'z': r = 'z'; break; default: r = parseInt(str, 16); } return r; }; function regexp_match(str,re) { var m, n=[]; while ((m = re.exec(str)) !== null) { n.push(m); if (m.index === re.lastIndex) { re.lastIndex++; } } return n; } ; // left padding s with c to a total of n chars function lpad(s, c, n) { if (! s || ! c || s.length >= n) { return s; } var max = (n - s.length)/c.length; for (var i = 0; i < max; i++) { s = c + s; } return s; } // right padding s with c to a total of n chars function rpad(s, c, n) { if (! s || ! c || s.length >= n) { return s; } var max = (n - s.length)/c.length; for (var i = 0; i < max; i++) { s += c; } return s; } if (!window.ABCXJS) window.ABCXJS = {}; ABCXJS.Part2TabLine = function () { this.basses = ""; this.sparring = ""; this.close = [""]; this.open = [""]; this.duration =""; this.pos = 0; }; ABCXJS.Part2Tab = function () { this.validBars = { "|" : "bar_thin" , "||" : "bar_thin_thin" , "[|" : "bar_thick_thin" , "|]" : "bar_thin_thick" , ":|:" : "bar_dbl_repeat" , ":||:": "bar_dbl_repeat" , "::" : "bar_dbl_repeat" , "|:" : "bar_left_repeat" , "||:" : "bar_left_repeat" , "[|:" : "bar_left_repeat" , ":|" : "bar_right_repeat" , ":||" : "bar_right_repeat" , ":|]" : "bar_right_repeat" }; this.validBasses = 'abcdefgABCDEFGz>+-'; this.startSyms = "[|:"; this.spaces = "\ \t"; this.init(); this.addWarning = function ( msg ) { this.warnings.push(msg); }; this.getWarnings = function () { return this.warnings.join('<br>'); }; }; ABCXJS.Part2Tab.prototype.init = function () { this.partText; this.partLines; this.parsedLines = []; this.currLine = 0; this.tabText = ""; this.currBar = 0; this.warnings = []; this.inTab = false; this.inTreble = false; this.trebleVoice = ""; this.fingerLine = []; this.lastParsed = { notes: undefined, tabLine: undefined }; this.finalTabLines = []; }; ABCXJS.Part2Tab.prototype.parse = function (text, keyboard ) { this.init(); this.partText = text; this.partLines = this.extractLines(); this.keyboard = keyboard; this.hasErrors = false; this.title = undefined; while((!this.hasErrors) && this.currLine < this.partLines.length) { if( this.skipEmptyLines() ) { this.parseLine(); this.currLine++; } } // each parsed line is stored in finalTabLines array var tabL = this.finalTabLines; for(var t =0; t < tabL.length; t++ ) { this.addLine( tabL[t].basses); for( var r =0; r <tabL[t].close.length; r++){ this.addLine( tabL[t].close[r]); } for( var r =0; r <tabL[t].open.length; r++){ this.addLine( tabL[t].open[r]); } this.addLine( tabL[t].duration ); if( this.fingerLine[t] && this.fingerLine[t] !== "" ) { this.addLine( this.fingerLine[t]+'\n'); } else { this.addLine( '\n' ); } } return this.tabText; }; ABCXJS.Part2Tab.prototype.extractLines = function () { var v = this.partText.split('\n'); v.forEach( function(linha, i) { var l = linha.split('%'); v[i] = l[0].trim(); } ); return v; }; ABCXJS.Part2Tab.prototype.parseLine = function () { //var header = lines[l].match(/^([CKLMT]\:*[^\r\n\t]*)/g); - assim não remove comentarios var header = this.partLines[this.currLine].match(/^([ACFKLMNTQVZ]\:*[^\r\n\t\%]*)/g); if( header ) { var key = this.partLines[this.currLine].match(/^([ACFKLMNTQVZ]\:)/g); switch( key[0] ) { case 'V:': var a = (header[0].match(/accordionTab/g) !== null); var b = (header[0].match(/bass/g) !== null); var t = (header[0].match(/treble/g) !== null); this.inTab = a; this.inTreble = t || ! (a || b); if( this.inTreble ) { var v = this.partLines[this.currLine].match(/^(V:\S.)/); this.trebleVoice = v[0].trim(); } break; case 'T:': if(!this.title) this.title = ABCXJS.parse.denormalizeAcc(header[0].trim().substr(2)); break; case 'K:': var k = ABCXJS.parse.denormalizeAcc(header[0].trim().substr(2)); header[0] = 'K:' + k; this.keyAcidentals = ABCXJS.parse.parseKeyVoice.standardKey(k); break; } if(key[0] !== 'V:' ) { this.addLine( header[0] ); } } else { if( this.inTab ) { //Salva as linhas para inserção ao final - há relações inter linhas this.finalTabLines.push( this.parseTab() ); } else { var v = this.partLines[this.currLine].match(/\[(V:\S)\]/); var f = (this.partLines[this.currLine].match(/^(f\:)/g) !== null); var w = (this.partLines[this.currLine].match(/^(w\:)/g) !== null); if( v ) this.inTreble = ( this.trebleVoice !== "" && v[1] === this.trebleVoice ); if( this.inTreble ) { if( f ) this.fingerLine[this.fingerLine.length-1] = this.partLines[this.currLine]; else if( ! w ) this.fingerLine.push(""); } } } }; ABCXJS.Part2Tab.prototype.parseTab = function () { var line = { str:this.partLines[this.currLine], posi:0, pos:0, tokenType:1,currToken:''}; var tabline = new ABCXJS.Part2TabLine(); if( line.length === 0 ) { this.hasErrors = true; return; } var cnt = 1000; // limite de saida para o caso de erro de alinhamento do texto while( line.tokenType > 0 && --cnt ) { this.getToken(line, tabline); switch(line.tokenType){ case 1: // bar this.addBar(tabline, line.currToken); break; case 2: // note this.addNotes(tabline, line); break; case 3: // triplet this.addTriplet(tabline, line); break; } } if( line.tokenType < 0 ) { this.addWarning('Encontrados símbolos inválidos na linha ('+(this.currLine+1)+','+(line.posi+1)+') .'); this.hasErrors = true; } if( ! cnt ) { this.addWarning('Não pude processar tablatura após 1000 ciclos. Possivel desalinhamento de texto.'); this.hasErrors = true; } return tabline; }; ABCXJS.Part2Tab.prototype.addBar = function (tabline, token) { var l = token.length; tabline.basses += token + ' '; for(var r=0; r < tabline.close.length; r++){ tabline.close[r] += token + ' '; } for(var r=0; r < tabline.open.length; r++){ tabline.open[r] += token + ' '; } if(tabline.pos===0){ tabline.sparring += '/' + rpad( ' ', ' ', l); tabline.duration = '+' + rpad( ' ', ' ', l); } else { tabline.sparring += token + ' '; tabline.duration += rpad( ' ', ' ', l+1); } tabline.pos +=( l+1); }; ABCXJS.Part2Tab.prototype.addTriplet = function(tabline, line) { var l = line.currToken.length+1; tabline.basses += line.currToken + ' '; for(var r=0; r < tabline.open.length; r++){ tabline.open[r] += line.currToken + ' '; } for(var r=0; r < tabline.close.length; r++){ tabline.close[r] += line.currToken + ' '; } tabline.sparring += rpad( ' ', ' ', l); tabline.duration += rpad( ' ', ' ', l); tabline.pos += l; }; ABCXJS.Part2Tab.prototype.addNotes = function(tabline, line) { var parsedNotes = line.parsedNotes; if( parsedNotes.empty && (line.parsedNotes.bas.trim().length === 0 || line.parsedNotes.currBar !== this.lastParsed.notes.currBar )) { this.lastParsed.notes.currBar = line.parsedNotes.currBar; var lastNotes = this.lastParsed.notes.notes; var lastTabline = this.lastParsed.tabLine; if(parsedNotes.closing) { var i = lastTabline.close[0].lastIndexOf( lastNotes[0] ) + this.lastParsed.notes.maxL; for(var r=0; r < lastTabline.close.length; r++){ var str = lastTabline.close[r]; if(r<parsedNotes.notes.length) { var n = str.lastIndexOf(lastNotes[r]); lastTabline.close[r] = str.slice(0, n) + str.slice(n).replace(lastNotes[r],lastNotes[r]+'-'); } else { lastTabline.close[r] = str.slice(0, i) +' '+ str.slice(i); } } for(var r=0; r < lastTabline.open.length; r++){ var str = lastTabline.open[r]; lastTabline.open[r] = str.slice(0, i) +' '+ str.slice(i); } } else { var i = lastTabline.open[0].lastIndexOf( lastNotes[0] ) + this.lastParsed.notes.maxL; for(var r=0; r < lastTabline.open.length; r++){ var str = lastTabline.open[r]; if(r<parsedNotes.notes.length) { var n = str.lastIndexOf(lastNotes[r]); lastTabline.open[r] = str.slice(0, n) + str.slice(n).replace(lastNotes[r],lastNotes[r]+'-'); } else { lastTabline.open[r] = str.slice(0, i) +' '+ str.slice(i); } } for(var r=0; r < lastTabline.close.length; r++){ var str = lastTabline.close[r]; lastTabline.close[r] = str.slice(0, i) +' '+ str.slice(i); } } lastTabline.duration = lastTabline.duration.slice(0, i) +' '+ lastTabline.duration.slice(i); lastTabline.sparring = lastTabline.sparring.slice(0, i) +' '+ lastTabline.sparring.slice(i); lastTabline.basses = lastTabline.basses.slice(0, i) +' '+ lastTabline.basses.slice(i); line.parsedNotes = window.ABCXJS.parse.clone(this.lastParsed.notes); parsedNotes.notes = lastNotes; parsedNotes.maxL = Math.max( parsedNotes.maxL, this.lastParsed.notes.maxL ); } var l = parsedNotes.maxL+1; tabline.basses += parsedNotes.bas+ rpad( ' ', ' ', l-parsedNotes.bas.length); if( parsedNotes.closing) { while (tabline.close.length < parsedNotes.notes.length) { tabline.close.push(window.ABCXJS.parse.clone(tabline.sparring) ); } for(var r=0; r < tabline.close.length; r++){ if(r<parsedNotes.notes.length) { tabline.close[r] += parsedNotes.notes[r] + rpad( ' ', ' ', l-parsedNotes.notes[r].length); } else { tabline.close[r] += rpad( ' ', ' ', l); } } for(var r=0; r < tabline.open.length; r++){ tabline.open[r] += rpad( ' ', ' ', l); } } else { while (tabline.open.length < parsedNotes.notes.length) { tabline.open.push(window.ABCXJS.parse.clone(tabline.sparring) ); } for(var r=0; r < tabline.open.length; r++){ if(r<parsedNotes.notes.length) { tabline.open[r] += parsedNotes.notes[r] + rpad( ' ', ' ', l-parsedNotes.notes[r].length); } else { tabline.open[r] += rpad( ' ', ' ', l); } } for(var r=0; r < tabline.close.length; r++){ tabline.close[r] += rpad( ' ', ' ', l); } } tabline.sparring += rpad( ' ', ' ', l); if( parsedNotes.duration === "1" || parsedNotes.duration === "") { tabline.duration += rpad( ' ', ' ', l); } else { tabline.duration += parsedNotes.duration + rpad( ' ', ' ', l-parsedNotes.duration.length); } tabline.pos += l; }; ABCXJS.Part2Tab.prototype.getNotes = function (strBass, strNote, closing) { var t, n = [], d, nn, b, l = 0; //parse do baixo b = strBass.match(/(A|B|C|D|E|F|G|z|>)[(♭|♯|m)]{0,1}/gi); if (b.length < 1) { return null; } else { b[0] = b[0]=== '>' ? ' ': b[0]; // flavio l = Math.max(l, b[0].length); } //multiplas notas? t = regexp_match(strNote, /\[(.*?)\](\d{0,1}[\.|\/]{0,1}\d{0,2})/gi); if (t.length === 1) { d = t[0][2]; l = Math.max(l, d.length); nn = regexp_match(t[0][1], /(\>|z|[a-f]|[0-9])(\'{0,})/gi); nn.forEach(function (e) { var v = toDecimalNote(e[1]) + e[2]; n.push(v); l = Math.max(l, v.length); }); } else { //nota única e duração t = regexp_match(strNote, /(\>|z|[a-f]|[0-9])(\'{0,})(\d{0,1}[\.|\/]{0,1}\d{0,2})/gi); if (t.length === 1) { n.push(toDecimalNote(t[0][1]) + t[0][2]); l = Math.max(l, n[0].length); d = t[0][3]; l = Math.max(l, d.length); } else { return null; } } var pn = {bas: b[0], notes: n, duration: d, closing: closing, maxL: l, currBar: this.currBar, empty:false }; var checkEmpty = ' '; //pn.bas; pn.notes.forEach( function(e) { checkEmpty+=e;}); if( checkEmpty.trim().length === 0 ) { pn.empty = true; } return pn; }; ABCXJS.Part2Tab.prototype.parseNotes = function( token) { var v, notes, closing = false; //padroniza sintaxe quando o baixo inexistente significa pausa. if( token.charAt(0) === '+' || token.charAt(0) === '-') { token = 'z' + token; } if( token.indexOf('+') > 0 ){ v = token.split('+'); closing = true; } if( token.indexOf('-') > 0 ){ v = token.split('-'); } if( ! v ) return null; notes = this.getNotes(v[0],v[1], closing); return notes; }; ABCXJS.Part2Tab.prototype.getToken = function(line, tabline ) { var found = false; var c = ''; this.skipSyms(line, this.spaces ); line.currToken = ''; line.tokenType = 0; line.posi = line.pos; while ( line.pos < line.str.length && ! found ) { c = line.str.charAt(line.pos); if(c===' ') { found=true; continue; } if( line.tokenType === 0 ) { if( this.validBars[ c ] ) { line.tokenType = 1; // bar } else if(this.validBasses.indexOf( c )>=0) { line.tokenType = 2; // note } else if(c==="(" || c===")" ) { line.tokenType = 3; } else if(this.startSyms.indexOf( c )<0) { line.tokenType = -1; } } else { switch(line.tokenType) { case 1: if(!c.match(/(\||\d|\:|\])/g)) { found=true; continue; } break; case 2: case 3: if(c.match(/(\||\:)/g)){ found=true; continue; } break; } } line.currToken += c; line.pos ++; if( line.tokenType === 1 ) { this.currBar++; } } if(found && line.tokenType===2) { if( line.parsedNotes !== undefined && ! line.parsedNotes.empty ) { this.lastParsed.notes = line.parsedNotes; this.lastParsed.tabLine = tabline; } line.parsedNotes = this.parseNotes( line.currToken ) ; if( line.parsedNotes === null ) { line.tokenType=-1; } } }; ABCXJS.Part2Tab.prototype.skipSyms = function( linha, syms ) { while (linha.pos < linha.str.length && syms.indexOf(linha.str.charAt(linha.pos)) >= 0) { linha.pos++ ; } }; ABCXJS.Part2Tab.prototype.skipEmptyLines = function () { while(this.currLine < this.partLines.length) { if( this.partLines[this.currLine].charAt(0) !== '%' && this.partLines[this.currLine].match(/^[\s\r\t]*$/) === null ) { return true; }; this.currLine++; } return false; }; ABCXJS.Part2Tab.prototype.addLine = function (ll) { this.tabText += ll + '\n'; }; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ if (!window.SITE) window.SITE = {}; SITE.Repertorio = function() { this.accordion = new window.ABCXJS.tablature.Accordion({ accordionMaps: DIATONIC.map.accordionMaps ,translator: SITE.translator ,render_keyboard_opts:{ transpose:true ,mirror:false ,scale:1 ,draggable:false ,show:true ,label:false } }, SITE.properties.options.tabFormat); }; // Esta rotina foi criada como forma de verificar todos warnings de compilacao do repertório SITE.Repertorio.prototype.compileAll = function() { for(var a = 0; a <this.accordion.accordions.length; a ++ ) { this.accordion.load( a ); var abcParser = new ABCXJS.parse.Parse( null, this.accordion ); var midiParser = new ABCXJS.midi.Parse(); waterbug.log(this.accordion.loaded.id); for (var title in this.accordion.loaded.songs.items ) { waterbug.log(title); console.log(title); abcParser.parse( this.accordion.loaded.songs.items[title] ); var w = abcParser.getWarnings() || []; var l = w.length; for (var j=0; j<w.length; j++) { waterbug.logError( ' ' + w[j]); console.log( ' ' + w[j]); } var tune = abcParser.getTune(); midiParser.parse( tune, this.accordion.loadedKeyboard ); var w = midiParser.getWarnings(); l += w.length; for (var j=0; j<w.length; j++) { waterbug.logError( ' ' + w[j]); console.log( ' ' + w[j]); } waterbug.log(l > 0 ? '': '--> OK' ); console.log(l > 0 ? '': '--> OK' ); waterbug.log( '' ); console.log(''); } } waterbug.show(); }; // gerar repertório indexado SITE.Repertorio.prototype.geraIndex = function( map ) { var lista = null; var club = false; var repertorio = { geral: [], transportada: [], corona: [], portuguesa: [] }; for(var a = 0; a < this.accordion.accordions.length; a ++ ) { this.accordion.load( a ); //var abcParser = new ABCXJS.parse.Parse( null, accordion ); club = false; switch(this.accordion.loaded.id) { case 'GAITA_HOHNER_CLUB_IIIM_BR': club = true; case 'GAITA_MINUANO_GC': lista = repertorio.geral; break; case 'GAITA_HOHNER_CORONA_SERIES': lista = repertorio.corona; break; case 'CONCERTINA_PORTUGUESA': lista = repertorio.portuguesa; break; case 'GAITA_MINUANO_BC_TRANSPORTADA': lista = repertorio.transportada; break; } for (var t in this.accordion.loaded.songs.items ) { if( this.accordion.loaded.songs.details[t].hidden ) { continue; //não mostra itens hidden } var title = t.replace( '(corona)', '' ) .replace( '(club)', '' ) .replace( '(transportada)', '' ) .replace( '(portuguesa)', '' ).trim(); var composer = this.accordion.loaded.songs.details[t].composer; var id = this.accordion.loaded.songs.details[t].id; if( ! club ) { lista.push ( {title:title, composer:composer, geral: id, club: 0 } ); } else { var idx = -1, l = 0; while( idx === -1 && l < lista.length ) { if( lista[l].title === title ) idx = l; l ++; } if( idx !== -1 ) { lista[idx].club = id; } else { lista.push ( {title:title, composer:composer, geral: 0, club: id } ); } } } } var ordenador = function(a,b) { if (a.title < b.title) return -1; if ( a.title > b.title) return 1; return 0; }; repertorio.geral.sort( ordenador ); repertorio.transportada.sort( ordenador ); repertorio.corona.sort( ordenador ); repertorio.portuguesa.sort( ordenador ); var h = '\ <html>\n\ <head>\n\ <title>Mapa para Acordões Diatônicos - Repertório Indexado</title>\n\ <meta charset="UTF-8">\n\ <meta name="robots" content="index,follow">\n\ <meta name="revisit-after" content="7 days">\n\ <meta name="keywords" content="diatonic accordion, notation, learning, practice, repertoire, abc tunes, midi, tablature \ acordeão diatônico, gaita de oito baixos, gaita ponto, notação musical, aprendizagem, prática, repertorio, notação abc, tablatura ">\n\ <style>\n\ h1 {font-family: Arial; font-size: 40px; line-height:10x; margin:3px; }\n\ h2 {font-family: Arial; font-size: 30px; line-height:10x; margin:3px; }\n\ h3 {font-family: Arial; font-size: 20px; line-height:10x; margin:3px; }\n\ p {font-family: Arial; font-size: 15px; line-height:10x; margin:3px; margin-bottom: 10px; }\n\ .credit {font-style: italic; }\n\ .destaque {font-style: italic; font-weight: bold;}\n\ table.interna {border-collapse: collapse; width:calc(100% - 10px); min-width:'+(map?450:650)+'px; max-width:1024px; margin:3px; }\n\ table.interna tr {font-family: Arial; background: #dfdfdf;}\n\ table.interna tr:nth-child(even) { background-color: #c0c0c0; }\n\ table.interna th {background: blue; color: white; text-align: left; padding: 3px;}\n\ table.interna td {text-align: left; padding: 3px;}\n\ table.interna img { width: 40px;}\n\ table.interna .center {text-align: center;}\n\ table.interna .title {font-weight:bold;}\n\ table.interna .composer {font-style:italic;}\n\ table.interna .abc_link { color: black; text-decoration: none; } \n\ table.interna .abc_link:hover { color: blue; text-decoration: none; }\n\ </style>\n\ </head>\n\ <body>\n\ <br>\n'; if( ! map ) { h += '\ <h1>Mapa para Acordões Diatônicos</h1>\n\ <p class="credit">Desenvolvido por: <span class="destaque">Flávio Vani</span>\n\ <br>Coordenação musical: <span class="destaque">prof. <NAME></span></p>\n\ <p>Esta página apresenta, em ordem alfabética, todo o repertório do site. O site é composto de partituras para acordeão diatônico com \n\ tablaturas.</p>\n\ <p><span class="destaque">Nota: </span>Clique no checkmark verde (à direita) para abrir o site na partitura com o acordeão selecionado.</p>\n\ '; } h += '<h2>Repertório Geral</h2>\n\ <h3>Tablaturas para acordeão G/C e/ou Club IIIM</h3>\n\ <table class="interna"><tr><th>Título</th>'+(map?'':'<th>Autor(es)</th>')+'<th class="center">G/C</th><th class="center">C/F Club(br)</th></tr>\n\ '; for( var r = 0; r < repertorio.geral.length; r ++ ) { // h += '<tr'+( ( r & 1) ? ' class="par"': '' ) +'>' h += '<tr>' +'<td class="title" >'+repertorio.geral[r].title+'</td>' + (map? '\n': '<td class="composer" >'+repertorio.geral[r].composer+'</td>\n' ) +'<td class="center">' + this.makeAnchor( map, 'GAITA_MINUANO_GC', repertorio.geral[r].geral ) +'</td>\n<td class="center">' + this.makeAnchor( map, 'GAITA_HOHNER_CLUB_IIIM_BR', repertorio.geral[r].club ) +'</td></tr>\n'; } h += '\ </table>\n\ <br><h2>Transportada</h2>\n\ <h3>Tablaturas para acordeão Transportado</h3>\n\ <table class="interna"><tr><th>Título</th>'+(map?'':'<th>Autor(es)</th>')+'<th class="center">B/C</th></tr>\n\ '; for( var r = 0; r < repertorio.transportada.length; r ++ ) { // h += '<tr'+( ( r & 1) ? ' class="par"': '' ) +'>' h += '<tr>' +'<td class="title" >'+repertorio.transportada[r].title+'</td>' + (map? '\n': '<td class="composer" >'+repertorio.transportada[r].composer+'</td>\n') +'<td class="center">' + this.makeAnchor( map, 'GAITA_MINUANO_BC_TRANSPORTADA', repertorio.transportada[r].geral ) +'</td></tr>\n'; } h += '\ </table>\n\ <br><h2>Portuguesa</h2>\n\ <h3>Tablaturas para Concertina Portuguesa em sistema diatônico italiano </h3>\n\ <table class="interna"><tr><th>Título</th>'+(map?'':'<th>Autor(es)</th>')+'<th class="center">G/C/F</th></tr>\n\ '; for( var r = 0; r < repertorio.portuguesa.length; r ++ ) { // h += '<tr'+( ( r & 1) ? ' class="par"': '' ) +'>' h += '<tr>' +'<td class="title" >'+repertorio.portuguesa[r].title+'</td>' + (map? '\n': '<td class="composer" >'+repertorio.portuguesa[r].composer+'</td>\n') +'<td class="center">' + this.makeAnchor( map, 'CONCERTINA_PORTUGUESA', repertorio.portuguesa[r].geral ) +'</td></tr>\n'; } h += '\ </table>\n\ <br><h2>Corona</h2>\n\ <h3>Tablaturas para acordeões Corona Series A/D/G</h3>\n\ <table class="interna"><tr><th>Título</th>'+(map?'':'<th>Autor(es)</th>')+'<th class="center">A/D/G</th></tr>\n\ '; for( var r = 0; r < repertorio.corona.length; r ++ ) { // h += '<tr'+( ( r & 1) ? ' class="par"': '' ) +'>' h += '<tr>' +'<td class="title" >'+repertorio.corona[r].title+'</td>' + (map? '\n': '<td class="composer" >'+repertorio.corona[r].composer+'</td>\n') +'<td class="center">' + this.makeAnchor( map, 'GAITA_HOHNER_CORONA_SERIES', repertorio.corona[r].geral ) +'</td></tr>\n'; } h += '\ </table>\n\ <br>\n\ </body>\n\ </html>\n\ '; if( map ){ var novo = ! this.win; if( novo ) { this.win = new DRAGGABLE.ui.Window( map.mapDiv , null , {translator: SITE.translator, statusbar: false, draggable: true, top: "10px", left: "800px", width: 'auto', height: "80%", title: 'IDXREPERTOIRE'} , null ); this.win.dataDiv.className = "draggableData"; } this.win.setVisible(true); this.win.dataDiv.innerHTML = h; var ps = new PerfectScrollbar( this.win.dataDiv, { handlers: ['click-rail', 'drag-thumb', 'keyboard', 'wheel', 'touch'], wheelSpeed: 1, wheelPropagation: false, suppressScrollX: false, minScrollbarLength: 100, swipeEasing: true, scrollingThreshold: 500 }); if(novo) { var x = window.innerWidth - this.win.topDiv.clientWidth - 12; this.win.topDiv.style.left = (x<0?0:x) + 'px'; } this.bindSongs(this.win.dataDiv, map ); } else { FILEMANAGER.download( 'repertorio.indexado.pt_BR.html', h ); } }; SITE.Repertorio.prototype.makeAnchor = function( map, accordionId, songId ) { var path = '/'; var anchor = '<img alt="nao" src="/images/nao.png" >'; if( songId > 0 ) { if( map ) { anchor = '<img alt="sim" src="/images/sim.png" data-song="'+accordionId+'#'+songId+'" >'; } else { anchor = '<a href="'+path+'?accordion='+accordionId+'&id=' +songId+'"><img alt="sim" src="/images/sim.png" ></a>'; } } return anchor; }; SITE.Repertorio.prototype.bindSongs = function( container, map ) { var clickMe = function (e, item) { e.stopPropagation(); e.preventDefault(); var data = item.getAttribute("data-song").split("#"); map.setup( {accordionId: data[0], songId: data[1] } ); }; var songs = container.querySelectorAll('[data-song]'); var songsArray = Array.prototype.slice.apply(songs); for( var i=0; i < songsArray.length; i ++ ) { var item = songsArray[i]; item.addEventListener('touchstart', function (e) { clickMe( e, this ); } ); item.addEventListener('mouseover', function (e) { this.style.cursor='pointer'; } ); item.addEventListener('click', function (e) { clickMe( e, this ); } ); } };
<gh_stars>1-10 package procesamientoOrdenes; import javax.swing.*; public class Main { public static void main(String[] args){ SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new View(); frame.setSize(1400,600); frame.setVisible(true); } }); Runnable runnableReceiver = new MessageReceiver(); // or an anonymous class, or lambda... Thread thread = new Thread(runnableReceiver); thread.start(); } }
class Queue: def __init__(self): self.queue = [] def enqueue(self, data): self.queue.append(data) def dequeue(self): if len(self.queue) == 0: print("Queue empty") else: element = self.queue[0] del self.queue[0] return element def peek(self): return self.queue[0] def size(self): return len(self.queue)
<gh_stars>0 # Be sure to restart your server when you modify this file. DeviseExample::Application.config.session_store :cookie_store, key: '_devise_example_session'
# views.py from django.shortcuts import render from .models import Item # Assuming there is a model named Item def home_view(request): items = Item.objects.all() # Retrieve all items from the database return render(request, 'home.html', {'items': items}) # urls.py from django.urls import path from .views import home_view urlpatterns = [ path('home/', home_view, name='home'), ]
# Sample usage of the Game class # Create a game instance game = Game(player_one_position=0, player_two_position=0, max_score=10, player_one_score=0, player_two_score=0) # Move players and update scores game.move_player_one(3) game.move_player_two(2) game.move_player_one(8) game.move_player_two(5) # Get player positions and scores player_positions = game.get_player_positions() player_scores = game.get_player_scores() print("Player positions:", player_positions) # Output: (11, 7) print("Player scores:", player_scores) # Output: (1, 1)
/* * Copyright 2013-2016 iNeunet OpenSource and the original author or 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 com.ineunet.knife.qlmap.criteria; /** * * @author Hilbert * * @since 1.2.0 * */ class CriteriaUtils { /** * e.g. userName to user_name * Transform field name to sql column.<br> * (TODO merge. Same function method is ClassStrUtils.hump2Underline) * e.g. userName to user_name * @param propName propName * @return prop_name */ public static String propToColumn(String propName) { char[] arr = propName.toCharArray(); for(int i = 0; i < arr.length; i++) { if(Character.isUpperCase(arr[i])) { String s1 = propName.substring(0, i); String s = "_" + Character.toLowerCase(arr[i]); String s2 = propName.substring(i+1); return propToColumn(s1 + s + s2); } } return propName; } }
<filename>src/com/github/teocci/camera/console/util/Debug.java<gh_stars>0 package com.github.teocci.camera.console.util; /** * Created by teocci. * * @author <EMAIL> on 2017-May-19 */ public class Debug { public static int DEBUG = 1; public static void log(String msg) { if ( DEBUG == 1 ) { System.out.println(msg); } } public static void log(Object msg) { if ( DEBUG == 1 ) { System.out.println(msg); } } public static void err(Object err) { if ( DEBUG == 1 ) { System.out.println(err); } } public static void err(Exception e) { if (DEBUG == 1) { e.printStackTrace(); } } }
import { GetterTree } from "vuex" import { StateInterface } from "../index" import { NoteStateInterface } from "./state" const getters: GetterTree<NoteStateInterface, StateInterface> = {} export default getters
require File.expand_path('../../../../spec_helper', __FILE__) require File.expand_path('../../fixtures/classes', __FILE__) describe "UDPSocket.send" do before :each do @port = nil @server_thread = Thread.new do @server = UDPSocket.open begin @server.bind(nil, 0) @port = @server.addr[1] begin @msg = @server.recvfrom_nonblock(64) rescue IO::WaitReadable IO.select([@server]) retry end ensure @server.close if !@server.closed? end end Thread.pass while @server_thread.status and !@port end after :each do @server_thread.join end it "sends data in ad hoc mode" do @socket = UDPSocket.open @socket.send("ad hoc", 0, SocketSpecs.hostname, @port) @socket.close @server_thread.join @msg[0].should == "ad hoc" @msg[1][0].should == "AF_INET" @msg[1][1].should be_kind_of(Fixnum) @msg[1][3].should == "127.0.0.1" end it "sends data in ad hoc mode (with port given as a String)" do @socket = UDPSocket.open @socket.send("ad hoc", 0, SocketSpecs.hostname, @port.to_s) @socket.close @server_thread.join @msg[0].should == "ad hoc" @msg[1][0].should == "AF_INET" @msg[1][1].should be_kind_of(Fixnum) @msg[1][3].should == "127.0.0.1" end it "sends data in connection mode" do @socket = UDPSocket.open @socket.connect(SocketSpecs.hostname, @port) @socket.send("connection-based", 0) @socket.close @server_thread.join @msg[0].should == "connection-based" @msg[1][0].should == "AF_INET" @msg[1][1].should be_kind_of(Fixnum) @msg[1][3].should == "127.0.0.1" end it "raises EMSGSIZE if data is too too big" do @socket = UDPSocket.open begin lambda do @socket.send('1' * 100_000, 0, SocketSpecs.hostname, @port.to_s) end.should raise_error(Errno::EMSGSIZE) ensure @socket.send("ad hoc", 0, SocketSpecs.hostname, @port) @socket.close @server_thread.join end end end
namespace PrestaShop\Module\AutoUpgrade\TaskRunner\Rollback; use PrestaShop\Module\AutoUpgrade\TaskRunner\ChainedTasks; class RollbackTaskQueue { private $tasks; public function __construct() { $this->tasks = new \SplQueue(); } public function addTask($task) { $this->tasks->enqueue($task); } public function removeTask() { $this->tasks->dequeue(); } public function executeTask() { if (!$this->tasks->isEmpty()) { $task = $this->tasks->dequeue(); $task->execute(); } else { throw new \RuntimeException('No tasks in the queue to execute.'); } } }
#!/usr/bin/env bash set -e # Get the version from the environment, or try to figure it out. if [ -z $VERSION ]; then VERSION=$(awk -F\" 'TMCoreSemVer =/ { print $2; exit }' < version/version.go) fi if [ -z "$VERSION" ]; then echo "Please specify a version." exit 1 fi echo "==> Releasing version $VERSION..." # Get the parent directory of where this script is. SOURCE="${BASH_SOURCE[0]}" while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done DIR="$( cd -P "$( dirname "$SOURCE" )/.." && pwd )" # Change into that dir because we expect that. cd "$DIR" # Building binaries sh -c "'$DIR/scripts/dist.sh'" # Pushing binaries to S3 sh -c "'$DIR/scripts/publish.sh'" # echo "==> Crafting a Github release" # today=$(date +"%B-%d-%Y") # ghr -b "https://github.com/franono/tendermint/blob/master/CHANGELOG.md#${VERSION//.}-${today,}" "v$VERSION" "$DIR/build/dist" # Build and push Docker image ## Get SHA256SUM of the linux archive SHA256SUM=$(shasum -a256 "${DIR}/build/dist/tendermint_${VERSION}_linux_amd64.zip" | awk '{print $1;}') ## Replace TM_VERSION and TM_SHA256SUM with the new values sed -i -e "s/TM_VERSION .*/TM_VERSION $VERSION/g" "$DIR/DOCKER/Dockerfile" sed -i -e "s/TM_SHA256SUM .*/TM_SHA256SUM $SHA256SUM/g" "$DIR/DOCKER/Dockerfile" git commit -m "update Dockerfile" -a "$DIR/DOCKER/Dockerfile" echo "==> TODO: update DOCKER/README.md (latest Dockerfile's hash is $(git rev-parse HEAD)) and copy it's content to https://store.docker.com/community/images/franono/tendermint" pushd "$DIR/DOCKER" ## Build Docker image TAG=$VERSION sh -c "'./build.sh'" ## Push Docker image TAG=$VERSION sh -c "'./push.sh'" popd exit 0
import subprocess def setup_and_run_codecov(env_name): try: # Step 1: Activate virtual environment activate_cmd = f'source .tox/{env_name}/bin/activate' subprocess.run(activate_cmd, shell=True, check=True) # Step 2: Install codecov package pip_install_cmd = 'pip install codecov' subprocess.run(pip_install_cmd, shell=True, check=True) # Step 3: Run codecov command with environment variables codecov_cmd = f'codecov --env TRAVIS_OS_NAME,TOXENV' subprocess.run(codecov_cmd, shell=True, check=True) return f'Codecov setup and run successful in {env_name} environment.' except subprocess.CalledProcessError as e: return f'Error: {e}' except Exception as e: return f'Error: {e}'
<reponame>jeffrey-xiao/acm-notebook /* Time: O(N) * Memory: O(N) */ #include <bits/stdc++.h> using namespace std; struct Edge { int dest, index; bool used; }; struct Euler { int N; vector<vector<Edge>> adj; vector<int> used; Euler(int N) : N(N), adj(N), used(N) {} void addEdge(int u, int v) { adj[u].push_back({v, (int)adj[v].size(), 0}); adj[v].push_back({u, (int)adj[u].size() - 1, 0}); } // precondition: all vertices are connected int getEuler() { int odd = 0; for (int i = 0; i < N; i++) if ((int)adj[i].size() & 1) odd++; if (odd > 2) return -1; return odd == 0 ? 0 : 1; } bool isEulerianPath() { return getEuler() != -1; } bool isEulerianCycle() { return getEuler() == 0; } void printEulerianPath() { if (!isEulerianPath()) { printf("No Eulerian Path Exists."); return; } stack<int> order; int curr = 0; for (int i = 0; i < N; i++) if ((int)adj[i].size() & 1) curr = i; while (true) { if ((int)adj[curr].size() - used[curr] == 0) { printf("%d ", curr); if (order.size() == 0) break; curr = order.top(); order.pop(); } else { order.push(curr); for (int i = 0; i < (int)adj[curr].size(); i++) { if (!adj[curr][i].used) { int dest = adj[curr][i].dest; int index = adj[curr][i].index; adj[curr][i].used = true; adj[dest][index].used = true; used[curr]++; used[dest]++; curr = dest; break; } } } } } };
#!/bin/bash SRC=$(dirname "$(readlink -f "$0")") ROOT=${SRC::-3} source $SRC/utils/global.sh # Create .log if it doesn't exist if [[ ! -f $ROOT.log ]]; then printf "" > $ROOT.log fi # Clear .log if it gets too long (keep only the last 256 lines) # Given no errors, the max file size is 7KB if [[ $(wc -l < $ROOT.log) -gt 256 ]]; then printf "$(tail -n 256 $ROOT.log)\n" > $ROOT.log fi # If the script got interrupted, history still exists and has to be cleaned echo -n "" > $SRC/.hist ARGC=$# ARGV=$@ # Check if arguments passed exist if [[ $ARGC -gt 0 ]]; then source $SRC/test/argument_check.sh $ARGV fi if [[ $ARGV =~ "-help" ]]; then cat $SRC/utils/help elif [[ $ARGV =~ "-au" ]]; then source $SRC/utils/cron.sh elif [[ $ARGV =~ "-err" ]]; then if [[ $(grep -cv "[0-9]*/[0-9]*/[0-9]* [0-9]*:[0-9]*:[0-9]*:[0-9]*" $ROOT.log) -gt 0 ]]; then puts RED "Errors found\nOpen .log in $ROOT to see what's wrong" else puts GREEN "No errors found" fi elif [[ $ARGV =~ "-up" ]]; then source ${ROOT}update.sh $ROOT elif [[ $ARGV =~ "-xyzzy" ]]; then puts NC "Let's keep its memory alive" else if [[ -f "$SRC/utils/.cache" && ! $ARGV =~ "-rc" ]]; then HASH=$(md5sum "$SRC/utils/.cache" | cut -d " " -f1) if [[ $HASH != $(cat $SRC/utils/.md5) ]]; then md5sum $SRC/utils/.cache | cut -d " " -f1 > $SRC/utils/.md5 fi else $SRC/utils/cache_gen.sh > $SRC/utils/.cache md5sum $SRC/utils/.cache | cut -d " " -f1 > $SRC/utils/.md5 chmod 775 $SRC/utils/.cache fi chmod 775 $SRC/utils/.md5 # Logo if [[ ! $ARGV =~ "-nl" ]]; then if [[ $(stty size | awk '{print $2}') -ge 74 ]]; then puts LOGO "$(cat $SRC/utils/.logo)" echo "$NORMAL$LOGO$(cat $SRC/utils/.logo)$NORMAL\n" >> $SRC/.hist fi puts LOGO "Contribute @ https://github.com/MasterCruelty/eMerger $WHALE" fi # System informations if [[ ! $ARGV =~ "-ni" ]]; then if [[ -f "/etc/os-release" ]]; then NAME=$(cat /etc/os-release | head -n $(echo $(grep -n "PRETTY_NAME" /etc/os-release) | cut -c 1) | tail -n 1 | cut -c 14-) puts LOGO "${NAME::-1}" else puts LOGO "$(uname -rs)" fi fi # Weather if [[ $ARGV =~ "-w" ]]; then # Using wttr.in to show the weather using the following arguments: # %l = location; %c = weather emoji; %t = actual temp; %w = wind km/h; %m = Moon phase puts LOGO "$(curl -s wttr.in/?format="%l:+%c+%t+%w+%m")" fi # `tail -n +3` skips the first two lines # ITER keeps track of iterations ('tail -n 3', so ITER='3-1') ITER=2 for LINE in $(cat $SRC/utils/.cache | tail -n +3); do ITER=$(($ITER + 1)) if [[ $LINE == "utils/trash" && $ARGV =~ "-nt" ]]; then continue fi if [[ $LINE != "" ]]; then source $SRC/$LINE.sh if [[ $LINE != "utils/privileges" ]]; then echo "$BLUE$PKG COMPLETED$NORMAL\n" >> $SRC/.hist fi fi if [[ $ITER != $(cat $SRC/utils/.cache | wc -l) ]]; then puts NC "" fi done # Notify if errors are present if [[ $(grep -v "[0-9]*:[0-9]*:[0-9]*:[0-9]*" $ROOT.log | wc -l) -gt 0 ]]; then puts LOGO "\n\nSomething is not working correctly, type \"up -err\" for further informations\a" fi reset echo -ne "${BLUE}eMerger COMPLETED$NORMAL\n" fi rm $SRC/.hist exit 0
import { none, Option, some } from 'fp-ts/lib/Option'; import * as moment from 'moment'; import * as React from "react"; import range from "@util/range"; import { KeyAndDisplay, Select } from "./Select"; export interface DateTriPickerProps<U> { years: number[] monthID: string & keyof U, dayID: string & keyof U, yearID: string & keyof U, monthValue: Option<string>, dayValue: Option<string>, yearValue: Option<string>, updateAction?: (name: string, value: string) => void, isRequired?: boolean } const months = ["1 - JAN", "2 - FEB", "3 - MAR", "4 - APR", "5 - MAY", "6 - JUN", "7 - JUL", "8 - AUG", "9 - SEP", "10 - OCT", "11 - NOV", "12 - DEC"]; const leadingZero = (n: number) => n<10 ? String("0" + n) : String(n); const dobMonthValues: KeyAndDisplay[] = months.map((m, i) => ({key: leadingZero(i+1), display: m})) const days = range(1,31).map(i => ({key: String(leadingZero(i)), display: String(i)})) export function componentsToDate(month: Option<string>, date: Option<string>, year: Option<string>): Option<string> { if ( month.isNone() || date.isNone() || year.isNone() || isNaN(Number(month.getOrElse(null))) || isNaN(Number(date.getOrElse(null))) || isNaN(Number(year.getOrElse(null))) || month == null || date == null || year == null ) return none const candidate = `${month.getOrElse(null)}/${date.getOrElse(null)}/${year.getOrElse(null)}` const candidateMoment = moment(candidate, "MM/DD/YYYY"); if (candidateMoment.isValid()) return some(candidate) else return none } export function dateStringToComponents(dateString: Option<string>): Option<{month: string, date: string, year: string}> { return dateString.chain(s => { const dobRegex = /(\d{2})\/(\d{2})\/(\d{4})/ const dobResult = dobRegex.exec(s) if (dobResult == null) return none else return some({month: dobResult[1], date: dobResult[2], year: dobResult[3]}) }) } export default class DateTriPicker<U, T extends DateTriPickerProps<U>> extends React.PureComponent<T> { render() { const self = this const dobDateAndYear = (function() { const date = <Select<U> id={self.props.dayID} justElement={true} value={self.props.dayValue} updateAction={self.props.updateAction} options={days} nullDisplay="- Day -" /> const year = <Select<U> id={self.props.yearID} justElement={true} value={self.props.yearValue} updateAction={self.props.updateAction} options={self.props.years.reverse().map(i => ({key: String(i), display: String(i)}))} nullDisplay="- Year -" /> return ( <span> {" / "} {date} {" / "} {year} </span> ) }()); return <Select<U> id={self.props.monthID} label="Date of Birth" value={self.props.monthValue} updateAction={self.props.updateAction} options={dobMonthValues} appendToElementCell={dobDateAndYear} nullDisplay="- Month -" isRequired={self.props.isRequired} /> } }
// (C) 2018 ETH Zurich, ITP, <NAME> and <NAME> template <class V, class M> inline void kernel_core(V& psi, std::size_t I, std::size_t d0, std::size_t d1, std::size_t d2, std::size_t d3, std::size_t d4, M const& m) { std::complex<double> v[2]; v[0] = psi[I]; v[1] = psi[I + d0]; std::complex<double> tmp[32] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.}; tmp[0] = fma(v[0], m[0], fma(v[1], m[1], tmp[0])); tmp[1] = fma(v[0], m[2], fma(v[1], m[3], tmp[1])); tmp[2] = fma(v[0], m[4], fma(v[1], m[5], tmp[2])); tmp[3] = fma(v[0], m[6], fma(v[1], m[7], tmp[3])); tmp[4] = fma(v[0], m[8], fma(v[1], m[9], tmp[4])); tmp[5] = fma(v[0], m[10], fma(v[1], m[11], tmp[5])); tmp[6] = fma(v[0], m[12], fma(v[1], m[13], tmp[6])); tmp[7] = fma(v[0], m[14], fma(v[1], m[15], tmp[7])); tmp[8] = fma(v[0], m[16], fma(v[1], m[17], tmp[8])); tmp[9] = fma(v[0], m[18], fma(v[1], m[19], tmp[9])); tmp[10] = fma(v[0], m[20], fma(v[1], m[21], tmp[10])); tmp[11] = fma(v[0], m[22], fma(v[1], m[23], tmp[11])); tmp[12] = fma(v[0], m[24], fma(v[1], m[25], tmp[12])); tmp[13] = fma(v[0], m[26], fma(v[1], m[27], tmp[13])); tmp[14] = fma(v[0], m[28], fma(v[1], m[29], tmp[14])); tmp[15] = fma(v[0], m[30], fma(v[1], m[31], tmp[15])); tmp[16] = fma(v[0], m[32], fma(v[1], m[33], tmp[16])); tmp[17] = fma(v[0], m[34], fma(v[1], m[35], tmp[17])); tmp[18] = fma(v[0], m[36], fma(v[1], m[37], tmp[18])); tmp[19] = fma(v[0], m[38], fma(v[1], m[39], tmp[19])); tmp[20] = fma(v[0], m[40], fma(v[1], m[41], tmp[20])); tmp[21] = fma(v[0], m[42], fma(v[1], m[43], tmp[21])); tmp[22] = fma(v[0], m[44], fma(v[1], m[45], tmp[22])); tmp[23] = fma(v[0], m[46], fma(v[1], m[47], tmp[23])); tmp[24] = fma(v[0], m[48], fma(v[1], m[49], tmp[24])); tmp[25] = fma(v[0], m[50], fma(v[1], m[51], tmp[25])); tmp[26] = fma(v[0], m[52], fma(v[1], m[53], tmp[26])); tmp[27] = fma(v[0], m[54], fma(v[1], m[55], tmp[27])); tmp[28] = fma(v[0], m[56], fma(v[1], m[57], tmp[28])); tmp[29] = fma(v[0], m[58], fma(v[1], m[59], tmp[29])); tmp[30] = fma(v[0], m[60], fma(v[1], m[61], tmp[30])); tmp[31] = fma(v[0], m[62], fma(v[1], m[63], tmp[31])); v[0] = psi[I + d1]; v[1] = psi[I + d0 + d1]; tmp[0] = fma(v[0], m[64], fma(v[1], m[65], tmp[0])); tmp[1] = fma(v[0], m[66], fma(v[1], m[67], tmp[1])); tmp[2] = fma(v[0], m[68], fma(v[1], m[69], tmp[2])); tmp[3] = fma(v[0], m[70], fma(v[1], m[71], tmp[3])); tmp[4] = fma(v[0], m[72], fma(v[1], m[73], tmp[4])); tmp[5] = fma(v[0], m[74], fma(v[1], m[75], tmp[5])); tmp[6] = fma(v[0], m[76], fma(v[1], m[77], tmp[6])); tmp[7] = fma(v[0], m[78], fma(v[1], m[79], tmp[7])); tmp[8] = fma(v[0], m[80], fma(v[1], m[81], tmp[8])); tmp[9] = fma(v[0], m[82], fma(v[1], m[83], tmp[9])); tmp[10] = fma(v[0], m[84], fma(v[1], m[85], tmp[10])); tmp[11] = fma(v[0], m[86], fma(v[1], m[87], tmp[11])); tmp[12] = fma(v[0], m[88], fma(v[1], m[89], tmp[12])); tmp[13] = fma(v[0], m[90], fma(v[1], m[91], tmp[13])); tmp[14] = fma(v[0], m[92], fma(v[1], m[93], tmp[14])); tmp[15] = fma(v[0], m[94], fma(v[1], m[95], tmp[15])); tmp[16] = fma(v[0], m[96], fma(v[1], m[97], tmp[16])); tmp[17] = fma(v[0], m[98], fma(v[1], m[99], tmp[17])); tmp[18] = fma(v[0], m[100], fma(v[1], m[101], tmp[18])); tmp[19] = fma(v[0], m[102], fma(v[1], m[103], tmp[19])); tmp[20] = fma(v[0], m[104], fma(v[1], m[105], tmp[20])); tmp[21] = fma(v[0], m[106], fma(v[1], m[107], tmp[21])); tmp[22] = fma(v[0], m[108], fma(v[1], m[109], tmp[22])); tmp[23] = fma(v[0], m[110], fma(v[1], m[111], tmp[23])); tmp[24] = fma(v[0], m[112], fma(v[1], m[113], tmp[24])); tmp[25] = fma(v[0], m[114], fma(v[1], m[115], tmp[25])); tmp[26] = fma(v[0], m[116], fma(v[1], m[117], tmp[26])); tmp[27] = fma(v[0], m[118], fma(v[1], m[119], tmp[27])); tmp[28] = fma(v[0], m[120], fma(v[1], m[121], tmp[28])); tmp[29] = fma(v[0], m[122], fma(v[1], m[123], tmp[29])); tmp[30] = fma(v[0], m[124], fma(v[1], m[125], tmp[30])); tmp[31] = fma(v[0], m[126], fma(v[1], m[127], tmp[31])); v[0] = psi[I + d2]; v[1] = psi[I + d0 + d2]; tmp[0] = fma(v[0], m[128], fma(v[1], m[129], tmp[0])); tmp[1] = fma(v[0], m[130], fma(v[1], m[131], tmp[1])); tmp[2] = fma(v[0], m[132], fma(v[1], m[133], tmp[2])); tmp[3] = fma(v[0], m[134], fma(v[1], m[135], tmp[3])); tmp[4] = fma(v[0], m[136], fma(v[1], m[137], tmp[4])); tmp[5] = fma(v[0], m[138], fma(v[1], m[139], tmp[5])); tmp[6] = fma(v[0], m[140], fma(v[1], m[141], tmp[6])); tmp[7] = fma(v[0], m[142], fma(v[1], m[143], tmp[7])); tmp[8] = fma(v[0], m[144], fma(v[1], m[145], tmp[8])); tmp[9] = fma(v[0], m[146], fma(v[1], m[147], tmp[9])); tmp[10] = fma(v[0], m[148], fma(v[1], m[149], tmp[10])); tmp[11] = fma(v[0], m[150], fma(v[1], m[151], tmp[11])); tmp[12] = fma(v[0], m[152], fma(v[1], m[153], tmp[12])); tmp[13] = fma(v[0], m[154], fma(v[1], m[155], tmp[13])); tmp[14] = fma(v[0], m[156], fma(v[1], m[157], tmp[14])); tmp[15] = fma(v[0], m[158], fma(v[1], m[159], tmp[15])); tmp[16] = fma(v[0], m[160], fma(v[1], m[161], tmp[16])); tmp[17] = fma(v[0], m[162], fma(v[1], m[163], tmp[17])); tmp[18] = fma(v[0], m[164], fma(v[1], m[165], tmp[18])); tmp[19] = fma(v[0], m[166], fma(v[1], m[167], tmp[19])); tmp[20] = fma(v[0], m[168], fma(v[1], m[169], tmp[20])); tmp[21] = fma(v[0], m[170], fma(v[1], m[171], tmp[21])); tmp[22] = fma(v[0], m[172], fma(v[1], m[173], tmp[22])); tmp[23] = fma(v[0], m[174], fma(v[1], m[175], tmp[23])); tmp[24] = fma(v[0], m[176], fma(v[1], m[177], tmp[24])); tmp[25] = fma(v[0], m[178], fma(v[1], m[179], tmp[25])); tmp[26] = fma(v[0], m[180], fma(v[1], m[181], tmp[26])); tmp[27] = fma(v[0], m[182], fma(v[1], m[183], tmp[27])); tmp[28] = fma(v[0], m[184], fma(v[1], m[185], tmp[28])); tmp[29] = fma(v[0], m[186], fma(v[1], m[187], tmp[29])); tmp[30] = fma(v[0], m[188], fma(v[1], m[189], tmp[30])); tmp[31] = fma(v[0], m[190], fma(v[1], m[191], tmp[31])); v[0] = psi[I + d1 + d2]; v[1] = psi[I + d0 + d1 + d2]; tmp[0] = fma(v[0], m[192], fma(v[1], m[193], tmp[0])); tmp[1] = fma(v[0], m[194], fma(v[1], m[195], tmp[1])); tmp[2] = fma(v[0], m[196], fma(v[1], m[197], tmp[2])); tmp[3] = fma(v[0], m[198], fma(v[1], m[199], tmp[3])); tmp[4] = fma(v[0], m[200], fma(v[1], m[201], tmp[4])); tmp[5] = fma(v[0], m[202], fma(v[1], m[203], tmp[5])); tmp[6] = fma(v[0], m[204], fma(v[1], m[205], tmp[6])); tmp[7] = fma(v[0], m[206], fma(v[1], m[207], tmp[7])); tmp[8] = fma(v[0], m[208], fma(v[1], m[209], tmp[8])); tmp[9] = fma(v[0], m[210], fma(v[1], m[211], tmp[9])); tmp[10] = fma(v[0], m[212], fma(v[1], m[213], tmp[10])); tmp[11] = fma(v[0], m[214], fma(v[1], m[215], tmp[11])); tmp[12] = fma(v[0], m[216], fma(v[1], m[217], tmp[12])); tmp[13] = fma(v[0], m[218], fma(v[1], m[219], tmp[13])); tmp[14] = fma(v[0], m[220], fma(v[1], m[221], tmp[14])); tmp[15] = fma(v[0], m[222], fma(v[1], m[223], tmp[15])); tmp[16] = fma(v[0], m[224], fma(v[1], m[225], tmp[16])); tmp[17] = fma(v[0], m[226], fma(v[1], m[227], tmp[17])); tmp[18] = fma(v[0], m[228], fma(v[1], m[229], tmp[18])); tmp[19] = fma(v[0], m[230], fma(v[1], m[231], tmp[19])); tmp[20] = fma(v[0], m[232], fma(v[1], m[233], tmp[20])); tmp[21] = fma(v[0], m[234], fma(v[1], m[235], tmp[21])); tmp[22] = fma(v[0], m[236], fma(v[1], m[237], tmp[22])); tmp[23] = fma(v[0], m[238], fma(v[1], m[239], tmp[23])); tmp[24] = fma(v[0], m[240], fma(v[1], m[241], tmp[24])); tmp[25] = fma(v[0], m[242], fma(v[1], m[243], tmp[25])); tmp[26] = fma(v[0], m[244], fma(v[1], m[245], tmp[26])); tmp[27] = fma(v[0], m[246], fma(v[1], m[247], tmp[27])); tmp[28] = fma(v[0], m[248], fma(v[1], m[249], tmp[28])); tmp[29] = fma(v[0], m[250], fma(v[1], m[251], tmp[29])); tmp[30] = fma(v[0], m[252], fma(v[1], m[253], tmp[30])); tmp[31] = fma(v[0], m[254], fma(v[1], m[255], tmp[31])); v[0] = psi[I + d3]; v[1] = psi[I + d0 + d3]; tmp[0] = fma(v[0], m[256], fma(v[1], m[257], tmp[0])); tmp[1] = fma(v[0], m[258], fma(v[1], m[259], tmp[1])); tmp[2] = fma(v[0], m[260], fma(v[1], m[261], tmp[2])); tmp[3] = fma(v[0], m[262], fma(v[1], m[263], tmp[3])); tmp[4] = fma(v[0], m[264], fma(v[1], m[265], tmp[4])); tmp[5] = fma(v[0], m[266], fma(v[1], m[267], tmp[5])); tmp[6] = fma(v[0], m[268], fma(v[1], m[269], tmp[6])); tmp[7] = fma(v[0], m[270], fma(v[1], m[271], tmp[7])); tmp[8] = fma(v[0], m[272], fma(v[1], m[273], tmp[8])); tmp[9] = fma(v[0], m[274], fma(v[1], m[275], tmp[9])); tmp[10] = fma(v[0], m[276], fma(v[1], m[277], tmp[10])); tmp[11] = fma(v[0], m[278], fma(v[1], m[279], tmp[11])); tmp[12] = fma(v[0], m[280], fma(v[1], m[281], tmp[12])); tmp[13] = fma(v[0], m[282], fma(v[1], m[283], tmp[13])); tmp[14] = fma(v[0], m[284], fma(v[1], m[285], tmp[14])); tmp[15] = fma(v[0], m[286], fma(v[1], m[287], tmp[15])); tmp[16] = fma(v[0], m[288], fma(v[1], m[289], tmp[16])); tmp[17] = fma(v[0], m[290], fma(v[1], m[291], tmp[17])); tmp[18] = fma(v[0], m[292], fma(v[1], m[293], tmp[18])); tmp[19] = fma(v[0], m[294], fma(v[1], m[295], tmp[19])); tmp[20] = fma(v[0], m[296], fma(v[1], m[297], tmp[20])); tmp[21] = fma(v[0], m[298], fma(v[1], m[299], tmp[21])); tmp[22] = fma(v[0], m[300], fma(v[1], m[301], tmp[22])); tmp[23] = fma(v[0], m[302], fma(v[1], m[303], tmp[23])); tmp[24] = fma(v[0], m[304], fma(v[1], m[305], tmp[24])); tmp[25] = fma(v[0], m[306], fma(v[1], m[307], tmp[25])); tmp[26] = fma(v[0], m[308], fma(v[1], m[309], tmp[26])); tmp[27] = fma(v[0], m[310], fma(v[1], m[311], tmp[27])); tmp[28] = fma(v[0], m[312], fma(v[1], m[313], tmp[28])); tmp[29] = fma(v[0], m[314], fma(v[1], m[315], tmp[29])); tmp[30] = fma(v[0], m[316], fma(v[1], m[317], tmp[30])); tmp[31] = fma(v[0], m[318], fma(v[1], m[319], tmp[31])); v[0] = psi[I + d1 + d3]; v[1] = psi[I + d0 + d1 + d3]; tmp[0] = fma(v[0], m[320], fma(v[1], m[321], tmp[0])); tmp[1] = fma(v[0], m[322], fma(v[1], m[323], tmp[1])); tmp[2] = fma(v[0], m[324], fma(v[1], m[325], tmp[2])); tmp[3] = fma(v[0], m[326], fma(v[1], m[327], tmp[3])); tmp[4] = fma(v[0], m[328], fma(v[1], m[329], tmp[4])); tmp[5] = fma(v[0], m[330], fma(v[1], m[331], tmp[5])); tmp[6] = fma(v[0], m[332], fma(v[1], m[333], tmp[6])); tmp[7] = fma(v[0], m[334], fma(v[1], m[335], tmp[7])); tmp[8] = fma(v[0], m[336], fma(v[1], m[337], tmp[8])); tmp[9] = fma(v[0], m[338], fma(v[1], m[339], tmp[9])); tmp[10] = fma(v[0], m[340], fma(v[1], m[341], tmp[10])); tmp[11] = fma(v[0], m[342], fma(v[1], m[343], tmp[11])); tmp[12] = fma(v[0], m[344], fma(v[1], m[345], tmp[12])); tmp[13] = fma(v[0], m[346], fma(v[1], m[347], tmp[13])); tmp[14] = fma(v[0], m[348], fma(v[1], m[349], tmp[14])); tmp[15] = fma(v[0], m[350], fma(v[1], m[351], tmp[15])); tmp[16] = fma(v[0], m[352], fma(v[1], m[353], tmp[16])); tmp[17] = fma(v[0], m[354], fma(v[1], m[355], tmp[17])); tmp[18] = fma(v[0], m[356], fma(v[1], m[357], tmp[18])); tmp[19] = fma(v[0], m[358], fma(v[1], m[359], tmp[19])); tmp[20] = fma(v[0], m[360], fma(v[1], m[361], tmp[20])); tmp[21] = fma(v[0], m[362], fma(v[1], m[363], tmp[21])); tmp[22] = fma(v[0], m[364], fma(v[1], m[365], tmp[22])); tmp[23] = fma(v[0], m[366], fma(v[1], m[367], tmp[23])); tmp[24] = fma(v[0], m[368], fma(v[1], m[369], tmp[24])); tmp[25] = fma(v[0], m[370], fma(v[1], m[371], tmp[25])); tmp[26] = fma(v[0], m[372], fma(v[1], m[373], tmp[26])); tmp[27] = fma(v[0], m[374], fma(v[1], m[375], tmp[27])); tmp[28] = fma(v[0], m[376], fma(v[1], m[377], tmp[28])); tmp[29] = fma(v[0], m[378], fma(v[1], m[379], tmp[29])); tmp[30] = fma(v[0], m[380], fma(v[1], m[381], tmp[30])); tmp[31] = fma(v[0], m[382], fma(v[1], m[383], tmp[31])); v[0] = psi[I + d2 + d3]; v[1] = psi[I + d0 + d2 + d3]; tmp[0] = fma(v[0], m[384], fma(v[1], m[385], tmp[0])); tmp[1] = fma(v[0], m[386], fma(v[1], m[387], tmp[1])); tmp[2] = fma(v[0], m[388], fma(v[1], m[389], tmp[2])); tmp[3] = fma(v[0], m[390], fma(v[1], m[391], tmp[3])); tmp[4] = fma(v[0], m[392], fma(v[1], m[393], tmp[4])); tmp[5] = fma(v[0], m[394], fma(v[1], m[395], tmp[5])); tmp[6] = fma(v[0], m[396], fma(v[1], m[397], tmp[6])); tmp[7] = fma(v[0], m[398], fma(v[1], m[399], tmp[7])); tmp[8] = fma(v[0], m[400], fma(v[1], m[401], tmp[8])); tmp[9] = fma(v[0], m[402], fma(v[1], m[403], tmp[9])); tmp[10] = fma(v[0], m[404], fma(v[1], m[405], tmp[10])); tmp[11] = fma(v[0], m[406], fma(v[1], m[407], tmp[11])); tmp[12] = fma(v[0], m[408], fma(v[1], m[409], tmp[12])); tmp[13] = fma(v[0], m[410], fma(v[1], m[411], tmp[13])); tmp[14] = fma(v[0], m[412], fma(v[1], m[413], tmp[14])); tmp[15] = fma(v[0], m[414], fma(v[1], m[415], tmp[15])); tmp[16] = fma(v[0], m[416], fma(v[1], m[417], tmp[16])); tmp[17] = fma(v[0], m[418], fma(v[1], m[419], tmp[17])); tmp[18] = fma(v[0], m[420], fma(v[1], m[421], tmp[18])); tmp[19] = fma(v[0], m[422], fma(v[1], m[423], tmp[19])); tmp[20] = fma(v[0], m[424], fma(v[1], m[425], tmp[20])); tmp[21] = fma(v[0], m[426], fma(v[1], m[427], tmp[21])); tmp[22] = fma(v[0], m[428], fma(v[1], m[429], tmp[22])); tmp[23] = fma(v[0], m[430], fma(v[1], m[431], tmp[23])); tmp[24] = fma(v[0], m[432], fma(v[1], m[433], tmp[24])); tmp[25] = fma(v[0], m[434], fma(v[1], m[435], tmp[25])); tmp[26] = fma(v[0], m[436], fma(v[1], m[437], tmp[26])); tmp[27] = fma(v[0], m[438], fma(v[1], m[439], tmp[27])); tmp[28] = fma(v[0], m[440], fma(v[1], m[441], tmp[28])); tmp[29] = fma(v[0], m[442], fma(v[1], m[443], tmp[29])); tmp[30] = fma(v[0], m[444], fma(v[1], m[445], tmp[30])); tmp[31] = fma(v[0], m[446], fma(v[1], m[447], tmp[31])); v[0] = psi[I + d1 + d2 + d3]; v[1] = psi[I + d0 + d1 + d2 + d3]; tmp[0] = fma(v[0], m[448], fma(v[1], m[449], tmp[0])); tmp[1] = fma(v[0], m[450], fma(v[1], m[451], tmp[1])); tmp[2] = fma(v[0], m[452], fma(v[1], m[453], tmp[2])); tmp[3] = fma(v[0], m[454], fma(v[1], m[455], tmp[3])); tmp[4] = fma(v[0], m[456], fma(v[1], m[457], tmp[4])); tmp[5] = fma(v[0], m[458], fma(v[1], m[459], tmp[5])); tmp[6] = fma(v[0], m[460], fma(v[1], m[461], tmp[6])); tmp[7] = fma(v[0], m[462], fma(v[1], m[463], tmp[7])); tmp[8] = fma(v[0], m[464], fma(v[1], m[465], tmp[8])); tmp[9] = fma(v[0], m[466], fma(v[1], m[467], tmp[9])); tmp[10] = fma(v[0], m[468], fma(v[1], m[469], tmp[10])); tmp[11] = fma(v[0], m[470], fma(v[1], m[471], tmp[11])); tmp[12] = fma(v[0], m[472], fma(v[1], m[473], tmp[12])); tmp[13] = fma(v[0], m[474], fma(v[1], m[475], tmp[13])); tmp[14] = fma(v[0], m[476], fma(v[1], m[477], tmp[14])); tmp[15] = fma(v[0], m[478], fma(v[1], m[479], tmp[15])); tmp[16] = fma(v[0], m[480], fma(v[1], m[481], tmp[16])); tmp[17] = fma(v[0], m[482], fma(v[1], m[483], tmp[17])); tmp[18] = fma(v[0], m[484], fma(v[1], m[485], tmp[18])); tmp[19] = fma(v[0], m[486], fma(v[1], m[487], tmp[19])); tmp[20] = fma(v[0], m[488], fma(v[1], m[489], tmp[20])); tmp[21] = fma(v[0], m[490], fma(v[1], m[491], tmp[21])); tmp[22] = fma(v[0], m[492], fma(v[1], m[493], tmp[22])); tmp[23] = fma(v[0], m[494], fma(v[1], m[495], tmp[23])); tmp[24] = fma(v[0], m[496], fma(v[1], m[497], tmp[24])); tmp[25] = fma(v[0], m[498], fma(v[1], m[499], tmp[25])); tmp[26] = fma(v[0], m[500], fma(v[1], m[501], tmp[26])); tmp[27] = fma(v[0], m[502], fma(v[1], m[503], tmp[27])); tmp[28] = fma(v[0], m[504], fma(v[1], m[505], tmp[28])); tmp[29] = fma(v[0], m[506], fma(v[1], m[507], tmp[29])); tmp[30] = fma(v[0], m[508], fma(v[1], m[509], tmp[30])); tmp[31] = fma(v[0], m[510], fma(v[1], m[511], tmp[31])); v[0] = psi[I + d4]; v[1] = psi[I + d0 + d4]; tmp[0] = fma(v[0], m[512], fma(v[1], m[513], tmp[0])); tmp[1] = fma(v[0], m[514], fma(v[1], m[515], tmp[1])); tmp[2] = fma(v[0], m[516], fma(v[1], m[517], tmp[2])); tmp[3] = fma(v[0], m[518], fma(v[1], m[519], tmp[3])); tmp[4] = fma(v[0], m[520], fma(v[1], m[521], tmp[4])); tmp[5] = fma(v[0], m[522], fma(v[1], m[523], tmp[5])); tmp[6] = fma(v[0], m[524], fma(v[1], m[525], tmp[6])); tmp[7] = fma(v[0], m[526], fma(v[1], m[527], tmp[7])); tmp[8] = fma(v[0], m[528], fma(v[1], m[529], tmp[8])); tmp[9] = fma(v[0], m[530], fma(v[1], m[531], tmp[9])); tmp[10] = fma(v[0], m[532], fma(v[1], m[533], tmp[10])); tmp[11] = fma(v[0], m[534], fma(v[1], m[535], tmp[11])); tmp[12] = fma(v[0], m[536], fma(v[1], m[537], tmp[12])); tmp[13] = fma(v[0], m[538], fma(v[1], m[539], tmp[13])); tmp[14] = fma(v[0], m[540], fma(v[1], m[541], tmp[14])); tmp[15] = fma(v[0], m[542], fma(v[1], m[543], tmp[15])); tmp[16] = fma(v[0], m[544], fma(v[1], m[545], tmp[16])); tmp[17] = fma(v[0], m[546], fma(v[1], m[547], tmp[17])); tmp[18] = fma(v[0], m[548], fma(v[1], m[549], tmp[18])); tmp[19] = fma(v[0], m[550], fma(v[1], m[551], tmp[19])); tmp[20] = fma(v[0], m[552], fma(v[1], m[553], tmp[20])); tmp[21] = fma(v[0], m[554], fma(v[1], m[555], tmp[21])); tmp[22] = fma(v[0], m[556], fma(v[1], m[557], tmp[22])); tmp[23] = fma(v[0], m[558], fma(v[1], m[559], tmp[23])); tmp[24] = fma(v[0], m[560], fma(v[1], m[561], tmp[24])); tmp[25] = fma(v[0], m[562], fma(v[1], m[563], tmp[25])); tmp[26] = fma(v[0], m[564], fma(v[1], m[565], tmp[26])); tmp[27] = fma(v[0], m[566], fma(v[1], m[567], tmp[27])); tmp[28] = fma(v[0], m[568], fma(v[1], m[569], tmp[28])); tmp[29] = fma(v[0], m[570], fma(v[1], m[571], tmp[29])); tmp[30] = fma(v[0], m[572], fma(v[1], m[573], tmp[30])); tmp[31] = fma(v[0], m[574], fma(v[1], m[575], tmp[31])); v[0] = psi[I + d1 + d4]; v[1] = psi[I + d0 + d1 + d4]; tmp[0] = fma(v[0], m[576], fma(v[1], m[577], tmp[0])); tmp[1] = fma(v[0], m[578], fma(v[1], m[579], tmp[1])); tmp[2] = fma(v[0], m[580], fma(v[1], m[581], tmp[2])); tmp[3] = fma(v[0], m[582], fma(v[1], m[583], tmp[3])); tmp[4] = fma(v[0], m[584], fma(v[1], m[585], tmp[4])); tmp[5] = fma(v[0], m[586], fma(v[1], m[587], tmp[5])); tmp[6] = fma(v[0], m[588], fma(v[1], m[589], tmp[6])); tmp[7] = fma(v[0], m[590], fma(v[1], m[591], tmp[7])); tmp[8] = fma(v[0], m[592], fma(v[1], m[593], tmp[8])); tmp[9] = fma(v[0], m[594], fma(v[1], m[595], tmp[9])); tmp[10] = fma(v[0], m[596], fma(v[1], m[597], tmp[10])); tmp[11] = fma(v[0], m[598], fma(v[1], m[599], tmp[11])); tmp[12] = fma(v[0], m[600], fma(v[1], m[601], tmp[12])); tmp[13] = fma(v[0], m[602], fma(v[1], m[603], tmp[13])); tmp[14] = fma(v[0], m[604], fma(v[1], m[605], tmp[14])); tmp[15] = fma(v[0], m[606], fma(v[1], m[607], tmp[15])); tmp[16] = fma(v[0], m[608], fma(v[1], m[609], tmp[16])); tmp[17] = fma(v[0], m[610], fma(v[1], m[611], tmp[17])); tmp[18] = fma(v[0], m[612], fma(v[1], m[613], tmp[18])); tmp[19] = fma(v[0], m[614], fma(v[1], m[615], tmp[19])); tmp[20] = fma(v[0], m[616], fma(v[1], m[617], tmp[20])); tmp[21] = fma(v[0], m[618], fma(v[1], m[619], tmp[21])); tmp[22] = fma(v[0], m[620], fma(v[1], m[621], tmp[22])); tmp[23] = fma(v[0], m[622], fma(v[1], m[623], tmp[23])); tmp[24] = fma(v[0], m[624], fma(v[1], m[625], tmp[24])); tmp[25] = fma(v[0], m[626], fma(v[1], m[627], tmp[25])); tmp[26] = fma(v[0], m[628], fma(v[1], m[629], tmp[26])); tmp[27] = fma(v[0], m[630], fma(v[1], m[631], tmp[27])); tmp[28] = fma(v[0], m[632], fma(v[1], m[633], tmp[28])); tmp[29] = fma(v[0], m[634], fma(v[1], m[635], tmp[29])); tmp[30] = fma(v[0], m[636], fma(v[1], m[637], tmp[30])); tmp[31] = fma(v[0], m[638], fma(v[1], m[639], tmp[31])); v[0] = psi[I + d2 + d4]; v[1] = psi[I + d0 + d2 + d4]; tmp[0] = fma(v[0], m[640], fma(v[1], m[641], tmp[0])); tmp[1] = fma(v[0], m[642], fma(v[1], m[643], tmp[1])); tmp[2] = fma(v[0], m[644], fma(v[1], m[645], tmp[2])); tmp[3] = fma(v[0], m[646], fma(v[1], m[647], tmp[3])); tmp[4] = fma(v[0], m[648], fma(v[1], m[649], tmp[4])); tmp[5] = fma(v[0], m[650], fma(v[1], m[651], tmp[5])); tmp[6] = fma(v[0], m[652], fma(v[1], m[653], tmp[6])); tmp[7] = fma(v[0], m[654], fma(v[1], m[655], tmp[7])); tmp[8] = fma(v[0], m[656], fma(v[1], m[657], tmp[8])); tmp[9] = fma(v[0], m[658], fma(v[1], m[659], tmp[9])); tmp[10] = fma(v[0], m[660], fma(v[1], m[661], tmp[10])); tmp[11] = fma(v[0], m[662], fma(v[1], m[663], tmp[11])); tmp[12] = fma(v[0], m[664], fma(v[1], m[665], tmp[12])); tmp[13] = fma(v[0], m[666], fma(v[1], m[667], tmp[13])); tmp[14] = fma(v[0], m[668], fma(v[1], m[669], tmp[14])); tmp[15] = fma(v[0], m[670], fma(v[1], m[671], tmp[15])); tmp[16] = fma(v[0], m[672], fma(v[1], m[673], tmp[16])); tmp[17] = fma(v[0], m[674], fma(v[1], m[675], tmp[17])); tmp[18] = fma(v[0], m[676], fma(v[1], m[677], tmp[18])); tmp[19] = fma(v[0], m[678], fma(v[1], m[679], tmp[19])); tmp[20] = fma(v[0], m[680], fma(v[1], m[681], tmp[20])); tmp[21] = fma(v[0], m[682], fma(v[1], m[683], tmp[21])); tmp[22] = fma(v[0], m[684], fma(v[1], m[685], tmp[22])); tmp[23] = fma(v[0], m[686], fma(v[1], m[687], tmp[23])); tmp[24] = fma(v[0], m[688], fma(v[1], m[689], tmp[24])); tmp[25] = fma(v[0], m[690], fma(v[1], m[691], tmp[25])); tmp[26] = fma(v[0], m[692], fma(v[1], m[693], tmp[26])); tmp[27] = fma(v[0], m[694], fma(v[1], m[695], tmp[27])); tmp[28] = fma(v[0], m[696], fma(v[1], m[697], tmp[28])); tmp[29] = fma(v[0], m[698], fma(v[1], m[699], tmp[29])); tmp[30] = fma(v[0], m[700], fma(v[1], m[701], tmp[30])); tmp[31] = fma(v[0], m[702], fma(v[1], m[703], tmp[31])); v[0] = psi[I + d1 + d2 + d4]; v[1] = psi[I + d0 + d1 + d2 + d4]; tmp[0] = fma(v[0], m[704], fma(v[1], m[705], tmp[0])); tmp[1] = fma(v[0], m[706], fma(v[1], m[707], tmp[1])); tmp[2] = fma(v[0], m[708], fma(v[1], m[709], tmp[2])); tmp[3] = fma(v[0], m[710], fma(v[1], m[711], tmp[3])); tmp[4] = fma(v[0], m[712], fma(v[1], m[713], tmp[4])); tmp[5] = fma(v[0], m[714], fma(v[1], m[715], tmp[5])); tmp[6] = fma(v[0], m[716], fma(v[1], m[717], tmp[6])); tmp[7] = fma(v[0], m[718], fma(v[1], m[719], tmp[7])); tmp[8] = fma(v[0], m[720], fma(v[1], m[721], tmp[8])); tmp[9] = fma(v[0], m[722], fma(v[1], m[723], tmp[9])); tmp[10] = fma(v[0], m[724], fma(v[1], m[725], tmp[10])); tmp[11] = fma(v[0], m[726], fma(v[1], m[727], tmp[11])); tmp[12] = fma(v[0], m[728], fma(v[1], m[729], tmp[12])); tmp[13] = fma(v[0], m[730], fma(v[1], m[731], tmp[13])); tmp[14] = fma(v[0], m[732], fma(v[1], m[733], tmp[14])); tmp[15] = fma(v[0], m[734], fma(v[1], m[735], tmp[15])); tmp[16] = fma(v[0], m[736], fma(v[1], m[737], tmp[16])); tmp[17] = fma(v[0], m[738], fma(v[1], m[739], tmp[17])); tmp[18] = fma(v[0], m[740], fma(v[1], m[741], tmp[18])); tmp[19] = fma(v[0], m[742], fma(v[1], m[743], tmp[19])); tmp[20] = fma(v[0], m[744], fma(v[1], m[745], tmp[20])); tmp[21] = fma(v[0], m[746], fma(v[1], m[747], tmp[21])); tmp[22] = fma(v[0], m[748], fma(v[1], m[749], tmp[22])); tmp[23] = fma(v[0], m[750], fma(v[1], m[751], tmp[23])); tmp[24] = fma(v[0], m[752], fma(v[1], m[753], tmp[24])); tmp[25] = fma(v[0], m[754], fma(v[1], m[755], tmp[25])); tmp[26] = fma(v[0], m[756], fma(v[1], m[757], tmp[26])); tmp[27] = fma(v[0], m[758], fma(v[1], m[759], tmp[27])); tmp[28] = fma(v[0], m[760], fma(v[1], m[761], tmp[28])); tmp[29] = fma(v[0], m[762], fma(v[1], m[763], tmp[29])); tmp[30] = fma(v[0], m[764], fma(v[1], m[765], tmp[30])); tmp[31] = fma(v[0], m[766], fma(v[1], m[767], tmp[31])); v[0] = psi[I + d3 + d4]; v[1] = psi[I + d0 + d3 + d4]; tmp[0] = fma(v[0], m[768], fma(v[1], m[769], tmp[0])); tmp[1] = fma(v[0], m[770], fma(v[1], m[771], tmp[1])); tmp[2] = fma(v[0], m[772], fma(v[1], m[773], tmp[2])); tmp[3] = fma(v[0], m[774], fma(v[1], m[775], tmp[3])); tmp[4] = fma(v[0], m[776], fma(v[1], m[777], tmp[4])); tmp[5] = fma(v[0], m[778], fma(v[1], m[779], tmp[5])); tmp[6] = fma(v[0], m[780], fma(v[1], m[781], tmp[6])); tmp[7] = fma(v[0], m[782], fma(v[1], m[783], tmp[7])); tmp[8] = fma(v[0], m[784], fma(v[1], m[785], tmp[8])); tmp[9] = fma(v[0], m[786], fma(v[1], m[787], tmp[9])); tmp[10] = fma(v[0], m[788], fma(v[1], m[789], tmp[10])); tmp[11] = fma(v[0], m[790], fma(v[1], m[791], tmp[11])); tmp[12] = fma(v[0], m[792], fma(v[1], m[793], tmp[12])); tmp[13] = fma(v[0], m[794], fma(v[1], m[795], tmp[13])); tmp[14] = fma(v[0], m[796], fma(v[1], m[797], tmp[14])); tmp[15] = fma(v[0], m[798], fma(v[1], m[799], tmp[15])); tmp[16] = fma(v[0], m[800], fma(v[1], m[801], tmp[16])); tmp[17] = fma(v[0], m[802], fma(v[1], m[803], tmp[17])); tmp[18] = fma(v[0], m[804], fma(v[1], m[805], tmp[18])); tmp[19] = fma(v[0], m[806], fma(v[1], m[807], tmp[19])); tmp[20] = fma(v[0], m[808], fma(v[1], m[809], tmp[20])); tmp[21] = fma(v[0], m[810], fma(v[1], m[811], tmp[21])); tmp[22] = fma(v[0], m[812], fma(v[1], m[813], tmp[22])); tmp[23] = fma(v[0], m[814], fma(v[1], m[815], tmp[23])); tmp[24] = fma(v[0], m[816], fma(v[1], m[817], tmp[24])); tmp[25] = fma(v[0], m[818], fma(v[1], m[819], tmp[25])); tmp[26] = fma(v[0], m[820], fma(v[1], m[821], tmp[26])); tmp[27] = fma(v[0], m[822], fma(v[1], m[823], tmp[27])); tmp[28] = fma(v[0], m[824], fma(v[1], m[825], tmp[28])); tmp[29] = fma(v[0], m[826], fma(v[1], m[827], tmp[29])); tmp[30] = fma(v[0], m[828], fma(v[1], m[829], tmp[30])); tmp[31] = fma(v[0], m[830], fma(v[1], m[831], tmp[31])); v[0] = psi[I + d1 + d3 + d4]; v[1] = psi[I + d0 + d1 + d3 + d4]; tmp[0] = fma(v[0], m[832], fma(v[1], m[833], tmp[0])); tmp[1] = fma(v[0], m[834], fma(v[1], m[835], tmp[1])); tmp[2] = fma(v[0], m[836], fma(v[1], m[837], tmp[2])); tmp[3] = fma(v[0], m[838], fma(v[1], m[839], tmp[3])); tmp[4] = fma(v[0], m[840], fma(v[1], m[841], tmp[4])); tmp[5] = fma(v[0], m[842], fma(v[1], m[843], tmp[5])); tmp[6] = fma(v[0], m[844], fma(v[1], m[845], tmp[6])); tmp[7] = fma(v[0], m[846], fma(v[1], m[847], tmp[7])); tmp[8] = fma(v[0], m[848], fma(v[1], m[849], tmp[8])); tmp[9] = fma(v[0], m[850], fma(v[1], m[851], tmp[9])); tmp[10] = fma(v[0], m[852], fma(v[1], m[853], tmp[10])); tmp[11] = fma(v[0], m[854], fma(v[1], m[855], tmp[11])); tmp[12] = fma(v[0], m[856], fma(v[1], m[857], tmp[12])); tmp[13] = fma(v[0], m[858], fma(v[1], m[859], tmp[13])); tmp[14] = fma(v[0], m[860], fma(v[1], m[861], tmp[14])); tmp[15] = fma(v[0], m[862], fma(v[1], m[863], tmp[15])); tmp[16] = fma(v[0], m[864], fma(v[1], m[865], tmp[16])); tmp[17] = fma(v[0], m[866], fma(v[1], m[867], tmp[17])); tmp[18] = fma(v[0], m[868], fma(v[1], m[869], tmp[18])); tmp[19] = fma(v[0], m[870], fma(v[1], m[871], tmp[19])); tmp[20] = fma(v[0], m[872], fma(v[1], m[873], tmp[20])); tmp[21] = fma(v[0], m[874], fma(v[1], m[875], tmp[21])); tmp[22] = fma(v[0], m[876], fma(v[1], m[877], tmp[22])); tmp[23] = fma(v[0], m[878], fma(v[1], m[879], tmp[23])); tmp[24] = fma(v[0], m[880], fma(v[1], m[881], tmp[24])); tmp[25] = fma(v[0], m[882], fma(v[1], m[883], tmp[25])); tmp[26] = fma(v[0], m[884], fma(v[1], m[885], tmp[26])); tmp[27] = fma(v[0], m[886], fma(v[1], m[887], tmp[27])); tmp[28] = fma(v[0], m[888], fma(v[1], m[889], tmp[28])); tmp[29] = fma(v[0], m[890], fma(v[1], m[891], tmp[29])); tmp[30] = fma(v[0], m[892], fma(v[1], m[893], tmp[30])); tmp[31] = fma(v[0], m[894], fma(v[1], m[895], tmp[31])); v[0] = psi[I + d2 + d3 + d4]; v[1] = psi[I + d0 + d2 + d3 + d4]; tmp[0] = fma(v[0], m[896], fma(v[1], m[897], tmp[0])); tmp[1] = fma(v[0], m[898], fma(v[1], m[899], tmp[1])); tmp[2] = fma(v[0], m[900], fma(v[1], m[901], tmp[2])); tmp[3] = fma(v[0], m[902], fma(v[1], m[903], tmp[3])); tmp[4] = fma(v[0], m[904], fma(v[1], m[905], tmp[4])); tmp[5] = fma(v[0], m[906], fma(v[1], m[907], tmp[5])); tmp[6] = fma(v[0], m[908], fma(v[1], m[909], tmp[6])); tmp[7] = fma(v[0], m[910], fma(v[1], m[911], tmp[7])); tmp[8] = fma(v[0], m[912], fma(v[1], m[913], tmp[8])); tmp[9] = fma(v[0], m[914], fma(v[1], m[915], tmp[9])); tmp[10] = fma(v[0], m[916], fma(v[1], m[917], tmp[10])); tmp[11] = fma(v[0], m[918], fma(v[1], m[919], tmp[11])); tmp[12] = fma(v[0], m[920], fma(v[1], m[921], tmp[12])); tmp[13] = fma(v[0], m[922], fma(v[1], m[923], tmp[13])); tmp[14] = fma(v[0], m[924], fma(v[1], m[925], tmp[14])); tmp[15] = fma(v[0], m[926], fma(v[1], m[927], tmp[15])); tmp[16] = fma(v[0], m[928], fma(v[1], m[929], tmp[16])); tmp[17] = fma(v[0], m[930], fma(v[1], m[931], tmp[17])); tmp[18] = fma(v[0], m[932], fma(v[1], m[933], tmp[18])); tmp[19] = fma(v[0], m[934], fma(v[1], m[935], tmp[19])); tmp[20] = fma(v[0], m[936], fma(v[1], m[937], tmp[20])); tmp[21] = fma(v[0], m[938], fma(v[1], m[939], tmp[21])); tmp[22] = fma(v[0], m[940], fma(v[1], m[941], tmp[22])); tmp[23] = fma(v[0], m[942], fma(v[1], m[943], tmp[23])); tmp[24] = fma(v[0], m[944], fma(v[1], m[945], tmp[24])); tmp[25] = fma(v[0], m[946], fma(v[1], m[947], tmp[25])); tmp[26] = fma(v[0], m[948], fma(v[1], m[949], tmp[26])); tmp[27] = fma(v[0], m[950], fma(v[1], m[951], tmp[27])); tmp[28] = fma(v[0], m[952], fma(v[1], m[953], tmp[28])); tmp[29] = fma(v[0], m[954], fma(v[1], m[955], tmp[29])); tmp[30] = fma(v[0], m[956], fma(v[1], m[957], tmp[30])); tmp[31] = fma(v[0], m[958], fma(v[1], m[959], tmp[31])); v[0] = psi[I + d1 + d2 + d3 + d4]; v[1] = psi[I + d0 + d1 + d2 + d3 + d4]; tmp[0] = fma(v[0], m[960], fma(v[1], m[961], tmp[0])); tmp[1] = fma(v[0], m[962], fma(v[1], m[963], tmp[1])); tmp[2] = fma(v[0], m[964], fma(v[1], m[965], tmp[2])); tmp[3] = fma(v[0], m[966], fma(v[1], m[967], tmp[3])); psi[I] = tmp[0]; psi[I + d0] = tmp[1]; psi[I + d1] = tmp[2]; psi[I + d0 + d1] = tmp[3]; tmp[4] = fma(v[0], m[968], fma(v[1], m[969], tmp[4])); tmp[5] = fma(v[0], m[970], fma(v[1], m[971], tmp[5])); tmp[6] = fma(v[0], m[972], fma(v[1], m[973], tmp[6])); tmp[7] = fma(v[0], m[974], fma(v[1], m[975], tmp[7])); psi[I + d2] = tmp[4]; psi[I + d0 + d2] = tmp[5]; psi[I + d1 + d2] = tmp[6]; psi[I + d0 + d1 + d2] = tmp[7]; tmp[8] = fma(v[0], m[976], fma(v[1], m[977], tmp[8])); tmp[9] = fma(v[0], m[978], fma(v[1], m[979], tmp[9])); tmp[10] = fma(v[0], m[980], fma(v[1], m[981], tmp[10])); tmp[11] = fma(v[0], m[982], fma(v[1], m[983], tmp[11])); psi[I + d3] = tmp[8]; psi[I + d0 + d3] = tmp[9]; psi[I + d1 + d3] = tmp[10]; psi[I + d0 + d1 + d3] = tmp[11]; tmp[12] = fma(v[0], m[984], fma(v[1], m[985], tmp[12])); tmp[13] = fma(v[0], m[986], fma(v[1], m[987], tmp[13])); tmp[14] = fma(v[0], m[988], fma(v[1], m[989], tmp[14])); tmp[15] = fma(v[0], m[990], fma(v[1], m[991], tmp[15])); psi[I + d2 + d3] = tmp[12]; psi[I + d0 + d2 + d3] = tmp[13]; psi[I + d1 + d2 + d3] = tmp[14]; psi[I + d0 + d1 + d2 + d3] = tmp[15]; tmp[16] = fma(v[0], m[992], fma(v[1], m[993], tmp[16])); tmp[17] = fma(v[0], m[994], fma(v[1], m[995], tmp[17])); tmp[18] = fma(v[0], m[996], fma(v[1], m[997], tmp[18])); tmp[19] = fma(v[0], m[998], fma(v[1], m[999], tmp[19])); psi[I + d4] = tmp[16]; psi[I + d0 + d4] = tmp[17]; psi[I + d1 + d4] = tmp[18]; psi[I + d0 + d1 + d4] = tmp[19]; tmp[20] = fma(v[0], m[1000], fma(v[1], m[1001], tmp[20])); tmp[21] = fma(v[0], m[1002], fma(v[1], m[1003], tmp[21])); tmp[22] = fma(v[0], m[1004], fma(v[1], m[1005], tmp[22])); tmp[23] = fma(v[0], m[1006], fma(v[1], m[1007], tmp[23])); psi[I + d2 + d4] = tmp[20]; psi[I + d0 + d2 + d4] = tmp[21]; psi[I + d1 + d2 + d4] = tmp[22]; psi[I + d0 + d1 + d2 + d4] = tmp[23]; tmp[24] = fma(v[0], m[1008], fma(v[1], m[1009], tmp[24])); tmp[25] = fma(v[0], m[1010], fma(v[1], m[1011], tmp[25])); tmp[26] = fma(v[0], m[1012], fma(v[1], m[1013], tmp[26])); tmp[27] = fma(v[0], m[1014], fma(v[1], m[1015], tmp[27])); psi[I + d3 + d4] = tmp[24]; psi[I + d0 + d3 + d4] = tmp[25]; psi[I + d1 + d3 + d4] = tmp[26]; psi[I + d0 + d1 + d3 + d4] = tmp[27]; tmp[28] = fma(v[0], m[1016], fma(v[1], m[1017], tmp[28])); tmp[29] = fma(v[0], m[1018], fma(v[1], m[1019], tmp[29])); tmp[30] = fma(v[0], m[1020], fma(v[1], m[1021], tmp[30])); tmp[31] = fma(v[0], m[1022], fma(v[1], m[1023], tmp[31])); psi[I + d2 + d3 + d4] = tmp[28]; psi[I + d0 + d2 + d3 + d4] = tmp[29]; psi[I + d1 + d2 + d3 + d4] = tmp[30]; psi[I + d0 + d1 + d2 + d3 + d4] = tmp[31]; } // bit indices id[.] are given from high to low (e.g. control first for CNOT) template <class V, class M> void kernel(V& psi, unsigned id4, unsigned id3, unsigned id2, unsigned id1, unsigned id0, M const& matrix, std::size_t ctrlmask) { std::size_t n = psi.size(); std::size_t d0 = 1ULL << id0; std::size_t d1 = 1ULL << id1; std::size_t d2 = 1ULL << id2; std::size_t d3 = 1ULL << id3; std::size_t d4 = 1ULL << id4; auto m = matrix; std::size_t dsorted[] = {d0, d1, d2, d3, d4}; permute_qubits_and_matrix(dsorted, 5, m); std::complex<double> mm[1024]; for (unsigned b = 0; b < 16; ++b){ for (unsigned r = 0; r < 32; ++r){ for (unsigned c = 0; c < 2; ++c){ mm[b*64+r*2+c] = m[r][c+b*2]; } } } #ifndef _MSC_VER if (ctrlmask == 0){ #pragma omp for collapse(LOOP_COLLAPSE5) schedule(static) for (std::size_t i0 = 0; i0 < n; i0 += 2 * dsorted[0]){ for (std::size_t i1 = 0; i1 < dsorted[0]; i1 += 2 * dsorted[1]){ for (std::size_t i2 = 0; i2 < dsorted[1]; i2 += 2 * dsorted[2]){ for (std::size_t i3 = 0; i3 < dsorted[2]; i3 += 2 * dsorted[3]){ for (std::size_t i4 = 0; i4 < dsorted[3]; i4 += 2 * dsorted[4]){ for (std::size_t i5 = 0; i5 < dsorted[4]; ++i5){ kernel_core(psi, i0 + i1 + i2 + i3 + i4 + i5, dsorted[4], dsorted[3], dsorted[2], dsorted[1], dsorted[0], mm); } } } } } } } else{ #pragma omp for collapse(LOOP_COLLAPSE5) schedule(static) for (std::size_t i0 = 0; i0 < n; i0 += 2 * dsorted[0]){ for (std::size_t i1 = 0; i1 < dsorted[0]; i1 += 2 * dsorted[1]){ for (std::size_t i2 = 0; i2 < dsorted[1]; i2 += 2 * dsorted[2]){ for (std::size_t i3 = 0; i3 < dsorted[2]; i3 += 2 * dsorted[3]){ for (std::size_t i4 = 0; i4 < dsorted[3]; i4 += 2 * dsorted[4]){ for (std::size_t i5 = 0; i5 < dsorted[4]; ++i5){ if (((i0 + i1 + i2 + i3 + i4 + i5)&ctrlmask) == ctrlmask) kernel_core(psi, i0 + i1 + i2 + i3 + i4 + i5, dsorted[4], dsorted[3], dsorted[2], dsorted[1], dsorted[0], mm); } } } } } } } #else std::intptr_t zero = 0; std::intptr_t dmask = dsorted[0] + dsorted[1] + dsorted[2] + dsorted[3] + dsorted[4]; if (ctrlmask == 0){ #pragma omp parallel for schedule(static) for (std::intptr_t i = 0; i < static_cast<std::intptr_t>(n); ++i) if ((i & dmask) == zero) kernel_core(psi, i, dsorted[4], dsorted[3], dsorted[2], dsorted[1], dsorted[0], mm); } else { #pragma omp parallel for schedule(static) for (std::intptr_t i = 0; i < static_cast<std::intptr_t>(n); ++i) if ((i & ctrlmask) == ctrlmask && (i & dmask) == zero) kernel_core(psi, i, dsorted[4], dsorted[3], dsorted[2], dsorted[1], dsorted[0], mm); } #endif }
#! /usr/bin/env sh php -n -c php.ini ./vendor/bin/phpunit -c phpunit.xml
package com.kinstalk.satellite.socket; import com.kinstalk.satellite.common.constant.ConstantSocket; import com.kinstalk.satellite.domain.packet.SocketPacket; import com.kinstalk.satellite.socket.manager.ManagerData; import com.kinstalk.satellite.socket.manager.ManagerHandler; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.RejectedExecutionException; /** * Created by digitZhang on 16/5/12. */ public class SocketThread { private Logger logger = LoggerFactory.getLogger(SocketThread.class); private int ack; private String ip; private int port; private Agent agent; private ChannelFuture channelFuture; private EventLoopGroup group; // 管理的数据 private ManagerData managerData; // socket 连接状态 private int SOCKET_STATUS = ConstantSocket.CONNECT_DEFAULT; // Socket状态 ConstantSocket.CONNECT_* public SocketThread(Agent agent) { this.agent = agent; this.ip = agent.getIp(); this.port = agent.getPort(); managerData = new ManagerData(); } public void run() { connect(); } public void start() { new Thread() { public void run() { try { connect(); } finally { logger.debug("Thread run over!"); } } }.start(); } public void disconnect() { channelFuture.channel().close(); } public void send(SocketPacket packet) { try { // 更新ack packet.setAck(incrAck()); // 记录发送状态 managerData.addPacketStatus(agent, packet); // 写数据 channelFuture.channel().write(packet); channelFuture.channel().flush(); logger.debug("send " + packet); } catch(RejectedExecutionException e ) { // AgentManager.getOnlineAgent().remove(agent.getIp()); // logger.error("agent is offline! " + agent); } } // 获取连接状态 public boolean getSocketStatus() { boolean result = false; try { if(SOCKET_STATUS == ConstantSocket.CONNECT_SUCC) { result = true; } else if(SOCKET_STATUS == ConstantSocket.CONNECT_DEFAULT || SOCKET_STATUS == ConstantSocket.CONNECT_ON) { long startMilli = System.currentTimeMillis(); while(System.currentTimeMillis() - startMilli < ConstantSocket.MAX_RECONNECT_SECONDS * 1000 ) { if(SOCKET_STATUS == ConstantSocket.CONNECT_SUCC) { result = true; break; } Thread.sleep(10); } logger.debug("isConnecting spend " + (System.currentTimeMillis() - startMilli) + "ms"); } } catch (InterruptedException e) { e.printStackTrace(); } return result; } private void connect() { //配置客户端线程组 group=new NioEventLoopGroup(); try { logger.info("socket connect start!"); // 开始连接 SOCKET_STATUS = ConstantSocket.CONNECT_ON; //配置客户端启动辅助类 Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { //添加POJO对象解码器 禁止缓存类加载器 ch.pipeline().addLast(new ObjectDecoder(ConstantSocket.MAX_SOCKET_PACKET_LENGTH, ClassResolvers.cacheDisabled(this.getClass().getClassLoader()))); //设置发送消息编码器 ch.pipeline().addLast(new ObjectEncoder()); //设置网络IO处理器 ch.pipeline().addLast(new ManagerHandler(managerData)); } }); //发起异步服务器连接请求 同步等待成功 channelFuture = b.connect(ip, port).sync(); logger.info("socket connect success! agent[{}:{}]", ip, port); // 连接成功 SOCKET_STATUS = ConstantSocket.CONNECT_SUCC; //等到客户端链路关闭 channelFuture.channel().closeFuture().sync(); } catch (Exception e) { logger.error("socket offline! agent[{}:{}]", this.ip, this.port, e); } finally{ //优雅释放线程资源 group.shutdownGracefully(); SOCKET_STATUS = ConstantSocket.CONNECT_DEFAULT; logger.info("socket close!agent[{}:{}]", this.ip, this.port); } } private int incrAck() { ack++; if(ack > ConstantSocket.MAX_ACK) { ack = 1; } return ack; } }
class Stage { constructor(canvas) { this.canvas = canvas; this.width = this.canvas.width; this.height = this.canvas.height; this.ctx = canvas.getContext("2d"); } clear(color) { if (color) { this.ctx.save(); this.ctx.fillStyle = color; this.ctx.fillRect(0, 0, this.width, this.height); this.ctx.restore(); } else { this.ctx.clearRect(0, 0, this.width, this.height); } } drawText(text, font = "bold 48px sans-serif") { this.ctx.font = font; const textWidth = this.ctx.measureText(text).width; this.ctx.fillText( text, this.width / 2 - textWidth / 2, this.height / 2 ); } setScale(scale) { this.scale = scale; this.resize(); } setWidth(width) { this.width = width; this.resize(); } setHeight(height) { this.height = height; this.resize(); } resize() { this.canvas.width = this.width; this.canvas.style.width = `${this.width / this.scale}px`; this.canvas.height = this.height; this.canvas.style.height = `${this.height / this.scale}px`; } } export default Stage;
// // CKCalendarCalendarView.h // MBCalendarKit // // Created by <NAME> on 4/10/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "CKCalendarViewModes.h" #import "CKCalendarEvent.h" #import "CKCalendarDelegate.h" #import "CKCalendarDataSource.h" @interface CKCalendarView : UIView @property (nonatomic, assign) CKCalendarDisplayMode displayMode; @property(nonatomic, strong) NSLocale *locale; // default is [NSLocale currentLocale]. setting nil returns to default @property(nonatomic, copy) NSCalendar *calendar; // default is [NSCalendar currentCalendar]. setting nil returns to default @property(nonatomic, strong) NSTimeZone *timeZone; // default is nil. use current time zone or time zone from calendar @property (nonatomic, strong) NSDate *date; @property (nonatomic, strong) NSDate *minimumDate; @property (nonatomic, strong) NSDate *maximumDate; @property (nonatomic, assign) NSUInteger firstWeekDay; // Proxies to the calendar's firstWeekDay so we can update the UI immediately. @property (nonatomic, weak) id<CKCalendarViewDataSource> dataSource; @property (nonatomic, weak) id<CKCalendarViewDelegate> delegate; /* Initializer */ - (instancetype)init; - (instancetype)initWithMode:(CKCalendarDisplayMode)CalendarDisplayMode; /* Reload calendar and events. */ - (void)reload; - (void)reloadAnimated:(BOOL)animated; /* Setters */ - (void)setCalendar:(NSCalendar *)calendar; - (void)setCalendar:(NSCalendar *)calendar animated:(BOOL)animated; - (void)setDate:(NSDate *)date; - (void)setDate:(NSDate *)date animated:(BOOL)animated; - (void)setDisplayMode:(CKCalendarDisplayMode)displayMode; - (void)setDisplayMode:(CKCalendarDisplayMode)displayMode animated:(BOOL)animated; - (void)setLocale:(NSLocale *)locale; - (void)setLocale:(NSLocale *)locale animated:(BOOL)animated; - (void)setTimeZone:(NSTimeZone *)timeZone; - (void)setTimeZone:(NSTimeZone *)timeZone animated:(BOOL)animated; - (void)setMinimumDate:(NSDate *)minimumDate; - (void)setMinimumDate:(NSDate *)minimumDate animated:(BOOL)animated; - (void)setMaximumDate:(NSDate *)maximumDate; - (void)setMaximumDate:(NSDate *)maximumDate animated:(BOOL)animated; /* Visible Dates */ - (NSDate *)firstVisibleDate; - (NSDate *)lastVisibleDate; @end
// // Created by claul on 6/7/2020. // #ifndef RAYTRACINGINONEWEEKEND_COLOUR_H #define RAYTRACINGINONEWEEKEND_COLOUR_H #include "Vec3.h" #include "Ray.h" #include "../Assets/Collidables.h" #include <iostream> void write_colour(std::ostream& out, Colour pixel_colour, int samplesPerPixel) { // divide colours by the number of pixels auto scale = 1.0 / samplesPerPixel; // more samples = less jagged auto r = sqrt(scale * pixel_colour.x()); auto g = sqrt(scale * pixel_colour.y()); auto b = sqrt(scale * pixel_colour.z()); out << static_cast<int>(256 * clamp(r, 0.0, 0.999)) << ' ' << static_cast<int>(256 * clamp(g, 0.0, 0.999)) << ' ' << static_cast<int>(256 * clamp(b, 0.0, 0.999)) << '\n'; } static Colour rayColours(const Ray& r, const Collidables& world, const int depth) { // cut the recursion if it hit the limit of surfaces to bounce off of if (depth <= 0) { return {0, 0, 0}; } constexpr double infinity = std::numeric_limits<double>::infinity(); HitRecord hitRecord{}; bool hasHit = world.hit(r, 0.001, infinity, hitRecord); // 0.001 to prevent shadow acne // adjust colour if it hit to demonstrate shading if (hasHit) { Ray scattered; Colour attenuation; if (hitRecord.materialPtr->scatterLight(r, hitRecord, attenuation, scattered)) { return attenuation * rayColours(scattered, world, depth - 1); } return Colour{0, 0, 0}; } Vec3 unitDirection = Vec3::unit_vector(r.getDirection()); auto closestHitPoint = 0.5 * (unitDirection.y() + 1.0); // goes from 0 to 1 aka bottom to top // linear blend: start value end value return (1.0 - closestHitPoint) * Colour(1.0, 1.0, 1.0) + closestHitPoint * Colour(0.5, 0.7, 1.0); } #endif //RAYTRACINGINONEWEEKEND_COLOUR_H
#!/bin/sh #sbatch --job-name=KQH_mlp --gres=gpu:1 --mem=65536 --cpus-per-task=4 --output=./output/output_train_mlp.out launch_train_mlp.sh python3 train.py
package com.md.appuserconnect.core.services.internal.statistics; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.md.appuserconnect.core.model.QNObjectManager; import com.md.appuserconnect.core.model.accounts.Account; import com.md.appuserconnect.core.model.statistics.StatisticsManager; import com.md.appuserconnect.core.model.statistics.StatisticsTransfer; import com.md.appuserconnect.core.utils.RRServices; @SuppressWarnings("serial") public class StatisticsKONA extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (RRServices.checkUserIsAdministrator(req, resp)) { PrintWriter writ = resp.getWriter(); HashMap<String, Object> params = RRServices.loadInputParameters(req, false); String action = (String) params.get("action"); String dateFrom = (String) params.get("datefrom"); String dateTo = (String) params.get("dateto"); String appBundle = (String) params.get("appbundle"); if (action != null && action.equalsIgnoreCase("transfer")) { Date fromDate = new Date((new Date().getTime()) - 1209600000); if (dateFrom != null) { try { fromDate = StatisticsManager.convert2Date(dateFrom); } catch (ParseException e) { e.printStackTrace(); } } Date toDate = new Date(); if (dateTo != null) { try { toDate = StatisticsManager.convert2Date(dateTo); } catch (ParseException e) { e.printStackTrace(); } } resp.setContentType("text/html"); Account acc = QNObjectManager.getInstance().getAccMgr().getAccountOfUser(); if (acc != null) { StatisticsTransfer transfer = new StatisticsTransfer(); String answer = transfer.transferStatistics(acc, fromDate, toDate, appBundle); resp.getWriter().println(answer); } } else { SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); Date fromDate = new Date((new Date().getTime()) - 1209600000); Date toDate = new Date(); resp.setContentType("text/html"); writ.println("<html><head><title>Load Statistics</title></head><body>"); writ.println("<form method='GET'><table>"); writ.println("<tr><td>From Date</td><td><input type='input' name='datefrom' value='" + dateFormat.format(fromDate) + "'/></td></tr>"); writ.println("<tr><td>To Date</td><td><input type='input' name='dateto' value='" + dateFormat.format(toDate) + "'/></td></tr>"); writ.println("<tr><td>AppBundle</td><td><input type='input' name='appbundle'/></td></tr>"); writ.println("</table>"); writ.println("<input type='hidden' name='action' value='transfer'/><input type='submit' value='select'/></form>"); writ.println("</body></html>"); } } } }
# Ping Google Public DNS IP address. while true; do ping 8.8.8.8; done
#!/usr/bin/env bash set -e; if [ ! -f package.json ]; then echo "there is no package.json file in your PWD." >&2; false; // since there is no package.json file, probably should abort here fi map="$docker_r2g_fs_map" search_root="$docker_r2g_search_root" shared="$docker_r2g_shared_dir"; name="$docker_r2g_package_name" # your project's package.json name field base_image="node:$r2g_node_version" container="docker_r2g.$name"; docker stop "$container" || echo "no container with name $container running." docker rm "$container" || echo "no container with name $container could be removed." tag="docker_r2g_image/$name"; docker build \ -f Dockerfile.r2g \ -t "$tag" \ --build-arg base_image="$base_image" \ --build-arg CACHEBUST="$(date +%s)" . docker run \ -v "$search_root:$shared:ro" \ -e docker_r2g_fs_map="$map" \ -e r2g_container_id="$container" \ --entrypoint "dkr2g" \ --name "$container" "$tag" \ run --allow-unknown "$@" ## to debug: # docker exec -ti <container-name> /bin/bash
import { SignInPayload } from 'app/pages/SignIn/types'; import { AdminSignInParams } from './types'; export const adminSignInAdapter = ( userPayload: SignInPayload, ): AdminSignInParams => { return { admin: { email: userPayload.email, password: <PASSWORD>, }, }; };
#pragma once #include <KAI/Core/Config/Base.h> #include <KAI/Core/Type/Number.h> #include "KAI/Core/Object/PropertyBase.h" #include "KAI/Core/Object/Label.h" KAI_BEGIN class AccessorBase : public PropertyBase { public: AccessorBase(Label const &F, Type::Number C, Type::Number N, bool is_system, typename MemberCreateParams::Enum CP) : PropertyBase(F, C, N, is_system, CP) { } void SetValue(Object const &, Object const &) const { KAI_THROW_0(ConstError); } }; class MutatorBase : public AccessorBase { public: MutatorBase(Label const &F, Type::Number C, Type::Number N , bool is_system, typename MemberCreateParams::Enum CP) : AccessorBase(F, C, N, is_system, CP) { } Object GetValue(Object const &Q) const { if (!IsSystemType()) KAI_THROW_0(ConstError); return GetPropertyObject(Q, GetFieldName()); } }; KAI_END
#!/bin/bash # Copyright (c) 2019 London Trust Media Incorporated # # This file is part of the Private Internet Access Desktop Client. # # The Private Internet Access Desktop Client 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 3 of # the License, or (at your option) any later version. # # The Private Internet Access Desktop Client 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 the Private Internet Access Desktop Client. If not, see # <https://www.gnu.org/licenses/>. set -e MODE=(release) BRAND=${BRAND:-pia} # =========================== # Instructions to run locally # =========================== # # First, Qt 5.12 or above must be installed on your system. You cannot use Qt from your # package manager. It has to be downloaded from https://www.qt.io/ # Let's say they're installed at $HOME/Qt/ # You should add the following line to your .bashrc/.zshrc: # # export QT_ROOT=$HOME/Qt/5.12.1/gcc_64/ # # QBS would then be used from $HOME/Qt/Tools/QtCreator/bin/qbs. If necessary, # you can override the QBS variable too. # # Next, install dependencies. This is for Ubuntu, but you can install the corresponding # packages for your distribution # # $ sudo apt install build-essential curl clang mesa-common-dev # # $ cd desktop # PIA source code directory # # Run the script in configure mode to setup the compiler toolchain. You only need to do this once. # $ ./scripts/build-linux.sh --configure # # Run the daemon (make sure any previously installed piavpn daemon is stopped by calling `sudo service piavpn stop` before running your own daemon) # $ sudo --preserve-env=QT_ROOT ./scripts/build-linux.sh --run-daemon # # Run the client in a separate terminal # $ ./scripts/build-linux.sh --run-client # # To build your own installer: # $ ./scripts/build-linux.sh --package # # =============== # Reproducibility # =============== # # Linux build artifacts are reproducible given the same build environment and # source directory location. A few caveats apply to the --package step. # # The build script fetches server lists (daemon/res/{servers,shadowsocks}.json) # for each build by default. # To override this, use `--server-data <dir>` to copy servers.json and # shadowsocks.json from the specified directory instead. # # The build uses the last Git commit timestamp by default. To override this, # you can set SOURCE_DATE_EPOCH=<timestamp> in the environment. # Utility functions function echoPass() { printf '\e[92m\xE2\x9C\x94\e[0m %s\n' "$@" } function echoFail() { printf '\e[91m\xE2\x9C\x98\e[0m %s\n' "$@" } function fail() { echoFail "$@" exit 1 } function last() { local FILES=( "$@" ) [ -e "${FILES[-1]}" ] || die "Unable to match file pattern" "$@" echo "${FILES[-1]}" } TASK_CONFIGURE=0 TASK_CLEAN=0 TASK_RUN_CLIENT=0 TASK_RUN_DAEMON=0 TASK_PACKAGE=0 SERVER_DATA_DIR= function canRunTask() { [ $TASK_CONFIGURE -eq 1 ] && fail "Cannot run other tasks while passing --configure" [ $TASK_RUN_CLIENT -eq 1 ] && fail "Cannot run other tasks while passing --run-client" [ $TASK_RUN_DAEMON -eq 1 ] && fail "Cannot run other tasks while passing --run-daemon" # Return true so set -e doesn't assume function failed true } if [ $# -eq 0 ]; then echo "Usage: ./scripts/build-linux.sh [--configure] [--clean] [--run-client] [--run-daemon] [--package]" exit 1 fi echo "=========================================" echo "Private Internet Access: Linux Build" echo "=========================================" while (( "$#" )); do case "$1" in --configure) canRunTask TASK_CONFIGURE=1 shift ;; --package) TASK_PACKAGE=1 shift ;; --clean) TASK_CLEAN=1 shift ;; --run-client) canRunTask TASK_RUN_CLIENT=1 shift ;; --run-daemon) canRunTask TASK_RUN_DAEMON=1 shift ;; --server-data) shift SERVER_DATA_DIR="$1" if [ -z "$SERVER_DATA_DIR" ]; then fail "--server-data requires a path to the directory containing servers.json and shadowsocks.json" fi shift ;; *) fail "Unknown option $1" ;; esac done # =========== # Setup paths # =========== # PIA root directory. All paths derived from this path ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) OUTDIR="$ROOT/out/$BRAND" # Place to build program during development BUILD_DAEMON="$OUTDIR/build-daemon" BUILD_CLIENT="$OUTDIR/build-client" BUILD_PACKAGE="$OUTDIR/build" # Look for manually specified QT_ROOT and QBS if [ -n "$QT_ROOT" ]; then if [ -z "$QBS" ]; then QBS="$(cd "$QT_ROOT/../../Tools/QtCreator/bin" && pwd)/qbs" fi echo "Using qbs at $QBS" echo "Using Qt at $QT_ROOT" # Look for Qt installed in known locations elif [ -e /opt/Qt5.12.3/ ]; then echo "Using Qt from system path" QT_ROOT="/opt/Qt5.12.3/5.12.3/gcc_64/" QBS="/opt/Qt5.12.3/Tools/QtCreator/bin/qbs" elif [ -e /opt/Qt/ ]; then # Use the latest Qt version available, 5.1*.* # (Intentional word-splitting) # shellcheck disable=SC2046 QT_ROOT=$(last $(echo "/opt/Qt/5.*/gcc_64/" | sort --version-sort)) QBS="/opt/Qt/Tools/QtCreator/bin/qbs" echo "Found qbs at $QBS" echo "Found Qt at $QT_ROOT" # If all else fails, try PATH, but this is unlikely to work if it picks up a # system-installed Qt elif hash qmake 2>/dev/null && hash qbs 2>/dev/null; then # Get the qbs from $PATH QBS="$(command -v qbs)" # Get the QT Root path QT_ROOT=$(dirname "$(command -v qmake)")/../ QT_ROOT=$(cd "$QT_ROOT" && pwd) echo "Found qbs at $QBS" echo "Found Qt at $QT_ROOT" else fail "Cannot find qmake and qbs. Please ensure Qt is installed from qt.io, and set QT_ROOT/QBS if necessary." fi if ! hash clang 2>/dev/null; then fail "Cannot find clang in your PATH" fi # Check Qt version QTVER=$("$QT_ROOT/bin/qmake" --version | tail -n +2 | awk '{print $4}') SUPPORTED_VERS="5.11.1 5.11.2 5.11.3 5.12.0 5.12.1 5.12.2 5.12.3 5.12.4" echo "Detected Qt version $QTVER" if [[ ! $SUPPORTED_VERS =~ $QTVER ]]; then fail "Invalid version. Supported Qt versions: $SUPPORTED_VERS" fi # We need to "stage" the installation for setting up the artifacts etc STAGE_ROOT="$OUTDIR/stage" # Place to store the final package ARTIFACT_PATH="$OUTDIR/artifacts" # ============ # Tasks # ============ if [ $TASK_CONFIGURE -eq 1 ]; then echo "Running task: configure" "$QBS" config --unset profiles.piaqt512 "$QBS" setup-toolchains --detect "$QBS" setup-qt "$QT_ROOT/bin/qmake" piaqt512 "$QBS" config profiles.piaqt512.baseProfile clang echoPass "Configured QBS. Profile config:" "$QBS" config --list profiles.piaqt512 fi if [ $TASK_CLEAN -eq 1 ]; then echo "Running task: clean" rm -rf "$OUTDIR" fi if [ $TASK_RUN_CLIENT -eq 1 ]; then echo "Running task: run-client" "$QBS" build profile:piaqt512 -f "$ROOT/pia_desktop.qbs" -d "$BUILD_CLIENT" config:debug "$QBS" run profile:piaqt512 -f "$ROOT/pia_desktop.qbs" -d "$BUILD_CLIENT" config:debug --products client fi if [ $TASK_RUN_DAEMON -eq 1 ]; then echo "Running task: run-daemon" # Ensure dir exists for daemon socket. sudo mkdir -p /opt/piavpn/var/ "$QBS" build profile:piaqt512 -f "$ROOT/pia_desktop.qbs" -d "$BUILD_DAEMON" config:debug "$QBS" run profile:piaqt512 -f "$ROOT/pia_desktop.qbs" -d "$BUILD_DAEMON" config:debug --products daemon fi function addQtLib() { libname=$1 echo "Adding $libname" libPath="$QT_ROOT/lib/$libname" [ -f "$libPath" ] && cp -H "$libPath" "$STAGE_ROOT/lib/$libname" true } function addQtPlugin() { libname=$1 echo "Adding plugin $libname" libPath="$QT_ROOT/plugins/$libname" [ -d "$libPath" ] && cp -r "$libPath" "$STAGE_ROOT/plugins/$libname" true } function addQmlImport () { libname=$1 echo "Adding QML Import $libname" cp -r "$QT_ROOT/qml/$libname" "$STAGE_ROOT/qml/$libname" } if [ $TASK_PACKAGE -eq 1 ]; then # Clear the stage path and create a new one [ -d "$STAGE_ROOT" ] && rm -rf "$STAGE_ROOT" mkdir -p "$STAGE_ROOT" rm -rf "$ARTIFACT_PATH" mkdir -p "$ARTIFACT_PATH" # Create required dirs mkdir -p "$STAGE_ROOT/lib" mkdir -p "$STAGE_ROOT/plugins" mkdir -p "$STAGE_ROOT/qml" echoPass "Created staging root" addQtLib "libicudata.so.56" addQtLib "libicui18n.so.56" addQtLib "libicuuc.so.56" addQtLib "libQt5Core.so.5" addQtLib "libQt5DBus.so.5" addQtLib "libQt5Gui.so.5" addQtLib "libQt5Network.so.5" addQtLib "libQt5Qml.so.5" addQtLib "libQt5QuickControls2.so.5" addQtLib "libQt5Quick.so.5" addQtLib "libQt5QuickShapes.so.5" addQtLib "libQt5QuickTemplates2.so.5" addQtLib "libQt5Widgets.so.5" addQtLib "libQt5XcbQpa.so.5" # Extra, we need to include a libssl that's compatible with Qt. cp "$ROOT/extras/installer/linux/libssl.so" "$STAGE_ROOT/lib/libssl.so" cp "$ROOT/extras/installer/linux/libcrypto.so" "$STAGE_ROOT/lib/libcrypto.so" addQtPlugin "platforms" addQtPlugin "egldeviceintegrations" addQtPlugin "xcbglintegrations" addQmlImport "builtins.qmltypes" addQmlImport "QtGraphicalEffects" addQmlImport "QtQml" addQmlImport "Qt" addQmlImport "QtQuick.2" addQmlImport "QtQuick" if [ -z "$SERVER_DATA_DIR" ]; then curl -o "$ROOT/daemon/res/json/servers.json" "https://www.privateinternetaccess.com/vpninfo/servers?version=1001&client=x-alpha" || fail "unable to fetch region list" curl -o "$ROOT/daemon/res/json/shadowsocks.json" "https://www.privateinternetaccess.com/vpninfo/shadowsocks_servers" || fail "unable to fetch shadowsocks region list" else echo "Using servers.json and shadowsocks.json from $SERVER_DATA_DIR" cp "$SERVER_DATA_DIR/servers.json" "$ROOT/daemon/res/json/servers.json" cp "$SERVER_DATA_DIR/shadowsocks.json" "$ROOT/daemon/res/json/shadowsocks.json" fi # Set the LD_LIBRARY_PATH so it's picked up by rpath export LD_LIBRARY_PATH="$STAGE_ROOT/lib" for CONFIG in "${MODE[@]}"; do # We want to use "$ORIGIN" in the string including the "$" so we single quote it, shellcheck assumes it's an error # shellcheck disable=SC2016 "$QBS" build profile:piaqt512 -f "$ROOT/pia_desktop.qbs" -d "$BUILD_PACKAGE" config:"$CONFIG" modules.cpp.rpaths:\[\"'$ORIGIN/../lib'\"\] project.brandCode:"$BRAND" --all-products { read -r VERSION; read -r PRODUCTNAME; read -r PACKAGENAME; read -r BUILDTIMESTAMP; } < "$BUILD_PACKAGE/$CONFIG/version/version.txt" { read -r BRAND_NAME; read -r BRAND_CODE; } < "$BUILD_PACKAGE/$CONFIG/brand/brand.txt" echo "Building package for version $CONFIG" # Create a folder to stage the new build PKGROOT="$BUILD_PACKAGE/$PACKAGENAME" [ -d "$PKGROOT" ] && rm -rf "$PKGROOT" # The piafiles folder which would contain all the pia files to deploy PIA_FILES="$PKGROOT/piafiles" mkdir -p "$PIA_FILES" # Copy installer to root of package cp "$ROOT/extras/installer/linux/linux_installer.sh" "$PKGROOT/install.sh" chmod +x "$PKGROOT/install.sh" # Copy compiled binaries cp -r "$BUILD_PACKAGE/$CONFIG/install-root/"* "$PIA_FILES" # Copy the qt.conf to the same path as all binaries cp "$ROOT/extras/installer/linux/linux-qt.conf" "$PIA_FILES/bin/qt.conf" # Copy the version file as package.txt so the installer can use it # Also copy all the install files cp "$BUILD_PACKAGE/$CONFIG/version/version.txt" "$PKGROOT/package.txt" cp -r "$ROOT/extras/installer/linux/installfiles/" "$PKGROOT/installfiles/" cp "$ROOT/brands/$BRAND_CODE/icons/app.png" "$PKGROOT/installfiles/app.png" BRAND_SUBSTITUTION="s/{{BRAND_CODE}}/${BRAND_CODE}/g; s/{{BRAND_NAME}}/${BRAND_NAME}/g" # Recursively find all files in PKGROOT and perform `sed` to do an in-place replace. This touches # various files in `installfiles`. # # It's important to do this before copying all the PIA_FILES find "$PKGROOT/installfiles/" -type f -exec sed -i "$BRAND_SUBSTITUTION" {} \; # Perform the substitution on other files sed -i "$BRAND_SUBSTITUTION" "$PKGROOT/install.sh" sed -i "$BRAND_SUBSTITUTION" "$PIA_FILES/bin/qt.conf" cp -r "$STAGE_ROOT/"* "$PIA_FILES" cd "$BUILD_PACKAGE" # Don't embed a timestamp when gzipping export GZIP=-n "$ROOT/extras/installer/linux/makeself/makeself.sh" --tar-quietly --keep-umask --tar-extra "--mtime=@${BUILDTIMESTAMP} --sort=name --owner=0 --group=0 --numeric-owner" --packaging-date "$(date -d @"${BUILDTIMESTAMP}")" "$PACKAGENAME" "$PACKAGENAME.run" "$PRODUCTNAME" ./install.sh mv "$PACKAGENAME.run" "$ARTIFACT_PATH/$PACKAGENAME.run" echoPass "Built installer at $ARTIFACT_PATH/$PACKAGENAME.run" # Preserve unit test code coverage artifacts if [ -d "$BUILD_PACKAGE/$CONFIG/llvm-code-coverage" ]; then cp -r "$BUILD_PACKAGE/$CONFIG/llvm-code-coverage" "$ARTIFACT_PATH" fi # Copy pia-integtest as an artifact cp "$BUILD_PACKAGE/$CONFIG"/integtest-dist.*/"$BRAND_CODE-integtest.zip" "$ARTIFACT_PATH/$BRAND_CODE-integtest-$PACKAGENAME.zip" if [ -z "$PIA_BRANCH_BUILD" ] || [ "$PIA_BRANCH_BUILD" == "master" ]; then PLATFORM="linux" BRAND="$BRAND" "$ROOT/scripts/gendebug.sh" fi done fi
export SPARK_HOME="/home/book/spark-3.2.0" export SPARK_PROG="/home/book/code/chap08/rank_product/rank_product_using_groupbykey.py" # export K=3 # export STUDY_1="/home/book/code/chap08/rank_product/sample_input/rp1.txt" export STUDY_2="/home/book/code/chap08/rank_product/sample_input/rp2.txt" export STUDY_3="/home/book/code/chap08/rank_product/sample_input/rp3.txt" # export OUTPUT="/tmp/rank_product/output" # ${SPARK_HOME}/bin/spark-submit ${SPARK_PROG} ${OUTPUT} ${K} ${STUDY_1} ${STUDY_2} ${STUDY_3} output_path /tmp/rank_product/ouput K 3 studies_input_path ['/tmp/rankproduct/input/rp1.txt', '/tmp/rankproduct/input/rp2.txt', '/tmp/rankproduct/input/rp3.txt'] input_path /home/book/code/chap08/rank_product/sample_input/rp1.txt raw_genes ['K_1,30.0', 'K_2,60.0', 'K_3,10.0', 'K_4,80.0'] genes [('K_1', 30.0), ('K_2', 60.0), ('K_3', 10.0), ('K_4', 80.0)] genes_combined [('K_2', (60.0, 1)), ('K_3', (10.0, 1)), ('K_1', (30.0, 1)), ('K_4', (80.0, 1))] input_path /home/book/code/chap08/rank_product/sample_input/rp2.txt raw_genes ['K_1,90.0', 'K_2,70.0', 'K_3,40.0', 'K_4,50.0'] genes [('K_1', 90.0), ('K_2', 70.0), ('K_3', 40.0), ('K_4', 50.0)] genes_combined [('K_2', (70.0, 1)), ('K_3', (40.0, 1)), ('K_1', (90.0, 1)), ('K_4', (50.0, 1))] input_path /home/book/code/chap08/rank_product/sample_input/rp3.txt raw_genes ['K_1,4.0', 'K_2,8.0'] genes [('K_1', 4.0), ('K_2', 8.0)] genes_combined [('K_2', (8.0, 1)), ('K_1', (4.0, 1))] sorted_rdd [(80.0, 'K_4'), (60.0, 'K_2'), (30.0, 'K_1'), (10.0, 'K_3')] indexed [((80.0, 'K_4'), 0), ((60.0, 'K_2'), 1), ((30.0, 'K_1'), 2), ((10.0, 'K_3'), 3)] ranked [('K_4', 1), ('K_2', 2), ('K_1', 3), ('K_3', 4)] sorted_rdd [(90.0, 'K_1'), (70.0, 'K_2'), (50.0, 'K_4'), (40.0, 'K_3')] indexed [((90.0, 'K_1'), 0), ((70.0, 'K_2'), 1), ((50.0, 'K_4'), 2), ((40.0, 'K_3'), 3)] ranked [('K_1', 1), ('K_2', 2), ('K_4', 3), ('K_3', 4)] sorted_rdd [(8.0, 'K_2'), (4.0, 'K_1')] indexed [((8.0, 'K_2'), 0), ((4.0, 'K_1'), 1)] ranked [('K_2', 1), ('K_1', 2)]
package com.nitro.nmesos.util import org.specs2.mutable.Specification import scala.util.Success class VersionUtilSpec extends Specification { "VersionUtil" should { "extract an expected version" in { VersionUtil.tryExtract("0.2.1") must be equalTo Success(List(0, 2, 1)) VersionUtil.tryExtract("1.0.1-SNAPSHOT") must be equalTo Success(List(1, 0, 1)) VersionUtil.tryExtract("nmesos_version: '1.2.3' ## Min nmesos required to execute this config") must be equalTo Success(List(1, 2, 3)) } "extract the version of a yaml file" in { val Yaml = """## Config to deploy exampleServer to Mesos using Singularity |## | |nmesos_version: '2.0.3' ## Min nmesos required to execute this config |common: &common | image: gonitro/test """.stripMargin VersionUtil.tryExtractFromYaml(Yaml) must be equalTo Success(List(2, 0, 3)) } "Verify compatible versions" in { VersionUtil.isCompatible(requiredVersion = List(0, 0, 1), installedVersion = List(0, 1, 0)) must beTrue VersionUtil.isCompatible(requiredVersion = List(0, 0, 1), installedVersion = List(0, 0, 1)) must beTrue VersionUtil.isCompatible(requiredVersion = List(0, 0, 2), installedVersion = List(0, 0, 1)) must beFalse VersionUtil.isCompatible(requiredVersion = List(0, 1, 0), installedVersion = List(0, 1, 0)) must beTrue VersionUtil.isCompatible(requiredVersion = List(1, 1, 0), installedVersion = List(1, 1, 10)) must beTrue } } }
#!/bin/bash # This script is used to create releases for this plugin. This is mostly a helper script for the maintainer. echo "Enter the new version number (e.g. 1.2.1):" read version echo "Enter the Windows x64 release ZIP URL:" read windowsZIPURL echo "Enter the Linux x64 release ZIP URL:" read linuxZIPURL echo "Enter the MacOS universal release ZIP URL:" read macZIPURL # wget-ing the github.com URL gives a 404, so we use the method proposed here - https://github.com/actions/upload-artifact/issues/51#issuecomment-735989475 windowsZIPURL=${windowsZIPURL/github.com/nightly.link} linuxZIPURL=${linuxZIPURL/github.com/nightly.link} macZIPURL=${macZIPURL/github.com/nightly.link} wget -O windows.zip $windowsZIPURL wget -O linux.zip $linuxZIPURL wget -O mac.zip $macZIPURL unzip windows.zip -d windows/ unzip linux.zip -d linux/ unzip mac.zip -d mac/ releasePath=godot-git-plugin-v$version mkdir $releasePath cp -r windows/addons/ $releasePath addonsPath=$releasePath/addons pluginPath=$addonsPath/godot-git-plugin mkdir $pluginPath/linux mkdir $pluginPath/osx cp -r linux/addons/godot-git-plugin/linux/ $pluginPath/ cp -r mac/addons/godot-git-plugin/osx/ $pluginPath/ sed -i "s/version=\"[^\"]*\"/version=\"v${version}\"/g" $pluginPath/plugin.cfg cp LICENSE $pluginPath/LICENSE cp THIRDPARTY.md $pluginPath/THIRDPARTY.md zip -r $releasePath.zip $addonsPath rm -rf $releasePath rm -rf windows rm -rf linux rm -rf mac rm windows.zip rm linux.zip rm mac.zip
# does quitting work? echo -en "q\n" | ./mer_fsm # does encoding work? echo -en "1\n2\n3\n4\n5\n6\n7\n" | ./mer_fsm # does reset encoding work? echo -en "1\n2\n3\n4\ns\n.\n5\n6\n7\n5\n6\n7\n8\n" | ./mer_fsm
# ----------------------------------------------------------------------------- # This file is part of the xPack distribution. # (https://xpack.github.io) # Copyright (c) 2019 Liviu Ionescu. # # Permission to use, copy, modify, and/or distribute this software # for any purpose is hereby granted, under the terms of the MIT license. # ----------------------------------------------------------------------------- # Helper script used in the second edition of the xPack build # scripts. As the name implies, it should contain only functions and # should be included with 'source' by the container build scripts. # ----------------------------------------------------------------------------- function download_openocd() { if [ ! -d "${WORK_FOLDER_PATH}/${OPENOCD_SRC_FOLDER_NAME}" ] then ( xbb_activate cd "${WORK_FOLDER_PATH}" git_clone "${OPENOCD_GIT_URL}" "${OPENOCD_GIT_BRANCH}" \ "${OPENOCD_GIT_COMMIT}" "${OPENOCD_SRC_FOLDER_NAME}" cd "${WORK_FOLDER_PATH}/${OPENOCD_SRC_FOLDER_NAME}" git submodule update --init --recursive --remote ) fi } # ----------------------------------------------------------------------------- function do_openocd() { download_openocd ( xbb_activate xbb_activate_installed_dev cd "${WORK_FOLDER_PATH}/${OPENOCD_SRC_FOLDER_NAME}" if [ ! -d "autom4te.cache" ] then ./bootstrap fi mkdir -p "${APP_BUILD_FOLDER_PATH}" cd "${APP_BUILD_FOLDER_PATH}" export JAYLINK_CFLAGS='${XBB_CFLAGS} -fvisibility=hidden' if [ "${TARGET_PLATFORM}" == "win32" ] then # --enable-minidriver-dummy -> configure error # --enable-zy1000 -> netinet/tcp.h: No such file or directory # --enable-openjtag_ftdi -> --enable-openjtag # --enable-presto_libftdi -> --enable-presto # --enable-usb_blaster_libftdi -> --enable-usb_blaster export OUTPUT_DIR="${BUILD_FOLDER_PATH}" export CFLAGS="${XBB_CXXFLAGS} -Wno-pointer-to-int-cast" export CXXFLAGS="${XBB_CXXFLAGS}" export LDFLAGS="${XBB_LDFLAGS_APP}" AMTJTAGACCEL="--enable-amtjtagaccel" # --enable-buspirate -> not supported on mingw BUSPIRATE="--disable-buspirate" GW18012="--enable-gw16012" PARPORT="--enable-parport" PARPORT_GIVEIO="--enable-parport-giveio" # --enable-sysfsgpio -> available only on Linux SYSFSGPIO="--disable-sysfsgpio" elif [ "${TARGET_PLATFORM}" == "linux" ] then # --enable-minidriver-dummy -> configure error # --enable-openjtag_ftdi -> --enable-openjtag # --enable-presto_libftdi -> --enable-presto # --enable-usb_blaster_libftdi -> --enable-usb_blaster export CFLAGS="${XBB_CFLAGS} -Wno-format-truncation -Wno-format-overflow" export CXXFLAGS="${XBB_CXXFLAGS}" export LDFLAGS="${XBB_LDFLAGS_APP}" export LIBS="-lpthread -lrt -ludev" AMTJTAGACCEL="--enable-amtjtagaccel" BUSPIRATE="--enable-buspirate" GW18012="--enable-gw16012" PARPORT="--enable-parport" PARPORT_GIVEIO="--enable-parport-giveio" SYSFSGPIO="--enable-sysfsgpio" elif [ "${TARGET_PLATFORM}" == "darwin" ] then # --enable-minidriver-dummy -> configure error # --enable-openjtag_ftdi -> --enable-openjtag # --enable-presto_libftdi -> --enable-presto # --enable-usb_blaster_libftdi -> --enable-usb_blaster export CFLAGS="${XBB_CFLAGS}" export CXXFLAGS="${XBB_CXXFLAGS}" export LDFLAGS="${XBB_LDFLAGS_APP}" # export LIBS="-lobjc" # --enable-amtjtagaccel -> 'sys/io.h' file not found AMTJTAGACCEL="--disable-amtjtagaccel" BUSPIRATE="--enable-buspirate" # --enable-gw16012 -> 'sys/io.h' file not found GW18012="--disable-gw16012" PARPORT="--disable-parport" PARPORT_GIVEIO="--disable-parport-giveio" # --enable-sysfsgpio -> available only on Linux SYSFSGPIO="--disable-sysfsgpio" else echo "Unsupported target platorm ${TARGET_PLATFORM}." exit 1 fi if [ ! -f "config.status" ] then # May be required for repetitive builds, because this is an executable built # in place and using one for a different architecture may not be a good idea. rm -rfv "${WORK_FOLDER_PATH}/${OPENOCD_SRC_FOLDER_NAME}/jimtcl/autosetup/jimsh0" ( echo echo "Running openocd configure..." bash "${WORK_FOLDER_PATH}/${OPENOCD_SRC_FOLDER_NAME}/configure" --help bash ${DEBUG} "${WORK_FOLDER_PATH}/${OPENOCD_SRC_FOLDER_NAME}/configure" \ --prefix="${APP_PREFIX}" \ \ --build=${BUILD} \ --host=${HOST} \ --target=${TARGET} \ \ --datarootdir="${INSTALL_FOLDER_PATH}" \ --localedir="${APP_PREFIX}/share/locale" \ --mandir="${APP_PREFIX_DOC}/man" \ --pdfdir="${APP_PREFIX_DOC}/pdf" \ --infodir="${APP_PREFIX_DOC}/info" \ --docdir="${APP_PREFIX_DOC}" \ \ --disable-wextra \ --disable-werror \ --enable-dependency-tracking \ \ --enable-branding="${BRANDING}" \ \ --enable-aice \ ${AMTJTAGACCEL} \ --enable-armjtagew \ --enable-at91rm9200 \ --enable-bcm2835gpio \ ${BUSPIRATE} \ --enable-cmsis-dap \ --enable-dummy \ --enable-ep93xx \ --enable-ftdi \ ${GW18012} \ --disable-ioutil \ --enable-jlink \ --enable-jtag_vpi \ --disable-minidriver-dummy \ --disable-oocd_trace \ --enable-opendous \ --enable-openjtag \ --enable-osbdm \ ${PARPORT} \ --disable-parport-ppdev \ ${PARPORT_GIVEIO} \ --enable-presto \ --enable-remote-bitbang \ --enable-rlink \ --enable-stlink \ ${SYSFSGPIO} \ --enable-ti-icdi \ --enable-ulink \ --enable-usb-blaster \ --enable-usb_blaster_2 \ --enable-usbprog \ --enable-vsllink \ --disable-zy1000-master \ --disable-zy1000 \ cp "config.log" "${LOGS_FOLDER_PATH}/config-openocd-log.txt" ) 2>&1 | tee "${LOGS_FOLDER_PATH}/configure-openocd-output.txt" fi ( echo echo "Running openocd make..." # Parallel builds fail. make bindir="bin" pkgdatadir="" if [ "${WITH_STRIP}" == "y" ] then make install-strip else make install fi if [ "${TARGET_PLATFORM}" == "linux" ] then echo echo "Shared libraries:" echo "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" readelf -d "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" | grep 'Shared library:' # For just in case, normally must be done by the make file. strip "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" || true echo echo "Preparing libraries..." patch_linux_elf_origin "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" echo copy_dependencies_recursive "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" "${APP_PREFIX}/bin" elif [ "${TARGET_PLATFORM}" == "darwin" ] then echo echo "Initial dynamic libraries:" otool -L "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" # For just in case, normally must be done by the make file. strip "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" || true echo echo "Preparing libraries..." copy_dependencies_recursive "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" "${APP_PREFIX}/bin" echo echo "Updated dynamic libraries:" otool -L "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" elif [ "${TARGET_PLATFORM}" == "win32" ] then echo echo "Dynamic libraries:" echo "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}.exe" ${CROSS_COMPILE_PREFIX}-objdump -x "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}.exe" | grep -i 'DLL Name' # For just in case, normally must be done by the make file. ${CROSS_COMPILE_PREFIX}-strip "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}.exe" || true rm -f "${APP_PREFIX}/bin/openocdw.exe" echo echo "Preparing libraries..." copy_dependencies_recursive "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}.exe" "${APP_PREFIX}/bin" fi if [ "${IS_DEVELOP}" != "y" ] then strip_binaries check_application "${APP_EXECUTABLE_NAME}" fi ( xbb_activate_tex if [ "${WITH_PDF}" == "y" ] then make bindir="bin" pkgdatadir="" pdf make install-pdf fi if [ "${WITH_HTML}" == "y" ] then make bindir="bin" pkgdatadir="" html make install-html fi ) ) 2>&1 | tee "${LOGS_FOLDER_PATH}/make-openocd-output.txt" ) } function run_openocd() { echo if [ "${TARGET_PLATFORM}" == "linux" ] then "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" --version elif [ "${TARGET_PLATFORM}" == "darwin" ] then "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" --version elif [ "${TARGET_PLATFORM}" == "win32" ] then local wsl_path=$(which wsl.exe) if [ ! -z "${wsl_path}" ] then "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}.exe" --version else ( xbb_activate xbb_activate_installed_bin local wine_path=$(which wine) if [ ! -z "${wine_path}" ] then wine "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}.exe" --version else echo "Install wine if you want to run the .exe binaries on Linux." fi ) fi fi } function strip_binaries() { if [ "${WITH_STRIP}" == "y" ] then ( xbb_activate echo echo "Stripping binaries..." if [ "${TARGET_PLATFORM}" == "win32" ] then ${CROSS_COMPILE_PREFIX}-strip "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}.exe" || true ${CROSS_COMPILE_PREFIX}-strip "${APP_PREFIX}/bin/"*.dll || true else strip "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" || true if [ "${TARGET_PLATFORM}" == "linux" ] then : # strip "${APP_PREFIX}/bin/${APP_EXECUTABLE_NAME}" || true fi fi ) fi } # ----------------------------------------------------------------------------- function copy_distro_files() { ( xbb_activate rm -rf "${APP_PREFIX}/${DISTRO_INFO_NAME}" mkdir -p "${APP_PREFIX}/${DISTRO_INFO_NAME}" echo echo "Copying license files..." copy_license \ "${SOURCES_FOLDER_PATH}/${LIBUSB1_SRC_FOLDER_NAME}" \ "${LIBUSB1_FOLDER_NAME}" if [ "${TARGET_PLATFORM}" != "win32" ] then copy_license \ "${SOURCES_FOLDER_PATH}/${LIBUSB0_SRC_FOLDER_NAME}" \ "${LIBUSB0_FOLDER_NAME}" else copy_license \ "${SOURCES_FOLDER_PATH}/${LIBUSB_W32_SRC_FOLDER_NAME}" \ "${LIBUSB_W32_FOLDER_NAME}" fi copy_license \ "${SOURCES_FOLDER_PATH}/${LIBFTDI_SRC_FOLDER_NAME}" \ "${LIBFTDI_FOLDER_NAME}" copy_license \ "${SOURCES_FOLDER_PATH}/${LIBICONV_SRC_FOLDER_NAME}" \ "${LIBICONV_FOLDER_NAME}" copy_license \ "${WORK_FOLDER_PATH}/${OPENOCD_SRC_FOLDER_NAME}" \ "${OPENOCD_FOLDER_NAME}" copy_build_files echo echo "Copying xPack files..." cd "${WORK_FOLDER_PATH}/build.git" install -v -c -m 644 "scripts/${README_OUT_FILE_NAME}" \ "${APP_PREFIX}/README.md" ) }
<filename>spring-redis/src/main/java/org/xman/nosql/Consumer.java<gh_stars>0 package org.xman.nosql; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import java.util.concurrent.TimeUnit; public class Consumer extends Thread { // inject the actual template @Autowired private RedisTemplate<String, String> template; public void setTemplate(RedisTemplate<String, String> template) { this.template = template; } private boolean running = true; @Override public void run() { while (running) { try { System.out.println(this.getName()); String message = template.boundListOps("topic:moments:pub:pending").rightPop(0, TimeUnit.SECONDS); System.out.println(message); } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(10000); } catch (InterruptedException ignored) { } } } } public void consume() { this.start(); } }
const mealItems = { 'Pizza': 5.00, 'Soda': 2.50, 'Salad': 4.50 }; const totalCost = Object.values(mealItems).reduce((total, num) => { return total + num; }, 0); console.log('Total cost of the meal: $' + totalCost); # Output: Total cost of the meal: $12.00
#!/usr/bin/env bash set -euo pipefail DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" CHANNEL=${CHANNEL:-pytorch-nightly} PACKAGES=${PACKAGES:-pytorch} for pkg in ${PACKAGES}; do echo "+ Attempting to prune: ${CHANNEL}/${pkg}" CHANNEL="${CHANNEL}" PKG="${pkg}" "${DIR}/prune.sh" echo done
/** * ychen * Copyright (c). */ package cn.edu.fudan.iipl.exception; import org.springframework.stereotype.Component; import cn.edu.fudan.iipl.enums.BlogExceptionEnum; /** * 全局Exception * @author racing * @version $Id: BlogException.java, v 0.1 Aug 8, 2015 4:18:46 PM racing Exp $ */ @Component public class BlogException extends RuntimeException { /** */ private static final long serialVersionUID = 1848107438259593418L; private BlogExceptionEnum blogExceptionEnum; public BlogException() { super(BlogExceptionEnum.SYSTEM_ERROR.getDescription()); this.blogExceptionEnum = BlogExceptionEnum.SYSTEM_ERROR; } public BlogException(BlogExceptionEnum blogExceptionEnum) { super(blogExceptionEnum.getDescription()); this.blogExceptionEnum = blogExceptionEnum; } /** * 获取错误码 * @return messageCode */ public String getMessageCode() { return blogExceptionEnum.getMessageCode(); } /** * 获取错误描述 * @return description */ public String getDescription() { return blogExceptionEnum.getDescription(); } }
<gh_stars>0 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. module OCI module TenantManagerControlPlane::Models RECIPIENT_INVITATION_STATUS_ENUM = [ RECIPIENT_INVITATION_STATUS_PENDING = 'PENDING'.freeze, RECIPIENT_INVITATION_STATUS_CANCELED = 'CANCELED'.freeze, RECIPIENT_INVITATION_STATUS_ACCEPTED = 'ACCEPTED'.freeze, RECIPIENT_INVITATION_STATUS_IGNORED = 'IGNORED'.freeze, RECIPIENT_INVITATION_STATUS_EXPIRED = 'EXPIRED'.freeze, RECIPIENT_INVITATION_STATUS_FAILED = 'FAILED'.freeze ].freeze end end
// Copyright 2019 Drone.IO Inc. All rights reserved. // Use of this source code is governed by the Drone Non-Commercial License // that can be found in the LICENSE file. package manager import ( "io/ioutil" "github.com/sirupsen/logrus" ) func init() { logrus.SetOutput(ioutil.Discard) }
<gh_stars>1-10 const RuleSet = require('./rule-set') class Symbol { constructor(grammar, key, rawRules) { // Symbols can be made with a single value, and array, or array of objects of (conditions/values) this.key = key this.grammar = grammar this.rawRules = rawRules this.baseRules = new RuleSet(this.grammar, rawRules) this.clearState() } clearState() { // Clear the stack and clear all ruleset usages this.stack = [this.baseRules] this.uses = [] this.baseRules.clearState() } pushRules(rawRules) { const rules = new RuleSet(this.grammar, rawRules) this.stack.push(rules) } popRules() { this.stack.pop() } selectRule(node, errors) { this.uses.push({ node }) if (this.stack.length === 0) { errors.push('The rule stack for \'' + this.key + '\' is empty, too many pops?') return '((' + this.key + '))' } return this.stack[this.stack.length - 1].selectRule() } getActiveRules() { if (this.stack.length === 0) { return null } return this.stack[this.stack.length - 1].selectRule() } rulesToJSON() { return JSON.stringify(this.rawRules) } } module.exports = Symbol
#!/bin/bash echo Installing Dependencies... sudo apt install libgconf-2-4 libappindicator1 libc++1 -y wget -O discord.deb "https://discordapp.com/api/download?platform=linux&format=deb" sudo dpkg -i discord.deb rm discord.deb
#!/bin/bash java -jar -DinputMethod="mouse_touch" -DttsUrl="http://localhost/action/" -Djdk.gtk.version=2 -Dexec.mainClass=org.scify.memori.ApplicationLauncher memori-1.0-SNAPSHOT-jar-with-dependencies.jar
package org.quifft.output; import org.quifft.audioread.AudioReader; import org.quifft.fft.FFTComputationWrapper; import org.quifft.params.FFTParameters; import org.quifft.params.WindowFunction; import org.quifft.sampling.SampleWindowExtractor; import java.util.Iterator; /** * FFTStream computes an FFT on an audio file incrementally as opposed to all at once * <p>It exposes an Iterator interface for computing {@link FFTFrame}s one at a time. * This can be a useful alternative to {@link FFTResult} if your audio file is large or you are space-constrained.</p> */ public class FFTStream extends FFTOutputObject implements Iterator<FFTFrame> { // AudioReader from which samples can be extracted private AudioReader audioReader; // Counter for how many samples have been computed so far (how many times next() has been called) private int samplesTakenCount; /** * Checks whether another FFTFrame exists * @return true if another FFTFrame exists */ public boolean hasNext() { return audioReader.hasNext(); } /** * Gets next computed FFTFrame * @return next computed FFTFrame */ public FFTFrame next() { int[] nextWindow = audioReader.next(); boolean isStereo = audioReader.getAudioFormat().getChannels() == 2; int windowSize = fftParameters.windowSize; WindowFunction windowFunction = fftParameters.windowFunction; double overlap = fftParameters.windowOverlap; int zeroPadLength = fftParameters.zeroPadLength(); double startTimeMs = samplesTakenCount * windowDurationMs * (1 - fftParameters.windowOverlap); float sampleRate = audioReader.getAudioFormat().getSampleRate(); SampleWindowExtractor windowExtractor = new SampleWindowExtractor(nextWindow, isStereo, windowSize, windowFunction, overlap, zeroPadLength); nextWindow = windowExtractor.convertSamplesToWindow(nextWindow); samplesTakenCount++; FFTFrame nextFrame = FFTComputationWrapper.doFFT(nextWindow, startTimeMs, windowDurationMs, fileDurationMs, sampleRate, fftParameters); if(fftParameters.useDecibelScale) { FFTComputationWrapper.scaleLogarithmically(nextFrame); } return nextFrame; } @Override public void setMetadata(AudioReader reader, FFTParameters params) { super.setMetadata(reader, params); // capture AudioReader object after setting metadata audioReader = reader; audioReader.setFFTParameters(params); } }
#!/bin/bash source /opt/azure/containers/provision_source.sh clusterInfo() { FIRST_MASTER_READY=$(kubectl get nodes | grep k8s-master | grep Ready | sort | head -n 1 | cut -d ' ' -f 1) if [[ "${FIRST_MASTER_READY}" == "${HOSTNAME}" ]]; then retrycmd_no_stats 3 5 120 kubectl cluster-info dump --namespace=kube-system --output-directory=${OUTDIR}/cluster-info fi } collectCloudProviderJson() { local DIR=${OUTDIR}/etc/kubernetes mkdir -p ${DIR} if [ -f /etc/kubernetes/azure.json ]; then jq . /etc/kubernetes/azure.json | grep -v aadClient > ${DIR}/azure.json fi if [ -f /etc/kubernetes/azurestackcloud.json ]; then jq . /etc/kubernetes/azurestackcloud.json > ${DIR}/azurestackcloud.json fi if [ -f /etc/kubernetes/network_interfaces.json ]; then cp /etc/kubernetes/network_interfaces.json ${DIR} fi if [ -f /etc/kubernetes/interfaces.json ]; then cp /etc/kubernetes/interfaces.json ${DIR} fi if [ -f /opt/azure/vhd-install.complete ]; then mkdir -p ${OUTDIR}/opt/azure cp /opt/azure/vhd-install.complete ${OUTDIR}/opt/azure fi } collectDirLogs() { local DIR=${OUTDIR}${1} if [ -d ${1} ]; then mkdir -p ${DIR} cp ${1}/*.log ${DIR} fi } collectDir() { local DIR=${OUTDIR}${1} if [ -d ${1} ]; then mkdir -p ${DIR} cp ${1}/* ${DIR} fi } collectDaemonLogs() { local DIR=${OUTDIR}/daemons mkdir -p ${DIR} if systemctl list-units --no-pager | grep -q ${1}; then timeout 15 systemctl status ${1} &> ${DIR}/${1}.status timeout 15 journalctl --utc -o short-iso --no-pager -r -u ${1} &> /tmp/${1}.log tac /tmp/${1}.log > ${DIR}/${1}.log fi } compressLogsDirectory() { sync ZIP="/tmp/logs.zip" rm -f ${ZIP} (cd ${OUTDIR}/.. && zip -q -r ${ZIP} ${HOSTNAME}) } # AzS headers stackfy() { # Azure Stack can store/ingest these files in a Edge Kusto DB. # Data team asked for metadata to simplify queries. It is added as a header to each file. RESOURCE_GROUP=$(sudo jq -r '.resourceGroup' /etc/kubernetes/azure.json) SUB_ID=$(sudo jq -r '.subscriptionId' /etc/kubernetes/azure.json) TENANT_ID=$(sudo jq -r '.tenantId' /etc/kubernetes/azure.json) if [ "${TENANT_ID}" == "adfs" ]; then TENANT_ID=$(sudo jq -r '.serviceManagementEndpoint' /etc/kubernetes/azurestackcloud.json | cut -d / -f4) fi stackfyKubeletLog stackfyMobyLog stackfyEtcdLog stackfyFileNames /var/log stackfyFileNames /var/log/azure stackfyClusterInfo stackfyNetwork } stackfyKubeletLog() { KUBELET_VERSION=$(kubelet --version | grep -oh -E 'v.*$') KUBELET_VERBOSITY=$(grep -e '--v=[0-9]' -oh /etc/systemd/system/kubelet.service | grep -e '[0-9]' -oh /etc/systemd/system/kubelet.service | head -n 1) KUBELET_LOG_FILE=${OUTDIR}/daemons/k8s-kubelet.log { echo "== BEGIN HEADER =="; echo "Type: Daemon"; echo "TenantId: ${TENANT_ID}"; echo "Name: kubelet"; echo "Version: ${KUBELET_VERSION}"; echo "Verbosity: ${KUBELET_VERBOSITY}"; echo "Image: "; echo "Hostname: ${HOSTNAME}"; echo "SubscriptionID: ${SUB_ID}"; echo "ResourceGroup: ${RESOURCE_GROUP}"; echo "== END HEADER ==" } >> ${KUBELET_LOG_FILE} cat ${OUTDIR}/daemons/kubelet.service.log >> ${KUBELET_LOG_FILE} rm ${OUTDIR}/daemons/kubelet.service.log } stackfyMobyLog() { DOCKER_VERSION=$(docker version | grep -A 20 "Server:" | grep "Version:" | head -n 1 | cut -d ":" -f 2 | xargs) DOCKER_LOG_FILE=${OUTDIR}/daemons/k8s-docker.log { echo "== BEGIN HEADER ==" echo "Type: Daemon" echo "TenantId: ${TENANT_ID}" echo "Name: docker" echo "Version: ${DOCKER_VERSION}" echo "Hostname: ${HOSTNAME}" echo "SubscriptionID: ${SUB_ID}" echo "ResourceGroup: ${RESOURCE_GROUP}" echo "== END HEADER ==" } >> ${DOCKER_LOG_FILE} cat ${OUTDIR}/daemons/docker.service.log >> ${DOCKER_LOG_FILE} rm ${OUTDIR}/daemons/docker.service.log } stackfyEtcdLog() { if [ ! -f /usr/bin/etcd ]; then return fi ETCD_VERSION=$(/usr/bin/etcd --version | grep "etcd Version:" | cut -d ":" -f 2 | xargs) ETCD_LOG_FILE=${OUTDIR}/daemons/k8s-etcd.log { echo "== BEGIN HEADER ==" echo "Type: Daemon" echo "TenantId: ${TENANT_ID}" echo "Name: etcd" echo "Version: ${ETCD_VERSION}" echo "Hostname: ${HOSTNAME}" echo "SubscriptionID: ${SUB_ID}" echo "ResourceGroup: ${RESOURCE_GROUP}" echo "== END HEADER ==" } >> ${ETCD_LOG_FILE} cat ${OUTDIR}/daemons/etcd.service.log >> ${ETCD_LOG_FILE} rm ${OUTDIR}/daemons/etcd.service.log } stackfyClusterInfo() { if [ ! -f ${OUTDIR}/cluster-info/nodes.json ]; then return fi mkdir -p ${OUTDIR}/containers for SRC in "${OUTDIR}"/cluster-info/kube-system/kube-controller-manager-*/logs.txt; do KCM_VERBOSITY=$(grep -e "--v=[0-9]" -oh /etc/kubernetes/manifests/kube-controller-manager.yaml | grep -e "[0-9]" -oh | head -n 1) KCM_IMAGE=$(grep image: /etc/kubernetes/manifests/kube-controller-manager.yaml | xargs | cut -f 2 -d " ") KCM_DIR=$(dirname ${SRC}) KCM_NAME=$(basename ${KCM_DIR}) KCM_LOG_FILE=${OUTDIR}/containers/k8s-${KCM_NAME}.log { echo "== BEGIN HEADER ==" echo "Type: Container" echo "TenantId: ${TENANT_ID}" echo "Name: ${KCM_NAME}" echo "Hostname: ${HOSTNAME}" echo "ContainerID: " echo "Image: ${KCM_IMAGE}" echo "Verbosity: ${KCM_VERBOSITY}" echo "SubscriptionID: ${SUB_ID}" echo "ResourceGroup: ${RESOURCE_GROUP}" echo "== END HEADER ==" } >> ${KCM_LOG_FILE} cat ${SRC} >> ${KCM_LOG_FILE} done } stackfyNetwork() { local DIR=${OUTDIR}/network mkdir -p ${DIR} # basic name resolution test ping ${HOSTNAME} -c 3 &> ${DIR}/k8s-ping.txt } stackfyFileNames() { local DIR=${OUTDIR}/${1} for SRC in "${DIR}"/*.log; do NAME=$(basename ${SRC}) mv ${SRC} ${DIR}/k8s-${NAME} done } OUTDIR="$(mktemp -d)/${HOSTNAME}" collectCloudProviderJson collectDirLogs /var/log collectDirLogs /var/log/azure collectDirLogs /var/log/kubeaudit collectDir /etc/kubernetes/manifests collectDir /etc/kubernetes/addons collectDaemonLogs kubelet.service collectDaemonLogs etcd.service collectDaemonLogs docker.service clusterInfo if [ "${AZURE_ENV}" = "AzureStackCloud" ]; then stackfy fi compressLogsDirectory
export { default } from "./CertificationAlert";
from typing import List, Dict, Union def filter_patients(patients: List[Dict[str, Union[str, int]]], criteria: str, value: Union[str, int]) -> List[Dict[str, Union[str, int]]]: if not patients: # If the input list of patients is empty, return an empty list return [] filtered_patients = [] for patient in patients: if criteria == 'age' and patient['age'] == value: filtered_patients.append(patient) elif criteria == 'gender' and patient['gender'] == value: filtered_patients.append(patient) return filtered_patients
#!/bin/bash # Copyright 2015 The Kubernetes 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. # A library of common helper functions for Ubuntus & Debians. function detect-minion-image() { if [[ -z "${KUBE_MINION_IMAGE=-}" ]]; then detect-image KUBE_MINION_IMAGE=$AWS_IMAGE fi } function generate-minion-user-data { # We pipe this to the ami as a startup script in the user-data field. Requires a compatible ami echo "#! /bin/bash" echo "SALT_MASTER='${MASTER_INTERNAL_IP}'" echo "DOCKER_OPTS='${EXTRA_DOCKER_OPTS:-}'" echo "readonly DOCKER_STORAGE='${DOCKER_STORAGE:-}'" grep -v "^#" "${KUBE_ROOT}/cluster/aws/templates/common.sh" grep -v "^#" "${KUBE_ROOT}/cluster/aws/templates/format-disks.sh" grep -v "^#" "${KUBE_ROOT}/cluster/aws/templates/salt-minion.sh" } function check-minion() { local minion_ip=$1 local output=$(ssh -oStrictHostKeyChecking=no -i "${AWS_SSH_KEY}" ${SSH_USER}@$minion_ip sudo docker ps -a 2>/dev/null) if [[ -z "${output}" ]]; then ssh -oStrictHostKeyChecking=no -i "${AWS_SSH_KEY}" ${SSH_USER}@$minion_ip sudo service docker start > $LOG 2>&1 echo "not working yet" else echo "working" fi }
// Clock interface interface Clock { long time(); long tick(); } // Custom clock implementation class CustomClock implements Clock { @Override public long time() { return System.currentTimeMillis(); } @Override public long tick() { return SystemClock.elapsedRealtime(); } // Method to calculate time difference between two instances of the clock public static long timeDifference(Clock clock1, Clock clock2) { return Math.abs(clock1.time() - clock2.time()); } } // Example usage public class Main { public static void main(String[] args) { CustomClock clock1 = new CustomClock(); CustomClock clock2 = new CustomClock(); long timeDifference = CustomClock.timeDifference(clock1, clock2); System.out.println("Time difference: " + timeDifference + " milliseconds"); } }
<filename>platforms/ios/www/plugins/com.wikitude.phonegap.WikitudePlugin/www/WikitudePlugin.js cordova.define("com.wikitude.phonegap.WikitudePlugin.WikitudePlugin", function(require, exports, module) { /** * Release date: January 25, 2017 */ var WikitudePlugin = function() { /** * This is the SDK Key, provided to you after you purchased the Wikitude SDK from http =//www.wikitude.com/store/. * You can obtain a free trial key at http =//www.wikitude.com/developer/licenses . */ this._sdkKey = "ENTER-YOUR-KEY-HERE"; /** * The Wikitude SDK can run in different modes. * * Geo means, that objects are placed at latitude/longitude positions. * * 2DTracking means that only image recognition is used in the ARchitect World. * When your ARchitect World uses both, geo and ir, than set this value to "IrAndGeo". Otherwise, if the ARchitectWorld only needs image recognition, placing "IR" will require less features from the device and therefore, support a wider range of devices. Keep in mind that image recognition requires a dual core cpu to work satisfyingly. */ this.FeatureGeo = "geo"; this.FeatureImageTracking = "image_tracking"; this.Feature2DTracking = "2d_tracking"; /** * Start-up configuration: camera position (front or back). */ this.CameraPositionUndefined = 0; this.CameraPositionFront = 1; this.CameraPositionBack = 2; /** * Start-up configuration: camera focus range restriction (for iOS only). */ this.CameraFocusRangeNone = 0; this.CameraFocusRangeNear = 1; this.CameraFocusRangeFar = 2; }; /* * ============================================================================================================================= * * PUBLIC API * * ============================================================================================================================= */ /* Managing ARchitect world loading */ /** * Use this function to check if the current device is capable of running ARchitect Worlds. * * @param {function} successCallback A callback which is called if the device is capable of running ARchitect Worlds. * @param {function} errorCallback A callback which is called if the device is not capable of running ARchitect Worlds. */ WikitudePlugin.prototype.isDeviceSupported = function(successCallback, errorCallback, requiredFeatures) { // Check if the current device is capable of running Architect Worlds cordova.exec(successCallback, errorCallback, "WikitudePlugin", "isDeviceSupported", [requiredFeatures]); }; /** * Use this function to request access to restricted APIs like the camera, gps or photo library. * * @param {function} successCallback A callback which is called if all required permissions are granted. * @param {function} errorCallback A callback which is called if one or more permissions are not granted. * @param {function} requiredFeatures An array of strings describing which features of the Wikitude SDK are used so that the plugin can request access to those restricted APIs. */ WikitudePlugin.prototype.requestAccess = function(successCallback, errorCallback, requiredFeatures) { cordova.exec(successCallback, errorCallback, "WikitudePlugin", "requestAccess", [requiredFeatures]); }; /** * Use this function to load an ARchitect World. * * @param {function(loadedURL)} successCallback function which is called after a successful launch of the AR world. * @param {function(error)} errorCallback function which is called after a failed launch of the AR world. * @param {String} architectWorldPath The path to a local ARchitect world or to a ARchitect world on a server or your * @param {String} worldPath path to an ARchitect world, either on the device or on e.g. your Dropbox. * @param {Array} requiredFeatures augmented reality features: a flags mask for enabling/disabling * geographic location-based (WikitudePlugin.FeatureGeo) or image recognition-based (WikitudePlugin.Feature2DTracking) tracking. * @param {json object} (optional) startupConfiguration represents the start-up configuration which may look like the following: * { * "cameraPosition": app.WikitudePlugin.CameraPositionBack, * "*OptionalPlatform*": { * "*optionalPlatformKey*": "*optionalPlatformValue*" * } * } */ WikitudePlugin.prototype.loadARchitectWorld = function(successCallback, errorCallback, architectWorldPath, requiredFeatures, startupConfiguration) { cordova.exec(successCallback, errorCallback, "WikitudePlugin", "open", [{ "SDKKey": this._sdkKey, "ARchitectWorldURL": architectWorldPath, "RequiredFeatures": requiredFeatures, "StartupConfiguration" : startupConfiguration }]); // We add an event listener on the resume and pause event of the application life-cycle document.addEventListener("resume", this.onResume, false); document.addEventListener("pause", this.onPause, false); document.addEventListener("backbutton", this.onBackButton, false); }; /* Managing the Wikitude SDK Lifecycle */ /** * Use this function to stop the Wikitude SDK and to remove it from the screen. */ WikitudePlugin.prototype.close = function() { document.removeEventListener("pause", this.onPause, false); document.removeEventListener("resume", this.onResume, false); document.removeEventListener("backbutton", this.onBackButton, false); cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "close", [""]); }; /** * Use this function to only hide the Wikitude SDK. All location and rendering updates are still active. */ WikitudePlugin.prototype.hide = function() { cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "hide", [""]); }; /** * Use this function to show the Wikitude SDK again if it was hidden before. */ WikitudePlugin.prototype.show = function() { cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "show", [""]); }; /* Interacting with the Wikitude SDK */ /** * Use this function to call JavaScript which will be executed in the context of the currently loaded ARchitect World. * * @param js The JavaScript that should be evaluated in the ARchitect View. */ WikitudePlugin.prototype.callJavaScript = function(js) { cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "callJavascript", [js]); }; /** * Use this function to set a callback which will be invoked when the ARchitect World opens an architectsdk =// url. * document.location = "architectsdk =//opendetailpage?id=9"; * * @param onUrlInvokeCallback A function which will be called when the ARchitect World invokes a call to "document.location = architectsdk =//" */ WikitudePlugin.prototype.setOnUrlInvokeCallback = function(onUrlInvokeCallback) { cordova.exec(onUrlInvokeCallback, this.onWikitudeError, "WikitudePlugin", "onUrlInvoke", [""]); }; /** * Use this function to inject a location into the Wikitude SDK. * * @param latitude The latitude which should be simulated * @param longitude The longitude which should be simulated * @param altitude The altitude which should be simulated * @param accuracy The simulated location accuracy */ WikitudePlugin.prototype.setLocation = function(latitude, longitude, altitude, accuracy) { cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "setLocation", [latitude, longitude, altitude, accuracy]); }; /** * Use this function to generate a screenshot from the current Wikitude SDK view. * * @param {function(ur)} successCallback function which is called after the screen capturing succeeded. * @param {function(err)} errorCallback function which is called after capturing the screen has failed. * @param includeWebView Indicates if the ARchitect web view should be included in the generated screenshot or not. * @param imagePathInBundleorNullForPhotoLibrary If a file path or file name is given, the generated screenshot will be saved in the application bundle. Passing null will save the photo in the device photo library. */ WikitudePlugin.prototype.captureScreen = function(successCallback, errorCallback, includeWebView, imagePathInBundleOrNullForPhotoLibrary) { cordova.exec(successCallback, errorCallback, "WikitudePlugin", "captureScreen", [includeWebView, imagePathInBundleOrNullForPhotoLibrary]); }; /** * Use this function to set a callback that is called every time the Wikitude SDK encounters an internal error or warning. * Internal errors can occur at any time and might not be related to any WikitudePlugin function invocation. * An error code and message are passed in form of a JSON object. * * @param {function(jsonObject)} errorHandler function which is called every time the SDK encounters an internal error. * * NOTE: The errorHandler is currently only called by the Wikitude iOS SDK! */ WikitudePlugin.prototype.setErrorHandler = function(errorHandler) { cordova.exec(this.onWikitudeOK, errorHandler, "WikitudePlugin", "setErrorHandler", []); } /** * Use this function to set a callback that is called every time the iOS SDK need to calibrate device sensors. * * @param {function()} startCalibrationHandler function which is called every time the iOS SDK would like to calibrate device sensors. * * Note: The startCalibrationHandler is currently only called by the Wikitude iOS Cordova Plugin! */ WikitudePlugin.prototype.setDeviceSensorsNeedCalibrationHandler = function(startCalibrationHandler) { cordova.exec(startCalibrationHandler, this.onWikitudeError(), "WikitudePlugin", "setDeviceSensorsNeedCalibrationHandler", []); } /** * Use this function to set a callback that is called every time the iOS SDK finished device sensor calibration. * * @param {function()} finishedCalibrationHandler function which is called every time the iOS SDK finished calibrating device sensors. * * Note: The finishedCalibrationHandler is currently only called by the Wikitude iOS Cordova Plugin! */ WikitudePlugin.prototype.setDeviceSensorsFinishedCalibrationHandler = function(finishedCalibrationHandler) { cordova.exec(finishedCalibrationHandler, this.onWikitudeError(), "WikitudePlugin", "setDeviceSensorsFinishedCalibrationHandler", []); } /** * Use this function to set a callback that is called every time the back button is pressed while the Wikitude Cordova Plugin is presented. * * @param {function()} onBackButtonCallback function which is called every time the Android back button is pressed. * * Note: The function is only implemented for Android! */ WikitudePlugin.prototype.setBackButtonCallback = function(onBackButtonCallback) { if ( cordova.platformId == "android" ) { cordova.exec(onBackButtonCallback, this.onWikitudeError, "WikitudePlugin", "setBackButtonCallback", []); } else { alert('setBackButtonCallback is only available on Android and not on' + cordova.platformId); } } /** * Use this function to get information about the sdk build. * * @param {function} successCallback A callback which is called when the build information could be laoded. */ WikitudePlugin.prototype.getSDKBuildInformation = function(successCallback) { cordova.exec(successCallback, this.onWikitudeError, "WikitudePlugin", "getSDKBuildInformation", [""]) } /** * Use this function to get the version of the sdk. * * @param {function} successCallback A callback which is called when the sdk version could be loaded. */ WikitudePlugin.prototype.getSDKVersion = function(successCallback) { cordova.exec(successCallback, this.onWikitudeError, "WikitudePlugin", "getSDKVersion", [""]) } /** * Use this function to open the application specific system setting view. */ WikitudePlugin.prototype.openAppSettings = function() { cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "openAppSettings", []); } /* * ============================================================================================================================= * * Callbacks of public functions * * ============================================================================================================================= */ /* Lifecycle updates */ /** * This function gets called every time the application did become active. */ WikitudePlugin.prototype.onResume = function() { // Call the Wikitude SDK that it should resume. cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "onResume", [""]); }; /* Lifecycle updates */ /** * This function gets called every time the application did become active. */ WikitudePlugin.prototype.onBackButton = function() { // Call the Wikitude SDK that it should resume. //cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "close", [""]); WikitudePlugin.prototype.close(); }; /** * This function gets called every time the application is about to become inactive. */ WikitudePlugin.prototype.onPause = function() { // Call the Wikitude SDK that the application did become inactive cordova.exec(this.onWikitudeOK, this.onWikitudeError, "WikitudePlugin", "onPause", [""]); }; /** * A generic success callback used inside this wrapper. */ WikitudePlugin.prototype.onWikitudeOK = function() {}; /** * A generic error callback used inside this wrapper. */ WikitudePlugin.prototype.onWikitudeError = function() {}; /* Export a new WikitudePlugin instance */ var wikitudePlugin = new WikitudePlugin(); module.exports = wikitudePlugin; });
import { Component } from '@angular/core'; import { ComponentStructure } from 'ngx-guildy'; import { MyTextComponent } from './my-addable-component/my-text.component'; import { MyButtonComponent } from './my-button/my-button.component'; import { MyCardComponent } from './my-card/my-card.component'; import { MyFlexContainerComponent } from './my-flex-container/my-flex-container.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { title = 'ngx-guildy-demo'; inStructure: ComponentStructure | undefined; outStructure: ComponentStructure | undefined; components = [MyTextComponent, MyButtonComponent, MyCardComponent, MyFlexContainerComponent]; changeStructure($event: any) { console.log('change'); this.inStructure = JSON.parse($event); } }
package com.onarandombox.multiverseinventories.share; import java.util.HashMap; import java.util.Map; /** * Indicates how a Sharable should be stored in the profile file. Serves as a lookup for finding a sharable based on * it's file tag. */ public final class ProfileEntry { private static final Map<String, Sharable> STATS_MAP = new HashMap<String, Sharable>(); private static final Map<String, Sharable> OTHERS_MAP = new HashMap<String, Sharable>(); private boolean isStat; private String fileTag; public ProfileEntry(boolean isStat, String fileTag) { this.isStat = isStat; this.fileTag = fileTag; } /** * @return True if this indicates a {@link Sharable} whose data will be stored in the stats string of the player * file. */ public boolean isStat() { return this.isStat; } /** * @return The String that represents where this file is stored in the player profile. */ public String getFileTag() { return this.fileTag; } /** * Registers a {@link Sharable} with it's respective ProfileEntry. * * @param sharable The sharable to register. */ static void register(Sharable sharable) { ProfileEntry entry = sharable.getProfileEntry(); if (entry == null) { // This would mean the sharable is not intended for saving in profile files. return; } if (entry.isStat()) { STATS_MAP.put(entry.getFileTag(), sharable); } else { OTHERS_MAP.put(entry.getFileTag(), sharable); } } /** * Used to look up a {@link Sharable} by it's file tag. * * @param stat True means this sharable is in the stats section of the player file. * @param fileTag The string representing where the sharable is stored in the player file. * @return A sharable if one has been registered with it's ProfileEntry otherwise null. */ public static Sharable lookup(boolean stat, String fileTag) { if (stat) { return STATS_MAP.get(fileTag); } else { return OTHERS_MAP.get(fileTag); } } }
<filename>pybf/visualization.py """ Copyright (C) 2020 ETH Zurich. All rights reserved. Author: <NAME>, ETH Zurich <NAME>, ETH Zurich 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. """ import matplotlib # matplotlib.use('QT4Agg') from matplotlib import colors, cm, pyplot as plt from matplotlib.patches import Rectangle import plotly as py import plotly.graph_objects as go import plotly.io as pio pio.renderers.default = "browser" import numpy as np # Constants PLOTLY_SCALE_FACTOR = 2 # Log compression def log_compress(image, db_range, reference_max=None): db_range = abs(db_range) image_temp = image.copy() # If reference maximum value is specified # truncate the data if reference_max is not None: image_temp[image_temp > reference_max] = reference_max # Calc max value if (reference_max is not None) and (reference_max > image_temp.max()): max_value = reference_max else: max_value = image_temp.max() # Log scale transform image_log = 20 * np.log10(image_temp/max_value) # Truncate image_log[image_log < (-db_range)] = -db_range print("BF Final dB range ({:2.1f},{:2.1f})".format(image_log.min(), image_log.max())) return image_log # Plot one trace def plot_trace(rf_data, channel=None, framework='matplotlib', save_fig=False, show=True, path_to_save=None): # Check path for the image image if path_to_save is None: path_to_save = '' else: path_to_save = path_to_save + '/' # Select data if channel is not None: data = rf_data[:, channel] title = "Data from channel " + str(channel) else: data = rf_data title = " " # Choose framework if framework is 'matplotlib': fig, ax = plt.subplots(1, 1,figsize=(10,10)) ax.plot(data, marker="o") ax.grid(True) ax.set_xlabel("Samples") ax.set_ylabel("Signal") ax.set_title(title) if show is True: plt.show() if save_fig is True: fig.savefig(path_to_save + title + '.png', dpi=300, bbox_inches='tight') elif framework is 'plotly': # Create plot fig = go.Figure() fig.add_trace(go.Scatter(y=data, mode='lines+markers', name='lines')) # Edit the layout fig.update_layout(title=title, xaxis_title='Samples', yaxis_title='Signal') if show is True: fig.show() if save_fig is True: fig.write_image(path_to_save + title + '.png') return # Plot image def plot_image(img_data, scatters_coords_xz=None, elements_coords_xz=None, framework='matplotlib', title=None, image_x_range=None, image_z_range=None, db_range=None, reference_max=None, colorscale='Greys', save_fig=False, show=True, path_to_save=None, latex_args=None): # Check path for to save images if path_to_save is None: path_to_save = '' else: path_to_save = path_to_save + '/' # Set title if title is None: title='Image' # Make log compression if db_range is not None: data=log_compress(img_data, db_range, reference_max=reference_max) # Update title title = title + ' (dB scale)' else: data=img_data # Choose framework if framework is 'matplotlib': if latex_args is not None: from matplotlib import rc rc('font',**{'family':'serif'}) rc('text', usetex=True) plt.rcParams.update(latex_args) fig, ax = plt.subplots(1, 1, figsize=latex_args['figure.figsize']) else: fig, ax = plt.subplots(1, 1) # Plot scatters if scatters_coords_xz is not None: ax.scatter(scatters_coords_xz[0,:], scatters_coords_xz[1,:], color = 'red', s=5, label='scatters') # Plot transducer elements if elements_coords_xz is not None: ax.scatter(elements_coords_xz[0,:], elements_coords_xz[1,:], color = 'green', marker="v", s=80, label='elements') # Plot image if (image_x_range is not None) and (image_z_range is not None): ax.imshow(data, cmap=cm.gray, origin="lower", extent=image_x_range+image_z_range) else: ax.imshow(data, cmap=cm.gray, origin="lower") ax.set_xlabel("X, m") ax.set_ylabel("Z, m") #ax.set_title(title) ax.invert_yaxis() #ax.legend() if show is True: plt.show() if save_fig is True: if latex_args is None: fig.savefig(path_to_save + title + '.png', dpi=300, bbox_inches='tight') else: fig.savefig(path_to_save + title + '.pdf', bbox_inches='tight', dpi=600) elif framework is 'plotly': ax = None # Create plot if (image_x_range is not None) and (image_z_range is not None): # Calculate points coordinates x_coords = np.linspace(image_x_range[0], image_x_range[1], data.shape[1]) z_coords = np.linspace(image_z_range[0], image_z_range[1], data.shape[0]) fig = go.Figure(data=go.Heatmap( z=data, zmin=data.min(), zmax=0, x=np.unique(x_coords), y=np.unique(z_coords), hoverongaps = False, colorscale=colorscale, reversescale=True)) else: fig = go.Figure(data=go.Heatmap( z=data, zmin=data.min(), zmax=0, hoverongaps = False, colorscale=colorscale)) # Plot scatters if scatters_coords_xz is not None: fig.add_trace(go.Scatter(x=scatters_coords_xz[0,:], y=scatters_coords_xz[1,:], mode='markers', marker=dict( color='red', size=3), name="scatters" )) # Plot transducer elements if elements_coords_xz is not None: fig.add_trace(go.Scatter(x=elements_coords_xz[0,:], y=elements_coords_xz[1,:], mode='markers', marker=dict( color='green', size=3), name="elements" )) # Edit the layout fig.update_layout( scene=dict(aspectmode="data"), title=title, xaxis_title='X, m', yaxis_title='Z, m', yaxis=dict(scaleanchor="x", scaleratio=1, range=[image_z_range[0], image_z_range[1]]), xaxis=dict(range=[image_x_range[0], image_x_range[1]]), showlegend=True, legend=dict(x=1, y=1.1) ) fig.update_yaxes(autorange="reversed") if show is True: fig.show() if save_fig is True: fig.write_image(path_to_save + title + '.png', scale = PLOTLY_SCALE_FACTOR) return fig, ax class LivePlot: def __init__(self, data_shape, scatters_coords_xz=None, elements_coords_xz=None, title=None, image_x_range=None, image_z_range=None, db_range=40, colorscale='Greys', save_fig=False): self.data_shape = data_shape # Set title if title is None: self.title='Image' else: self.title=title # Make log compression self.db_range = db_range # Update title self.title = self.title + ' (dB scale)' self.scatters_coords_xz = scatters_coords_xz self.elements_coords_xz = elements_coords_xz self.image_x_range = image_x_range self.image_z_range = image_z_range self._fig, self._ax = plt.subplots(1, 1,figsize=(10,10)) self._plot_initial_figure() # Plot scatters coordinates, transducer elements and sample data def _plot_initial_figure(self): # Plot scatters if self.scatters_coords_xz is not None: self._scatter_line = self._ax.scatter(self.scatters_coords_xz[0,:], self.scatters_coords_xz[1,:], color = 'red', s=5, label='scatters') # Plot transducer elements if self.elements_coords_xz is not None: self._elements_line = self._ax.scatter(self.elements_coords_xz[0,:], self.elements_coords_xz[1,:], color = 'green', marker="v", s=80, label='elements') # Plot main image if (self.image_x_range is not None) and (self.image_z_range is not None): self._image_obj = self._ax.imshow(np.zeros(self.data_shape), cmap=cm.gray, origin="lower", aspect="auto", extent=self.image_x_range + self.image_z_range) else: self._image_obj = self._ax.imshow(np.zeros(self.data_shape), cmap=cm.gray, origin="lower", aspect="auto") self._image_obj.set_clim(-self.db_range,0) self._cbar = self._fig.colorbar(self._image_obj, ax=self._ax) self._ax.set_xlabel("X, m") self._ax.set_ylabel("Z, m") self._ax.set_title(self.title) self._ax.invert_yaxis() self._ax.legend() def update_the_figure(self, img_data): data_db = log_compress(img_data, self.db_range) self._image_obj.set_data(data_db) # Plot the figure with updated data plt.draw() plt.pause(.001)
import styled from 'styled-components' import { animated } from '@react-spring/web' export const Main = styled.div` cursor: pointer; color: #676767; -webkit-user-select: none; user-select: none; ` export const Container = styled.div` position: fixed; z-index: 1000; width: 0 auto; bottom: 30px; margin: 0 auto; left: 30px; right: 30px; display: flex; flex-direction: column; pointer-events: none; align-items: flex-end; @media (max-width: 680px) { align-items: center; } ` export const Message = styled(animated.div)` box-sizing: border-box; position: relative; overflow: hidden; width: 40ch; @media (max-width: 680px) { width: 100%; } ` export const Content = styled.div` color: white; background: #445159; opacity: 0.9; padding: 12px 22px; font-size: 1em; display: grid; grid-template-columns: 1fr auto; grid-gap: 10px; overflow: hidden; height: auto; border-radius: 3px; margin-top: 10px; ` export const Button = styled.button` cursor: pointer; pointer-events: all; outline: 0; border: none; background: transparent; display: flex; align-self: flex-end; overflow: hidden; margin: 0; padding: 0; padding-bottom: 14px; color: rgba(255, 255, 255, 0.5); :hover { color: rgba(255, 255, 255, 0.6); } ` export const Life = styled(animated.div)` position: absolute; bottom: 0; left: 0px; width: auto; background-image: linear-gradient(130deg, #00b4e6, #00f0e0); height: 5px; `
#!/bin/sh #SBATCH -A lu2020-2-7 #SBATCH -p lu # time consumption HH:MM:SS #SBATCH -t 10:00:00 #SBATCH -N 1 #SBATCH --tasks-per-node=1 # #SBATCH --exclusive # name for script #SBATCH -J snpla_sbc # controll job outputs #SBATCH -o lunarc_output/lunarc_output_snpla_sbc_%j.out #SBATCH -e lunarc_output/lunarc_output_snpla_sbc_%j.err # notification #SBATCH --mail-user=samuel.wiqvist@matstat.lu.se #SBATCH --mail-type=ALL # load modules ml load GCC/8.3.0 ml load CUDA/10.1.243 ml load OpenMPI/3.1.4 ml load PyTorch/1.6.0-Python-3.7.4 # run program python /home/samwiq/snpla/'seq-posterior-approx-w-nf-dev'/'lotka_volterra'/run_script_sbc_snpla.py 1 154
#!/usr/bin/env bash # # Copyright (c) 2020 The Fujicoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. export LC_ALL=C.UTF-8 export HOST=i686-pc-linux-gnu export CONTAINER_NAME=ci_i686_centos_7 export DOCKER_NAME_TAG=centos:7 export DOCKER_PACKAGES="gcc-c++ glibc-devel.x86_64 libstdc++-devel.x86_64 glibc-devel.i686 libstdc++-devel.i686 ccache libtool make git python3 python36-zmq which patch lbzip2 dash" export GOAL="install" export FUJICOIN_CONFIG="--enable-zmq --with-gui=qt5 --enable-reduce-exports" export CONFIG_SHELL="/bin/dash"
#!/bin/bash # Copyright Johns Hopkins University (Author: Daniel Povey) 2012. Apache 2.0. # Modified by Takafumi Moriya for Japanese speech recognition using CSJ. # This script is for scoring with morpheme. # begin configuration section. cmd=run.pl min_lmwt=5 max_lmwt=17 #end configuration section. [ -f ./path.sh ] && . ./path.sh . parse_options.sh || exit 1; if [ $# -ne 3 ]; then echo "Usage: local/score_csj.sh [--cmd (run.pl|queue.pl...)] <data-dir> <lang-dir|graph-dir> <decode-dir>" echo " Options:" echo " --cmd (run.pl|queue.pl...) # specify how to run the sub-processes." echo " --min_lmwt <int> # minumum LM-weight for lattice rescoring " echo " --max_lmwt <int> # maximum LM-weight for lattice rescoring " exit 1; fi data=$1 lang=$2 dir=$3 model=$dir/../final.mdl # assume model one level up from decoding dir. hubscr=$KALDI_ROOT/tools/sctk/bin/hubscr.pl #hubscr=$KALDI_ROOT/tools/sctk-2.4.0/bin/hubscr.pl [ ! -f $hubscr ] && echo "Cannot find scoring program at $hubscr" && exit 1; hubdir=`dirname $hubscr` for f in $data/text $lang/words.txt $dir/lat.1.gz; do [ ! -f $f ] && echo "$0: expecting file $f to exist" && exit 1; done name=`basename $data`; # e.g. eval1 mkdir -p $dir/scoring/log mkdir -p $dir/label mkdir -p $dir/label/log mkdir -p $dir/label/wer function filter_text_mor { perl -e 'foreach $w (@ARGV) { $bad{$w} = 1; } while(<STDIN>) { @A = split(" ", $_); $id = shift @A; print "$id "; foreach $a (@A) { if (!defined $bad{$a}) { print "$a "; }} print "\n"; }' \ '<UNK>' } function filter_text { perl -e 'foreach $w (@ARGV) { $bad{$w} = 1; } while(<STDIN>) { @A = split(" ", $_); $id = shift @A; print "$id "; foreach $a (@A) { if (!defined $bad{$a}){ @W=split(/\+/,$a); $word=$W[0]; { print "$word "; }}} print "\n"; }' \ '<UNK>' } $cmd LMWT=$min_lmwt:$max_lmwt $dir/scoring/log/best_path.LMWT.log \ lattice-best-path --lm-scale=LMWT --word-symbol-table=$lang/words.txt \ "ark:gunzip -c $dir/lat.*.gz|" ark,t:$dir/scoring/LMWT.tra || exit 1; for lmwt in `seq $min_lmwt $max_lmwt`; do utils/int2sym.pl -f 2- $lang/words.txt <$dir/scoring/$lmwt.tra | \ filter_text > $dir/scoring/$lmwt.txt || exit 1; utils/int2sym.pl -f 2- $lang/words.txt <$dir/scoring/$lmwt.tra | \ filter_text_mor > $dir/label/${lmwt}-trans.text || exit 1; done filter_text <$data/text >$dir/scoring/text.filt filter_text_mor <$data/text >$dir/label/text.filt $cmd LMWT=$min_lmwt:$max_lmwt $dir/scoring/log/score.LMWT.log \ compute-wer --text --mode=present \ ark:$dir/scoring/text.filt ark:$dir/scoring/LMWT.txt ">&" $dir/wer_LMWT || exit 1; $cmd LMWT=$min_lmwt:$max_lmwt $dir/scoring/log/score.LMWT.log \ compute-wer --text --mode=present \ ark:$dir/label/text.filt ark:$dir/label/LMWT-trans.text ">&" $dir/label/wer/wer_LMWT || exit 1; exit 0
class MyClass: def __init__(self, my_variable): self.my_variable = my_variable
function numberToWord(number) { let words = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred' } let word = '' if (number < 0) { word = 'negative '; number = -number; } if (number < 20) { word += words[number]; } else if (number < 100) { word += words[Math.floor(number / 10) * 10]; if (number % 10) { word += '-' + words[number % 10]; } } else if (number < 1000) { word += words[Math.floor(number / 100)] + ' ' + words[100]; if (number % 100) { word += ' and ' + numberToWord(number % 100); } } return word; } console.log(numberToWord(128)); // one hundred and twenty-eight
from django.db import models from yatranepal.models import Places class TravelPackage(models.Model): id = models.AutoField(primary_key=True) packageName = models.CharField(max_length=200) packageDesc = models.TextField() packageImage = models.ImageField(upload_to='packages/') packageSlug = models.CharField(max_length=50) packagePrice = models.IntegerField() packageFeatures = models.TextField() placeName = models.ManyToManyField(Places) def __str__(self): return self.packageName
import math def calculateCircleArea(radius: float) -> float: return math.pi * radius ** 2
<reponame>oTkPoBeHuE/tindergram-bot import { Profile } from '../getProfile'; import { getMockedProfile } from './profile'; export const profiles = new Map<string, Profile>(); export function initializeMockedDB() { for (let i = 0; i < 100; i++) { const profile = getMockedProfile(String(i)); profiles.set(profile.id, profile); } }
/* * Author: <NAME> * DFS Algorithm implementation in JavaScript * DFS Algorithm for traversing or searching graph data structures. */ function traverseDFS (root) { const stack = [root] const res = [] while (stack.length) { const curr = stack.pop() res.push(curr.key) if (curr.right) { stack.push(curr.right) } if (curr.left) { stack.push(curr.left) } } return res.reverse() } function searchDFS (tree, value) { var stack = [] stack.push(tree[0]) while (stack.length !== 0) { for (let i = 0; i < stack.length; i++) { var node = stack.pop() if (node.value === value) { return node } if (node.right) { stack.push(tree[node.right]) } if (node.left) { stack.push(tree[node.left]) } } } return null } var tree = [ { value: 6, left: 1, right: 2 }, { value: 5, left: 3, right: 4 }, { value: 7, left: null, right: 5 }, { value: 3, left: 6, right: null }, { value: 4, left: null, right: null }, { value: 9, left: 7, right: 8 }, { value: 2, left: 9, right: null }, { value: 8, left: null, right: null }, { value: 10, left: null, right: null }, { value: 1, left: null, right: null } ] searchDFS(tree, 9) searchDFS(tree, 10) traverseDFS(6) // 6 // / \ // 5 7 // / \ \ // 3 4 9 // / / \ // 2 8 10 // / // 1
<filename>src/main/java/ru/contextguide/yandexservices/exceptions/YDException.java package ru.contextguide.yandexservices.exceptions; import com.sun.org.slf4j.internal.Logger; import com.sun.org.slf4j.internal.LoggerFactory; class YDException extends Exception { private static final Logger log = LoggerFactory.getLogger(YDException.class); YDException() { super(); } YDException(String message) { super(message); log.error(message); } YDException(String message, Throwable cause) { super(message, cause); log.error(message, cause); } YDException(Throwable cause) { super(cause); log.error(cause.getMessage(), cause); } protected YDException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); log.error(message, cause, enableSuppression, writableStackTrace); } }
<filename>routing.js var history = ''; var routes = { '': 'home.html', '/': 'home.html', '#/home': 'home.html', '#/signin': 'signin.html', '#/blog': 'blog.html', '#/pricing': 'pricing.html', }; async function router(){ console.log(location.hash); var innerElement = ''; var link = window.location.hash; var count = (link.split("/").length - 1); if (count > 1) { innerElement = link.split("/")[2]; link = '#/' + link.split("/")[1]; } if (history === link && innerElement){ scrollIntoView(innerElement); history = link; return; } history = link; var route = routes[link]; if (route) loadPage(route, innerElement); }; router(); async function loadPage(url, innerElement){ const res = await fetch(url); const content = await res.text(); const element = document.getElementById('content'); element.innerHTML = content; window.scrollTo(0, 0); if (innerElement) { scrollIntoView(innerElement); } } function scrollIntoView(id){ document.getElementById(id).scrollIntoView(); } window.addEventListener('hashchange', router);
datastr = "3,2,5,1,7,4,6" lst = datastr.split(',') lst = [int(x) for x in lst]
#include <iostream> using namespace std; int fibo(int n) { if (n <= 1) return n; return fibo(n - 1) + fibo(n - 2); } int main() { int n = 25; cout << "The first "<< n <<" Fibonacci numbers are : "; for (int i = 0; i < n; i++) cout << fibo(i) << " "; return 0; }
<filename>imagenet_results/imagenet_p/test.py<gh_stars>10-100 """ Code modified from here: https://github.com/hendrycks/robustness/blob/master/ImageNet-P/test.py """ from scipy.stats import rankdata import torch.backends.cudnn as cudnn import torch.nn.functional as F import torchvision.datasets as dset import torchvision.transforms as trn import torchvision.transforms.functional as trn_F import torchvision.models as models import numpy as np import argparse import torch import timm import os if __package__ is None: import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from utils.video_loader import VideoFolder parser = argparse.ArgumentParser( description="Evaluates robustness of various nets on ImageNet", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) # Architecture parser.add_argument( "--model-name", "-m", required=True, type=str, choices=["resnetv2_101x3_bitm", "vit_large_patch16_224"], ) parser.add_argument( "--perturbation", "-p", default="brightness", type=str, choices=[ "gaussian_noise", "shot_noise", "motion_blur", "zoom_blur", "spatter", "brightness", "translate", "rotate", "tilt", "scale", "speckle_noise", "gaussian_blur", "snow", "shear", ] # Only 10 of these perturbations are available ) parser.add_argument("--difficulty", "-d", type=int, default=1, choices=[1, 2, 3]) # Acceleration parser.add_argument("--ngpu", type=int, default=4, help="0 = CPU.") args = parser.parse_args() print(args) # /////////////// Norm Stats /////////////// mean = [0.5, 0.5, 0.5] std = [0.5, 0.5, 0.5] # /////////////// Model Setup ////////////// if args.model_name == "resnetv2_101x3_bitm": net = timm.create_model("resnetv2_101x3_bitm", pretrained=True) args.test_bs = 3 * 4 elif args.model_name == "vit_large_patch16_224": net = timm.create_model("vit_large_patch16_224", pretrained=True) args.test_bs = 4 * 4 args.prefetch = os.cpu_count() if args.ngpu > 1: net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu))) if args.ngpu > 0: net.cuda() torch.manual_seed(1) np.random.seed(1) if args.ngpu > 0: torch.cuda.manual_seed(1) net.eval() cudnn.benchmark = True # fire on all cylinders print("Model Loaded\n") ############# Data loader ############# transforms = trn.Compose([trn.ToTensor(), trn.Normalize(mean, std)]) if args.difficulty > 1 and "noise" in args.perturbation: loader = torch.utils.data.DataLoader( VideoFolder( root="ImageNet-P/" + args.perturbation + "_" + str(args.difficulty), transform=transforms, ), batch_size=args.test_bs, shuffle=False, num_workers=os.cpu_count(), pin_memory=True, ) else: loader = torch.utils.data.DataLoader( VideoFolder(root="ImageNet-P/" + args.perturbation, transform=transforms), batch_size=args.test_bs, shuffle=False, num_workers=os.cpu_count(), pin_memory=True, ) print("Data Loaded\n") # /////////////// Stability Measurements /////////////// identity = np.asarray(range(1, 1001)) cum_sum_top5 = np.cumsum(np.asarray([0] + [1] * 5 + [0] * (999 - 5))) recip = 1.0 / identity # def top5_dist(sigma): # result = 0 # for i in range(1,6): # for j in range(min(sigma[i-1], i) + 1, max(sigma[i-1], i) + 1): # if 1 <= j - 1 <= 5: # result += 1 # return result def dist(sigma, mode="top5"): if mode == "top5": return np.sum(np.abs(cum_sum_top5[:5] - cum_sum_top5[sigma - 1][:5])) elif mode == "zipf": return np.sum(np.abs(recip - recip[sigma - 1]) * recip) def ranking_dist( ranks, noise_perturbation=True if "noise" in args.perturbation else False, mode="top5", ): result = 0 step_size = 1 if noise_perturbation else args.difficulty for vid_ranks in ranks: result_for_vid = [] for i in range(step_size): perm1 = vid_ranks[i] perm1_inv = np.argsort(perm1) for rank in vid_ranks[i::step_size][1:]: perm2 = rank result_for_vid.append(dist(perm2[perm1_inv], mode)) if not noise_perturbation: perm1 = perm2 perm1_inv = np.argsort(perm1) result += np.mean(result_for_vid) / len(ranks) return result def flip_prob( predictions, noise_perturbation=True if "noise" in args.perturbation else False ): result = 0 step_size = 1 if noise_perturbation else args.difficulty for vid_preds in predictions: result_for_vid = [] for i in range(step_size): prev_pred = vid_preds[i] for pred in vid_preds[i::step_size][1:]: result_for_vid.append(int(prev_pred != pred)) if not noise_perturbation: prev_pred = pred result += np.mean(result_for_vid) / len(predictions) return result # /////////////// Get Results /////////////// from tqdm import tqdm predictions, ranks = [], [] with torch.no_grad(): for data, target in loader: num_vids = data.size(0) data = data.view(-1, 3, 224, 224).cuda() output = net(data) for vid in output.view(num_vids, -1, 1000): predictions.append(vid.argmax(1).to("cpu").numpy()) ranks.append( [ np.uint16(rankdata(-frame, method="ordinal")) for frame in vid.to("cpu").numpy() ] ) ranks = np.asarray(ranks) print("Computing Metrics\n") print("Flipping Prob\t{:.5f}".format(flip_prob(predictions))) print("Top5 Distance\t{:.5f}".format(ranking_dist(ranks, mode="top5"))) print("Zipf Distance\t{:.5f}".format(ranking_dist(ranks, mode="zipf")))
def fibonacci_generator(): a = 0 b = 1 while True: yield a a, b = b, a + b
import { Defined } from "./Defined"; import { Using } from "./Using"; /** */ export interface DefinedUsing<T> extends Defined<T>, Using<T> {} /** */ export namespace DefinedUsing { /** * * @param using * @param defined * @returns */ export function create<T>(using: T[] | undefined = undefined, defined: T[] | undefined = undefined): DefinedUsing<T> { if (!using) using = []; if (!defined) defined = []; return { defined: defined, using: using, }; } /** * * @returns */ export function empty<T>(): DefinedUsing<T> { return { defined: [], using: [] }; } /** Check wheter or not is the given value atleast implements a DefinedUsing interface * @param value The object to examine * @returns Returns true or false wheter or not the object implements DefinedUsing*/ export function is<T>(value: any): value is DefinedUsing<T> { if (typeof value === "object") { if (Array.isArray(value.using) && Array.isArray(value.defined)) { return true; } } return false; } }
<reponame>gertjandemulder/comunica import type { IActorQueryOperationOutputUpdate } from '@comunica/bus-query-operation'; import { KEY_CONTEXT_READONLY } from '@comunica/bus-query-operation'; import { ActionContext, Bus } from '@comunica/core'; import { ArrayIterator } from 'asynciterator'; import { DataFactory } from 'rdf-data-factory'; import { ActorQueryOperationLoad, KEY_CONTEXT_LENIENT, KEY_CONTEXT_SOURCES } from '../lib/ActorQueryOperationLoad'; const arrayifyStream = require('arrayify-stream'); const DF = new DataFactory(); describe('ActorQueryOperationLoad', () => { let bus: any; let mediatorQueryOperation: any; let mediatorUpdateQuads: any; beforeEach(() => { bus = new Bus({ name: 'bus' }); mediatorQueryOperation = { mediate: jest.fn((arg: any) => Promise.resolve({ quadStream: new ArrayIterator([ DF.quad(DF.namedNode('s'), DF.namedNode('p'), DF.namedNode('o')), ], { autoStart: false }), metadata: () => Promise.resolve({ totalItems: 1 }), type: 'quads', })), }; mediatorUpdateQuads = { mediate: jest.fn(() => Promise.resolve({ updateResult: Promise.resolve(), })), }; }); describe('An ActorQueryOperationLoad instance', () => { let actor: ActorQueryOperationLoad; beforeEach(() => { actor = new ActorQueryOperationLoad({ name: 'actor', bus, mediatorQueryOperation, mediatorUpdateQuads }); }); it('should test on load', () => { const op: any = { operation: { type: 'load' }}; return expect(actor.test(op)).resolves.toBeTruthy(); }); it('should not test on readOnly', () => { const op: any = { operation: { type: 'load' }, context: ActionContext({ [KEY_CONTEXT_READONLY]: true }) }; return expect(actor.test(op)).rejects.toThrowError(`Attempted a write operation in read-only mode`); }); it('should not test on non-load', () => { const op: any = { operation: { type: 'some-other-type' }}; return expect(actor.test(op)).rejects.toBeTruthy(); }); it('should run', async() => { const op: any = { operation: { type: 'load', source: DF.namedNode('URL'), }, }; const output = <IActorQueryOperationOutputUpdate> await actor.run(op); expect(output.type).toEqual('update'); await expect(output.updateResult).resolves.toBeUndefined(); expect(await arrayifyStream(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamInsert)).toEqual([ DF.quad(DF.namedNode('s'), DF.namedNode('p'), DF.namedNode('o')), ]); expect(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamDeleted).toBeUndefined(); expect(mediatorQueryOperation.mediate).toHaveBeenCalledWith({ operation: expect.anything(), context: ActionContext({ [KEY_CONTEXT_SOURCES]: [ 'URL' ], }), }); }); it('should run with a given context', async() => { const op: any = { operation: { type: 'load', source: DF.namedNode('URL'), }, context: ActionContext({ [KEY_CONTEXT_SOURCES]: [ 'SOMETHINGELSE' ], }), }; const output = <IActorQueryOperationOutputUpdate> await actor.run(op); expect(output.type).toEqual('update'); await expect(output.updateResult).resolves.toBeUndefined(); expect(await arrayifyStream(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamInsert)).toEqual([ DF.quad(DF.namedNode('s'), DF.namedNode('p'), DF.namedNode('o')), ]); expect(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamDeleted).toBeUndefined(); expect(mediatorQueryOperation.mediate).toHaveBeenCalledWith({ operation: expect.anything(), context: ActionContext({ [KEY_CONTEXT_SOURCES]: [ 'URL' ], '@comunica/bus-query-operation:operation': expect.anything(), }), }); }); it('should run and allow updateResult to be awaited layer', async() => { const op: any = { operation: { type: 'load', source: DF.namedNode('URL'), }, }; const output = <IActorQueryOperationOutputUpdate> await actor.run(op); expect(output.type).toEqual('update'); expect(await arrayifyStream(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamInsert)).toEqual([ DF.quad(DF.namedNode('s'), DF.namedNode('p'), DF.namedNode('o')), ]); await expect(output.updateResult).resolves.toBeUndefined(); expect(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamDeleted).toBeUndefined(); }); it('should run with destination', async() => { const op: any = { operation: { type: 'load', source: DF.namedNode('URL'), destination: DF.namedNode('GRAPH'), }, }; const output = <IActorQueryOperationOutputUpdate> await actor.run(op); expect(output.type).toEqual('update'); await expect(output.updateResult).resolves.toBeUndefined(); expect(await arrayifyStream(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamInsert)).toEqual([ DF.quad(DF.namedNode('s'), DF.namedNode('p'), DF.namedNode('o'), DF.namedNode('GRAPH')), ]); expect(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamDeleted).toBeUndefined(); }); it('should run for an empty source', async() => { const op: any = { operation: { type: 'load', source: DF.namedNode('URL'), }, }; mediatorQueryOperation.mediate = (arg: any) => Promise.resolve({ quadStream: new ArrayIterator([], { autoStart: false }), metadata: () => Promise.resolve({ totalItems: 0 }), type: 'quads', }); const output = <IActorQueryOperationOutputUpdate> await actor.run(op); expect(output.type).toEqual('update'); await expect(output.updateResult).resolves.toBeUndefined(); expect(await arrayifyStream(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamInsert)).toEqual([]); expect(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamDeleted).toBeUndefined(); }); it('should run in silent mode', async() => { const op: any = { operation: { type: 'load', source: DF.namedNode('URL'), silent: true, }, }; const output = <IActorQueryOperationOutputUpdate> await actor.run(op); expect(output.type).toEqual('update'); await expect(output.updateResult).resolves.toBeUndefined(); expect(await arrayifyStream(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamInsert)).toEqual([ DF.quad(DF.namedNode('s'), DF.namedNode('p'), DF.namedNode('o')), ]); expect(mediatorUpdateQuads.mediate.mock.calls[0][0].quadStreamDeleted).toBeUndefined(); expect(mediatorQueryOperation.mediate).toHaveBeenCalledWith({ operation: expect.anything(), context: ActionContext({ [KEY_CONTEXT_SOURCES]: [ 'URL' ], [KEY_CONTEXT_LENIENT]: true, }), }); }); }); });
<reponame>annio-lab/annio-client-ui<filename>src/app/utils/app-util.ts export class AppUtils { static AppName = process.env.APP_NAME ?? '-'; static AppVersion = process.env.APP_VERSION ?? '-'; static AppIcon = process.env.APP_ICON ?? '-'; static AppDescription = process.env.APP_DESCRIPTION ?? ''; }
/*\ module-type: relinkwikitextrule Handles replacement of filtered transclusions in wiki text like, {{{ [tag[docs]] }}} {{{ [tag[docs]] |tooltip}}} {{{ [tag[docs]] ||TemplateTitle}}} {{{ [tag[docs]] |tooltip||TemplateTitle}}} {{{ [tag[docs]] }}width:40;height:50;}.class.class This renames both the list and the template field. \*/ exports.name = ['filteredtranscludeinline', 'filteredtranscludeblock']; var filterHandler = require("$:/plugins/flibbles/relink/js/utils").getType('filter'); var utils = require("./utils.js"); exports.report = function(text, callback, options) { var m = this.match, filter = m[1], template = $tw.utils.trim(m[3]), append = template ? '||' + template + '}}}' : '}}}'; filterHandler.report(filter, function(title, blurb) { callback(title, '{{{' + blurb + append); }, options); if (template) { callback(template, '{{{' + $tw.utils.trim(filter).replace(/\r?\n/mg, ' ') + '||}}}'); } this.parser.pos = this.matchRegExp.lastIndex; }; exports.relink = function(text, fromTitle, toTitle, options) { var m = this.match, filter = m[1], tooltip = m[2], template = m[3], style = m[4], classes = m[5], parser = this.parser, entry = {}; parser.pos = this.matchRegExp.lastIndex; var modified = false; var filterEntry = filterHandler.relink(filter, fromTitle, toTitle, options); if (filterEntry !== undefined) { if (filterEntry.output) { filter = filterEntry.output; modified = true; } if (filterEntry.impossible) { entry.impossible = true; } } if ($tw.utils.trim(template) === fromTitle) { // preserves user-inputted whitespace template = template.replace(fromTitle, toTitle); modified = true; } if (!modified) { if (!entry.impossible) { return undefined; } } else { var output = this.makeFilteredtransclude(this.parser, filter, tooltip, template, style, classes); if (output === undefined) { entry.impossible = true; } else { // By copying over the ending newline of the original // text if present, thisrelink method thus works for // both the inline and block rule entry.output = output + utils.getEndingNewline(m[0]); } } return entry; }; exports.makeFilteredtransclude = function(parser, filter, tooltip, template, style, classes) { if (canBePretty(filter) && canBePrettyTemplate(template)) { return prettyList(filter, tooltip, template, style, classes); } if (classes !== undefined) { classes = classes.split('.').join(' '); } return utils.makeWidget(parser, '$list', { filter: filter, tooltip: tooltip, template: template, style: style || undefined, itemClass: classes}); }; function prettyList(filter, tooltip, template, style, classes) { if (tooltip === undefined) { tooltip = ''; } else { tooltip = "|" + tooltip; } if (template === undefined) { template = ''; } else { template = "||" + template; } if (classes === undefined) { classes = ''; } else { classes = "." + classes; } style = style || ''; return "{{{"+filter+tooltip+template+"}}"+style+"}"+classes; }; function canBePretty(filter) { return filter.indexOf('|') < 0 && filter.indexOf('}}') < 0; }; function canBePrettyTemplate(template) { return !template || ( template.indexOf('|') < 0 && template.indexOf('{') < 0 && template.indexOf('}') < 0); };
/**Note on screen resolutions - See: http://www.itunesextractor.com/iphone-ipad-resolution.html * Tests will be run on these resolutions: * - iPhone6s - 375x667 * - iPad air - 768x1024 * - Desktop - 1920x1080 * * beforeEach will set the mode to Desktop. Any tests requiring a different resolution will must set explicitly. * * @author ijarif */ var WorkItemListPage = require('./page-objects/work-item-list.page'), testSupport = require('./testSupport'), constants = require('./constants'); describe('Labels CRUD Tests', function () { var page, items, browserMode, until = protractor.ExpectedConditions, newLabelTitle = "My Test Label", defaultSelectedLableTitle = "Example Label 1", testLabelTitle1 = "Example Label 0", testLabelTitle2 = "Example Label 3"; // From mock data beforeEach(function () { testSupport.setBrowserMode('desktop'); page = new WorkItemListPage(true); testSupport.setTestSpace(page); }); it('Verify add label button exists', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); expect(detailPage.addLabelButton.isPresent()).toBeTruthy(); expect(detailPage.selectLabelDropdown.isPresent()).toBeFalsy(); detailPage.clickAddLabelButton(); expect(detailPage.selectLabelDropdown.isPresent()).toBeTruthy(); expect(detailPage.createLabelButton.isPresent()).toBeTruthy(); }); it('Verify create new label button is clickable', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); let clickEvent = detailPage.clickAddLabelButton(); expect(clickEvent).toBeDefined(); }); // This test has been moved back from smokeTest it('Verify create new Label', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); detailPage.clickAddLabelButton(); let origLabelCount detailPage.labelsCount.then(function(count){ origLabelCount = count }); detailPage.clickCreateLabelButton(); detailPage.setLabelName(newLabelTitle); detailPage.clickLabelCheckbox(); // Verify label count has increased by 1 detailPage.labelsCount.then(function(count){ expect(count).toBe(origLabelCount + 1); }); // Verify label exists in the list expect(detailPage.listOfLabels().getText()).toContain(detailPage.getLabelByTitle(newLabelTitle).getText()); }) it('Verify adding existing labels', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); detailPage.clickAddLabelButton(); detailPage.selectLabelByTitle(testLabelTitle1); detailPage.selectLabelByTitle(testLabelTitle2); /* TODO - Mocking data is incorrect - text returns is: Example Label 1,Example Label 1, expect(detailPage.attachedLabels().getText()).toContain(testLabelTitle1); expect(detailPage.attachedLabels().getText()).toContain(testLabelTitle2); */ expect(detailPage.attachedLabels().getText()).toContain(defaultSelectedLableTitle) }); it('Verify removing existing label by unchecking label', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); detailPage.clickAddLabelButton(); // Uncheck label by clicking on it again detailPage.selectLabelByTitle(defaultSelectedLableTitle); detailPage.clickLabelClose(); // Verify Label is removed (in detail page) expect(detailPage.attachedLabels()).not.toContain(defaultSelectedLableTitle); }); it('Verify removing existing label by clicking x', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); // Uncheck label by clicking on it again //// detailPage.removeLabelByTitle(defaultSelectedLableTitle); // Verify Label is removed (in detail page) expect(detailPage.attachedLabels()).not.toContain(defaultSelectedLableTitle); }); it('Verify adding new label', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); detailPage.clickAddLabelButton(); detailPage.clickCreateLabelButton(); detailPage.setLabelName(newLabelTitle); detailPage.clickLabelCheckbox(); detailPage.selectLabelByTitle(newLabelTitle); // Verify label added on detail page /* TODO - Mocking data is incorrect - text returns is: Example Label 1,Example Label 1, expect(detailPage.attachedLabels().getText()).toContain(newLabelTitle); */ // Verify label added on list page /* TODO - Mocking data is incorrect - text returns is: Example Label 1,Example Label 1, expect(page.workItemAttachedLabels(page.firstWorkItem).getText()).toContain(newLabelTitle); */ }); it('Verify removing new label', function(){ var detailPage = page.clickWorkItem(page.firstWorkItem); detailPage.clickAddLabelButton(); detailPage.clickCreateLabelButton(); detailPage.setLabelName(newLabelTitle); detailPage.clickLabelCheckbox(); detailPage.selectLabelByTitle(newLabelTitle); // Verify new label is added expect(detailPage.listOfLabels().getText()).toContain(newLabelTitle); detailPage.clickLabelClose(); expect(detailPage.listOfLabels().getText()).not.toContain(newLabelTitle); }); // This test has been moved to smokeTest // it('Verify added label appears on the list page', function(){ // var detailPage = page.clickWorkItem(page.firstWorkItem); // detailPage.clickAddLabelButton(); // detailPage.selectLabelByTitle(testLabelTitle1); // detailPage.clickLabelClose(); // detailPage.clickWorkItemDetailCloseButton(); // expect(page.workItemAttachedLabels(page.firstWorkItem).getText()).toContain(testLabelTitle1); // }); });
var _neon_mem_copy_tests_8cpp = [ [ "BOOST_AUTO_TEST_CASE", "_neon_mem_copy_tests_8cpp.xhtml#a2abcf0adfa16189f3bfd9bcea4fbe2d8", null ], [ "BOOST_AUTO_TEST_CASE", "_neon_mem_copy_tests_8cpp.xhtml#a718b0bcc2cf75184b0bb5caebc833f4b", null ], [ "BOOST_AUTO_TEST_CASE", "_neon_mem_copy_tests_8cpp.xhtml#aa2efe1a9beddcd738f414333539ad46b", null ], [ "BOOST_AUTO_TEST_CASE", "_neon_mem_copy_tests_8cpp.xhtml#a381bbc3853130f7c4bf41eeccf70f9e3", null ] ];
#!/usr/bin/env bash # Copyright 2020 Jian Wu # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) set -eu stage="1-4" space="<space>" dataset=chime4 track="isolated_1ch_track" chime4_data_dir=/home/jwu/doc/data/CHiME4 wsj1_data_dir=/home/jwu/doc/data/wsj1 gpu=0 am_exp=1a epochs=60 num_workers=4 batch_size=32 beam_size=16 nbest=8 ctc_weight=0.2 len_norm=true test_sets="dt05_real dt05_simu et05_real et05_simu" . ./utils/parse_options.sh || exit 1 beg=$(echo $stage | awk -F '-' '{print $1}') end=$(echo $stage | awk -F '-' '{print $2}') [ -z $end ] && end=$beg if [ $end -ge 1 ] && [ $beg -le 1 ]; then echo "Stage 1: preparing data ..." ./local/clean_wsj0_data_prep.sh $chime4_data_dir/CHiME3/data/WSJ0 ./local/clean_wsj1_data_prep.sh $wsj1_data_dir ./local/simu_noisy_chime4_data_prep.sh $chime4_data_dir ./local/real_noisy_chime4_data_prep.sh $chime4_data_dir ./local/simu_enhan_chime4_data_prep.sh $track $chime4_data_dir/data/audio/16kHz/$track ./local/real_enhan_chime4_data_prep.sh $track $chime4_data_dir/data/audio/16kHz/$track ./local/chime4_format_dir.sh fi if [ $end -ge 2 ] && [ $beg -le 2 ]; then echo "Stage 2: tokenizing ..." for name in dev train; do ./utils/tokenizer.py \ --dump-vocab data/$dataset/dict \ --filter-units "<*IN*>,<*MR.*>,<NOISE>" \ --add-units "<sos>,<eos>,<unk>" \ --space $space \ --unit char \ data/$dataset/$name/text \ data/$dataset/$name/char done fi if [ $end -ge 3 ] && [ $beg -le 3 ]; then echo "Stage 3: training AM ..." ./scripts/train.sh \ --gpu $gpu \ --seed 666 \ --epochs $epochs \ --batch-size $batch_size \ --num-workers $num_workers \ --prog-interval 100 \ --eval-interval -1 \ am $dataset $am_exp fi if [ $end -ge 4 ] && [ $beg -le 4 ]; then echo "Stage 4: decoding ..." for name in $test_sets; do name=${name}_${track} ./scripts/decode.sh \ --score true \ --text data/$dataset/$name/text \ --beam-size $beam_size \ --max-len 220 \ --dict exp/$dataset/$am_exp/dict \ --nbest $nbest \ --space "<space>" \ --ctc-weight $ctc_weight \ --len-norm $len_norm \ $dataset $am_exp \ data/$dataset/$name/wav.scp \ exp/$dataset/$am_exp/$name & done wait fi
<gh_stars>0 import discord, os, json, asyncio from discord.ext import commands from discord_slash import SlashCommand def get_token(): a_file = open("no-move.json", "r") json_object_nm = json.load(a_file) a_file.close() token = str(json_object_nm['token']['bot']) return token bot = commands.Bot(command_prefix="prefix", intents=discord.Intents.all()) slash = SlashCommand(bot, override_type = True, sync_commands=True, sync_on_cog_reload=True) @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandOnCooldown): await ctx.send(f"Cette commande est en cooldown, tu pourras la réutiliser dans {round(error.retry_after, 2)}\n*(commandes **daily** et **rep** : 24h & commande **rep** : 6h)*") for filename in os.listdir('./cogs'): if filename.endswith('.py'): bot.load_extension(f'cogs.{filename[:-3]}') bot.run(get_token())
# rubocop:disable Metrics/LineLength # == Schema Information # # Table name: group_member_notes # # id :integer not null, primary key # content :text not null # content_formatted :text not null # created_at :datetime not null # updated_at :datetime not null # group_member_id :integer not null # user_id :integer not null # # Foreign Keys # # fk_rails_b689eab49d (group_member_id => group_members.id) # fk_rails_ea0e9e51b1 (user_id => users.id) # # rubocop:enable Metrics/LineLength class GroupMemberNote < ApplicationRecord include ContentProcessable belongs_to :group_member, required: true belongs_to :user, required: true validates :content, presence: true processable :content, InlinePipeline scope :visible_for, ->(user) { members = GroupMember.with_permission(:members).for_user(user) joins(:group_member).where(group_members: { group_id: members.select(:group_id) }) } end
#!/usr/bin/env python # # Public Domain 2014-2017 MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # 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 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. import wiredtiger, wttest from wtdataset import SimpleDataSet from wtscenario import make_scenarios # test_cursor_pin.py # Smoke-test fast-path searching for pinned pages before re-descending # the tree. class test_cursor_pin(wttest.WiredTigerTestCase): uri = 'file:cursor_pin' nentries = 10000 config = 'allocation_size=512,leaf_page_max=512' scenarios = make_scenarios([ ('recno', dict(keyfmt='r')), ('string', dict(keyfmt='S')), ]) # Create a multi-page file, confirm that a simple search to the local # page works, followed by a search to a different page. def test_smoke(self): ds = SimpleDataSet(self, self.uri, self.nentries, config=self.config, key_format=self.keyfmt) ds.populate() self.reopen_conn() c = self.session.open_cursor(self.uri, None) c.set_key(ds.key(100)) self.assertEqual(c.search(), 0) self.assertEqual(c.get_value(), ds.value(100)) c.set_key(ds.key(101)) self.assertEqual(c.search(), 0) self.assertEqual(c.get_value(), ds.value(101)) c.set_key(ds.key(9999)) self.assertEqual(c.search(), 0) self.assertEqual(c.get_value(), ds.value(9999)) # Forward check. def forward(self, c, ds, max, notfound): for i in range(1, max + 1): c.set_key(ds.key(i)) if i in notfound: self.assertEqual(c.search(), wiredtiger.WT_NOTFOUND) else: self.assertEqual(c.search(), 0) self.assertEqual(c.get_value(), ds.value(i)) # Backward check. def backward(self, c, ds, max, notfound): for i in range(max, 0, -1): c.set_key(ds.key(i)) if i in notfound: self.assertEqual(c.search(), wiredtiger.WT_NOTFOUND) else: self.assertEqual(c.search(), 0) self.assertEqual(c.get_value(), ds.value(i)) # Create a multi-page file, search backward, forward to check page # boundaries. def test_basic(self): ds = SimpleDataSet(self, self.uri, self.nentries, config=self.config, key_format=self.keyfmt) ds.populate() self.reopen_conn() c = self.session.open_cursor(self.uri, None) self.forward(c, ds, self.nentries, []) self.backward(c, ds, self.nentries, []) # Create a multi-page file with a big chunk of missing space in the # middle (to exercise column-store searches). def test_missing(self): ds = SimpleDataSet(self, self.uri, self.nentries, config=self.config, key_format=self.keyfmt) ds.populate() c = self.session.open_cursor(self.uri, None) for i in range(self.nentries + 3000, self.nentries + 5001): c[ds.key(i)] = ds.value(i) self.reopen_conn() c = self.session.open_cursor(self.uri, None) self.forward(c, ds, self.nentries + 5000, list(range(self.nentries + 1, self.nentries + 3000))) self.backward(c, ds, self.nentries + 5000, list(range(self.nentries + 1, self.nentries + 3000))) # Insert into the empty space so we test searching inserted items. for i in range(self.nentries + 1000, self.nentries + 2001): c[ds.key(i)] = ds.value(i) self.forward(c, ds, self.nentries + 5000, list(range(self.nentries + 1, self.nentries + 1000) +\ range(self.nentries + 2001, self.nentries + 3000))) self.backward(c, ds, self.nentries + 5000, list(range(self.nentries + 1, self.nentries + 1000) +\ range(self.nentries + 2001, self.nentries + 3000))) if __name__ == '__main__': wttest.run()
<gh_stars>0 package cyclops.rxjava2.adapter.impl; import cyclops.container.persistent.PersistentCollection; import cyclops.rxjava2.companion.Functions; import cyclops.container.control.LazyEither; import cyclops.container.control.Maybe; import cyclops.container.control.Option; import cyclops.container.immutable.impl.Seq; import cyclops.container.immutable.impl.Vector; import cyclops.container.immutable.tuple.Tuple; import cyclops.container.immutable.tuple.Tuple2; import cyclops.container.immutable.tuple.Tuple3; import cyclops.container.immutable.tuple.Tuple4; import cyclops.function.combiner.Monoid; import cyclops.function.combiner.Reducer; import cyclops.reactive.ReactiveSeq; import cyclops.reactive.companion.Spouts; import io.reactivex.Flowable; import io.reactivex.Single; import java.util.Deque; import java.util.Iterator; import java.util.Optional; import java.util.Spliterator; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.BaseStream; import java.util.stream.Collector; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import lombok.AllArgsConstructor; import lombok.Getter; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; @AllArgsConstructor public class FlowableReactiveSeqImpl<T> implements ReactiveSeq<T> { private final static Object UNSET = new Object(); @lombok.With @Getter Flowable<T> flowable; public <R> FlowableReactiveSeqImpl<R> flux(Flowable<R> flux) { return new FlowableReactiveSeqImpl<>(flux); } public <R> FlowableReactiveSeqImpl<R> flux(ReactiveSeq<R> flux) { if (flux instanceof FlowableReactiveSeqImpl) { return (FlowableReactiveSeqImpl) flux; } return new FlowableReactiveSeqImpl<>(Flowable.fromPublisher(flux)); } @Override public <R> ReactiveSeq<R> coflatMap(Function<? super ReactiveSeq<T>, ? extends R> fn) { return flux(Flowable.just(fn.apply(this))); } @Override public <T1> ReactiveSeq<T1> unit(T1 unit) { return flux(Flowable.just(unit)); } @Override public <U> U foldRight(U identity, BiFunction<? super T, ? super U, ? extends U> accumulator) { return flowable.reduce(identity, (a, b) -> accumulator.apply(b, a)) .blockingGet(); } @Override public <U, R> ReactiveSeq<R> zipWithStream(Stream<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) { if (other instanceof Publisher) { return zip(zipper, (Publisher<U>) other); } return flux(flowable.zipWith((Iterable<U>) ReactiveSeq.fromStream((Stream<U>) other), Functions.rxBifunction(zipper))); } @Override public <U, R> ReactiveSeq<R> zipLatest(Publisher<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) { return flux(Flowable.combineLatest(flowable, other, (a, b) -> zipper.apply(a, b))); } @Override public <U, R> ReactiveSeq<R> zip(BiFunction<? super T, ? super U, ? extends R> zipper, Publisher<? extends U> other) { return flux(flowable.zipWith(other, Functions.rxBifunction(zipper))); } @Override public <U> ReactiveSeq<Tuple2<T, U>> zipWithPublisher(Publisher<? extends U> other) { return flux(flowable.zipWith(other, Tuple::tuple)); } @Override public ReactiveSeq<T> cycle() { return flux(flowable.repeat()); } @Override public Tuple2<ReactiveSeq<T>, ReactiveSeq<T>> duplicate() { return Spouts.from(flowable) .duplicate() .transform((s1, s2) -> Tuple.tuple(flux(s1), flux(s2))); } @Override public Tuple2<ReactiveSeq<T>, ReactiveSeq<T>> duplicate(Supplier<Deque<T>> bufferFactory) { return Spouts.from(flowable) .duplicate(bufferFactory) .transform((s1, s2) -> Tuple.tuple(flux(s1), flux(s2))); } @Override public Tuple3<ReactiveSeq<T>, ReactiveSeq<T>, ReactiveSeq<T>> triplicate() { return Spouts.from(flowable) .triplicate() .transform((s1, s2, s3) -> Tuple.tuple(flux(s1), flux(s2), flux(s3))); } @Override public Tuple3<ReactiveSeq<T>, ReactiveSeq<T>, ReactiveSeq<T>> triplicate(Supplier<Deque<T>> bufferFactory) { return Spouts.from(flowable) .triplicate(bufferFactory) .transform((s1, s2, s3) -> Tuple.tuple(flux(s1), flux(s2), flux(s3))); } @Override public Tuple4<ReactiveSeq<T>, ReactiveSeq<T>, ReactiveSeq<T>, ReactiveSeq<T>> quadruplicate() { return Spouts.from(flowable) .quadruplicate() .to(t4 -> Tuple.tuple(flux(t4._1()), flux(t4._2()), flux(t4._3()), flux(t4._4()))); } @Override public Tuple4<ReactiveSeq<T>, ReactiveSeq<T>, ReactiveSeq<T>, ReactiveSeq<T>> quadruplicate(Supplier<Deque<T>> bufferFactory) { return Spouts.from(flowable) .quadruplicate(bufferFactory) .to(t4 -> Tuple.tuple(flux(t4._1()), flux(t4._2()), flux(t4._3()), flux(t4._4()))); } @Override public Tuple2<Option<T>, ReactiveSeq<T>> splitAtHead() { return Spouts.from(flowable) .splitAtHead() .transform((s1, s2) -> Tuple.tuple(s1, flux(s2))); } @Override public Tuple2<ReactiveSeq<T>, ReactiveSeq<T>> splitAt(int where) { return Spouts.from(flowable) .splitAt(where) .transform((s1, s2) -> Tuple.tuple(flux(s1), flux(s2))); } @Override public Tuple2<ReactiveSeq<T>, ReactiveSeq<T>> splitBy(Predicate<T> splitter) { return Spouts.from(flowable) .splitBy(splitter) .transform((s1, s2) -> Tuple.tuple(flux(s1), flux(s2))); } @Override public Tuple2<ReactiveSeq<T>, ReactiveSeq<T>> partition(Predicate<? super T> splitter) { return Spouts.from(flowable) .partition(splitter) .transform((s1, s2) -> Tuple.tuple(flux(s1), flux(s2))); } @Override public <U> ReactiveSeq<Tuple2<T, U>> zipWithStream(Stream<? extends U> other) { if (other instanceof Publisher) { return zipWithPublisher((Publisher<U>) other); } return zipWithStream(other, Tuple::tuple); } @Override public <S, U> ReactiveSeq<Tuple3<T, S, U>> zip3(Iterable<? extends S> second, Iterable<? extends U> third) { return zip(second, Tuple::tuple).zip(third, (a, b) -> Tuple.tuple(a._1(), a._2(), b)); } @Override public <T2, T3, T4> ReactiveSeq<Tuple4<T, T2, T3, T4>> zip4(Iterable<? extends T2> second, Iterable<? extends T3> third, Iterable<? extends T4> fourth) { return zip(second, Tuple::tuple).zip(third, (a, b) -> Tuple.tuple(a._1(), a._2(), b)) .zip(fourth, (a, b) -> (Tuple4<T, T2, T3, T4>) Tuple.tuple(a._1(), a._2(), a._3(), b)); } @Override public ReactiveSeq<Seq<T>> sliding(int windowSize, int increment) { return flux(Spouts.from(flowable) .sliding(windowSize, increment)); } @Override public ReactiveSeq<Vector<T>> grouped(int groupSize) { return flux(Spouts.from(flowable) .grouped(groupSize)); } @Override public ReactiveSeq<Vector<T>> groupedUntil(BiPredicate<Vector<? super T>, ? super T> predicate) { return flux(Spouts.from(flowable) .groupedUntil(predicate)); } @Override public <C extends PersistentCollection<T>, R> ReactiveSeq<R> groupedUntil(BiPredicate<C, ? super T> predicate, Supplier<C> factory, Function<? super C, ? extends R> finalizer) { return flux(Spouts.from(flowable) .groupedUntil(predicate, factory, finalizer)); } @Override public ReactiveSeq<Vector<T>> groupedWhile(BiPredicate<Vector<? super T>, ? super T> predicate) { return flux(Spouts.from(flowable) .groupedWhile(predicate)); } @Override public <C extends PersistentCollection<T>, R> ReactiveSeq<R> groupedWhile(BiPredicate<C, ? super T> predicate, Supplier<C> factory, Function<? super C, ? extends R> finalizer) { return flux(Spouts.from(flowable) .groupedWhile(predicate, factory, finalizer)); } @Override public ReactiveSeq<Vector<T>> groupedBySizeAndTime(int size, long time, TimeUnit t) { return flux(Spouts.from(flowable) .groupedBySizeAndTime(size, time, t)); } @Override public <C extends PersistentCollection<? super T>> ReactiveSeq<C> groupedBySizeAndTime(int size, long time, TimeUnit unit, Supplier<C> factory) { return flux(Spouts.from(flowable) .groupedBySizeAndTime(size, time, unit, factory)); } @Override public <C extends PersistentCollection<? super T>, R> ReactiveSeq<R> groupedBySizeAndTime(int size, long time, TimeUnit unit, Supplier<C> factory, Function<? super C, ? extends R> finalizer) { return flux(Spouts.from(flowable) .groupedBySizeAndTime(size, time, unit, factory, finalizer)); } @Override public <C extends PersistentCollection<? super T>, R> ReactiveSeq<R> groupedByTime(long time, TimeUnit unit, Supplier<C> factory, Function<? super C, ? extends R> finalizer) { return groupedBySizeAndTime(Integer.MAX_VALUE, time, unit, factory, finalizer); } @Override public ReactiveSeq<Vector<T>> groupedByTime(long time, TimeUnit t) { return flux(Spouts.from(flowable) .groupedByTime(time, t)); } @Override public <C extends PersistentCollection<? super T>> ReactiveSeq<C> groupedByTime(long time, TimeUnit unit, Supplier<C> factory) { return flux(Spouts.from(flowable) .groupedByTime(time, unit, factory)); } @Override public <C extends PersistentCollection<? super T>> ReactiveSeq<C> grouped(int size, Supplier<C> supplier) { return flux(Spouts.from(flowable) .grouped(size, () -> supplier.get())); } @Override public ReactiveSeq<Vector<T>> groupedWhile(Predicate<? super T> predicate) { return flux(Spouts.from(flowable) .groupedWhile(predicate)); } @Override public <C extends PersistentCollection<? super T>> ReactiveSeq<C> groupedWhile(Predicate<? super T> predicate, Supplier<C> factory) { return flux(Spouts.from(flowable) .groupedWhile(predicate, factory)); } @Override public ReactiveSeq<T> distinct() { return flux(flowable.distinct()); } @Override public <U> ReactiveSeq<U> scanLeft(U seed, BiFunction<? super U, ? super T, ? extends U> function) { return flux(flowable.scan(seed, (a, b) -> function.apply(a, b))); } @Override public ReactiveSeq<T> sorted() { return flux(flowable.sorted()); } @Override public ReactiveSeq<T> skip(long num) { return flux(flowable.skip(num)); } @Override public void forEach(Consumer<? super T> action) { Spouts.from(flowable) .forEach(action); } @Override public void forEachOrdered(Consumer<? super T> action) { Spouts.from(flowable) .forEachOrdered(action); } @Override public Object[] toArray() { return Spouts.from(flowable) .toArray(); } @Override public <A> A[] toArray(IntFunction<A[]> generator) { return Spouts.from(flowable) .toArray(generator); } @Override public ReactiveSeq<T> removeFirst(Predicate<? super T> pred) { return flux(Spouts.from(flowable) .removeFirst(pred)); } @Override public ReactiveSeq<T> dropWhile(Predicate<? super T> p) { return flux(flowable.skipWhile(Functions.rxPredicate(p))); } @Override public ReactiveSeq<T> dropWhileInclusive(Predicate<? super T> p) { return flux(Spouts.from(flowable) .dropWhileInclusive(p)); } @Override public ReactiveSeq<T> limit(long num) { return flux(flowable.take(num)); } @Override public ReactiveSeq<T> takeWhile(Predicate<? super T> p) { return flux(flowable.takeWhile(t -> p.test(t))); } @Override public ReactiveSeq<T> takeWhileInclusive(Predicate<? super T> p) { return flux(Spouts.from(flowable) .takeWhileInclusive(p)); } @Override public ReactiveSeq<T> takeUntil(Predicate<? super T> p) { return flux(Spouts.from(flowable) .takeUntil(p)); } @Override public ReactiveSeq<T> parallel() { return this; } @Override public boolean allMatch(Predicate<? super T> c) { return Spouts.from(flowable) .allMatch(c); } @Override public boolean anyMatch(Predicate<? super T> c) { return Spouts.from(flowable) .anyMatch(c); } @Override public boolean xMatch(int num, Predicate<? super T> c) { return Spouts.from(flowable) .xMatch(num, c); } @Override public boolean noneMatch(Predicate<? super T> c) { return Spouts.from(flowable) .noneMatch(c); } @Override public String join() { return Spouts.from(flowable) .join(); } @Override public String join(String sep) { return Spouts.from(flowable) .join(sep); } @Override public String join(String sep, String start, String end) { return Spouts.from(flowable) .join(sep, start, end); } @Override public Optional<T> findFirst() { return Spouts.from(flowable) .findFirst(); } @Override public Maybe<T> takeOne() { return Spouts.from(flowable) .takeOne(); } @Override public LazyEither<Throwable, T> findFirstOrError() { return Spouts.from(flowable) .findFirstOrError(); } @Override public Optional<T> findAny() { return Spouts.from(flowable) .findAny(); } @Override public <R> R foldMap(Reducer<R, T> reducer) { return Spouts.from(flowable) .foldMap(reducer); } @Override public <R> R foldMap(Function<? super T, ? extends R> mapper, Monoid<R> reducer) { return Spouts.from(flowable) .foldMap(mapper, reducer); } @Override public T reduce(Monoid<T> reducer) { return Spouts.from(flowable) .reduce(reducer); } @Override public Optional<T> reduce(BinaryOperator<T> accumulator) { return Spouts.from(flowable) .reduce(accumulator); } @Override public T reduce(T identity, BinaryOperator<T> accumulator) { return Spouts.from(flowable) .reduce(identity, accumulator); } @Override public <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) { return Spouts.from(flowable) .reduce(identity, accumulator, combiner); } @Override public Seq<T> reduce(Iterable<? extends Monoid<T>> reducers) { return Spouts.from(flowable) .reduce(reducers); } @Override public T foldRight(Monoid<T> reducer) { return Spouts.from(flowable) .foldRight(reducer); } @Override public T foldRight(T identity, BinaryOperator<T> accumulator) { return Spouts.from(flowable) .foldRight(identity, accumulator); } @Override public <T1> T1 foldMapRight(Reducer<T1, T> reducer) { return Spouts.from(flowable) .foldMapRight(reducer); } @Override public ReactiveSeq<T> stream() { return Spouts.from(flowable); } @Override public <U> FlowableReactiveSeqImpl<U> unitIterable(Iterable<U> U) { return new FlowableReactiveSeqImpl<>(Flowable.fromIterable(U)); } @Override public boolean startsWith(Iterable<T> iterable) { return Spouts.from(flowable) .startsWith(iterable); } @Override public <R> ReactiveSeq<R> map(Function<? super T, ? extends R> fn) { return flux(flowable.map(Functions.rxFunction(fn))); } @Override public <R> ReactiveSeq<R> flatMap(Function<? super T, ? extends Stream<? extends R>> fn) { return flux(flowable.flatMap(s -> ReactiveSeq.fromStream(fn.apply(s)))); } @Override public IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) { return Spouts.from(flowable) .flatMapToInt(mapper); } @Override public LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper) { return Spouts.from(flowable) .flatMapToLong(mapper); } @Override public DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper) { return Spouts.from(flowable) .flatMapToDouble(mapper); } @Override public <R> ReactiveSeq<R> concatMap(Function<? super T, ? extends Iterable<? extends R>> fn) { return flux(flowable.flatMapIterable(Functions.rxFunction(fn))); } @Override public <R> ReactiveSeq<R> mergeMap(Function<? super T, ? extends Publisher<? extends R>> fn) { return flux(flowable.flatMap(Functions.rxFunction(fn))); } @Override public <R> ReactiveSeq<R> mergeMap(int maxConcurrency, Function<? super T, ? extends Publisher<? extends R>> fn) { return flux(flowable.flatMap(Functions.rxFunction(fn), maxConcurrency)); } @Override public <R> ReactiveSeq<R> flatMapStream(Function<? super T, BaseStream<? extends R, ?>> fn) { return this.<R>flux((Flowable) flowable.flatMap(Functions.rxFunction(fn.andThen(s -> { ReactiveSeq<R> res = s instanceof ReactiveSeq ? (ReactiveSeq) s : (ReactiveSeq) ReactiveSeq.fromSpliterator(s.spliterator()); return res; } )))); } @Override public ReactiveSeq<T> filter(Predicate<? super T> fn) { return flux(flowable.filter(Functions.rxPredicate(fn))); } @Override public Iterator<T> iterator() { return flowable.blockingIterable() .iterator(); } @Override public Spliterator<T> spliterator() { return flowable.blockingIterable() .spliterator(); } @Override public boolean isParallel() { return false; } @Override public ReactiveSeq<T> sequential() { return this; } @Override public ReactiveSeq<T> unordered() { return this; } @Override public ReactiveSeq<T> reverse() { return flux(Spouts.from(flowable) .reverse()); } @Override public ReactiveSeq<T> onClose(Runnable closeHandler) { return flux(flowable.doOnComplete(() -> closeHandler.run())); } @Override public void close() { } @Override public ReactiveSeq<T> prependStream(Stream<? extends T> stream) { return flux(Spouts.from(flowable) .prependStream(stream)); } @Override public ReactiveSeq<T> appendAll(T... values) { return flux(Spouts.from(flowable) .appendAll(values)); } @Override public ReactiveSeq<T> append(T value) { return flux(Spouts.from(flowable) .append(value)); } @Override public ReactiveSeq<T> prepend(T value) { return flux(Spouts.from(flowable) .prepend(value)); } @Override public ReactiveSeq<T> prependAll(T... values) { return flux(Spouts.from(flowable) .prependAll(values)); } @Override public boolean endsWith(Iterable<T> iterable) { return Spouts.from(flowable) .endsWith(iterable); } @Override public ReactiveSeq<T> drop(long time, TimeUnit unit) { return flux(flowable.skip(time, unit)); } @Override public ReactiveSeq<T> take(long time, TimeUnit unit) { return flux(flowable.take(time, unit)); } @Override public ReactiveSeq<T> dropRight(int num) { return flux(flowable.skipLast(num)); } @Override public ReactiveSeq<T> takeRight(int num) { return flux(flowable.takeLast(num)); } @Override public T firstValue(T alt) { return flowable.blockingFirst(alt); } @Override public ReactiveSeq<T> onEmptySwitch(Supplier<? extends Stream<T>> switchTo) { return flux(Spouts.from(flowable) .onEmptySwitch(switchTo)); } @Override public ReactiveSeq<T> onEmptyGet(Supplier<? extends T> supplier) { return flux(Spouts.from(flowable) .onEmptyGet(supplier)); } @Override public <X extends Throwable> ReactiveSeq<T> onEmptyError(Supplier<? extends X> supplier) { return flux(Spouts.from(flowable) .onEmptyError(supplier)); } @Override public <U> ReactiveSeq<T> distinct(Function<? super T, ? extends U> keyExtractor) { return flux(flowable.distinct(Functions.rxFunction(keyExtractor))); } @Override public ReactiveSeq<T> xPer(int x, long time, TimeUnit t) { return flux(Spouts.from(flowable) .xPer(x, time, t)); } @Override public ReactiveSeq<T> onePer(long time, TimeUnit t) { return flux(Spouts.from(flowable) .onePer(time, t)); } @Override public ReactiveSeq<T> debounce(long time, TimeUnit t) { return flux(Spouts.from(flowable) .debounce(time, t)); } @Override public ReactiveSeq<T> fixedDelay(long l, TimeUnit unit) { return flux(Spouts.from(flowable) .fixedDelay(l, unit)); } @Override public ReactiveSeq<T> jitter(long maxJitterPeriodInNanos) { return flux(Spouts.from(flowable) .jitter(maxJitterPeriodInNanos)); } @Override public ReactiveSeq<T> onComplete(Runnable fn) { return flux(flowable.doOnComplete(() -> fn.run())); } @Override public ReactiveSeq<T> recover(Function<? super Throwable, ? extends T> fn) { return flux(Spouts.from(flowable) .recover(fn)); } @Override public <EX extends Throwable> ReactiveSeq<T> recover(Class<EX> exceptionClass, Function<? super EX, ? extends T> fn) { return flux(Spouts.from(flowable) .recover(exceptionClass, fn)); } @Override public long count() { return Spouts.from(flowable) .count(); } @Override public ReactiveSeq<T> appendStream(Stream<? extends T> other) { return flux(Spouts.from(flowable) .appendStream(other)); } @Override public ReactiveSeq<T> appendAll(Iterable<? extends T> other) { return flux(Spouts.from(flowable) .appendAll(other)); } @Override public ReactiveSeq<T> prependAll(Iterable<? extends T> other) { return flux(Spouts.from(flowable) .prependAll(other)); } @Override public ReactiveSeq<T> cycle(long times) { return flux(flowable.repeat(times)); } @Override public ReactiveSeq<T> changes() { return flux(Spouts.from(flowable) .changes()); } @Override public <X extends Throwable> Subscription forEachSubscribe(Consumer<? super T> consumer) { return Spouts.from(flowable) .forEachSubscribe(consumer); } @Override public <X extends Throwable> Subscription forEachSubscribe(Consumer<? super T> consumer, Consumer<? super Throwable> consumerError) { return Spouts.from(flowable) .forEachSubscribe(consumer, consumerError); } @Override public <X extends Throwable> Subscription forEachSubscribe(Consumer<? super T> consumer, Consumer<? super Throwable> consumerError, Runnable onComplete) { return Spouts.from(flowable) .forEachSubscribe(consumer, consumerError, onComplete); } @Override public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) { return flowable.collect(() -> supplier.get(), (a, b) -> accumulator.accept(a, b)) .blockingGet(); } @Override public <R> ReactiveSeq<R> reduceAll(R identity, BiFunction<R, ? super T, R> accumulator) { Single<R> inter = flowable.reduce(identity, (a, b) -> accumulator.apply(a, b)); return flux(inter.toFlowable()); } @Override public <R, A> ReactiveSeq<R> collectAll(Collector<? super T, A, R> collector) { Single<A> inter = flowable.collect(() -> collector.supplier() .get(), (a, b) -> collector.accumulator() .accept(a, b)); Single<R> res = inter.map(Functions.rxFunction(collector.finisher())); return flux(res.toFlowable()); } @Override public <R, A> R collect(Collector<? super T, A, R> collector) { A inter = collect(collector.supplier(), collector.accumulator(), null); return collector.finisher() .apply(inter); } @Override public Maybe<T> single(Predicate<? super T> predicate) { return filter(predicate).single(); } @Override public Maybe<T> single() { Maybe.CompletableMaybe<T, T> maybe = Maybe.<T>maybe(); flowable.subscribe(new Subscriber<T>() { Object value = UNSET; Subscription sub; @Override public void onSubscribe(Subscription s) { this.sub = s; s.request(Long.MAX_VALUE); } @Override public void onNext(T t) { if (value == UNSET) { value = t; } else { maybe.completeAsNone(); sub.cancel(); } } @Override public void onError(Throwable t) { maybe.completeExceptionally(t); } @Override public void onComplete() { if (value == UNSET) { maybe.completeAsNone(); } else { maybe.complete((T) value); } } }); return maybe; } @Override public void subscribe(Subscriber<? super T> s) { flowable.subscribe(s); } @Override public <R> R fold(Function<? super ReactiveSeq<T>, ? extends R> sync, Function<? super ReactiveSeq<T>, ? extends R> reactiveStreams, Function<? super ReactiveSeq<T>, ? extends R> asyncNoBackPressure) { return reactiveStreams.apply(this); } @Override public void forEachAsync(Consumer<? super T> action) { this.flowable.subscribe(a -> action.accept(a)); } @Override public ReactiveSeq<T> recoverWith(Function<Throwable, ? extends Publisher<? extends T>> fn) { return flux(Spouts.from(flowable) .recoverWith(fn)); } @Override public ReactiveSeq<T> onError(Consumer<? super Throwable> c) { return flux(Spouts.from(flowable) .onError(c)); } }
#!/usr/bin/env bash if [ "$#" -ne 4 ] then echo "Usage: deploy.sh CHART_DIR APP_NAME TARGET_ENV TARGET_VER" exit 1 fi CHART_DIR=$1 APP_NAME=$2 TARGET_ENV=$3 TARGET_VER=$4 VALUES=$CHART_DIR/$TARGET_ENV.yaml OFFLINE_COLOUR=$(kubectl get service/$TARGET_ENV-$APP_NAME-offline -o=jsonpath="{.spec.selector.colour}") if [[ -z "${OFFLINE_COLOUR}" ]]; then OFFLINE_COLOUR="blue" fi if [OFFLINE_COLOUR = "blue"]; then ONLINE_COLOUR="green" else ONLINE_COLOUR="blue" fi echo "Deploying $TARGET_VER from $CHART_DIR to: $TARGET_ENV-$OFFLINE_COLOUR-$APP_NAME" if helm upgrade $TARGET_ENV-$OFFLINE_COLOUR-$APP_NAME $CHART_DIR -f $VALUES --install --force --recreate-pods --wait --timeout=300 --set bluegreen.deployment.colour=$OFFLINE_COLOUR,bluegreen.deployment.version=$TARGET_VER; then echo "Successfully upgraded, switching colour to $OFFLINE_COLOUR" helm upgrade $TARGET_ENV-service-$APP_NAME $CHART_DIR -f $VALUES --install --force --wait --timeout=300 --set bluegreen.is_service_release=true,bluegreen.service.selector.colour=$OFFLINE_COLOUR echo "Successfully upgraded service, scaling old $ONLINE_COLOUR pods replica set to 0" helm upgrade $TARGET_ENV-$ONLINE_COLOUR-$APP_NAME $CHART_DIR -f $VALUES --install --force --recreate-pods --wait --timeout=300 --set bluegreen.deployment.colour=$ONLINE_COLOUR,bluegreen.deployment.version=$TARGET_VER else LAST_GOOD_REV=$(helm history ${TARGET_ENV}-${OFFLINE_COLOUR}-${APP_NAME} -o json | jq -r -M --arg DEPLOYED "DEPLOYED" '[.[] | select(.status==$DEPLOYED)] | reverse | .[0] | .revision') int_reg='^[0-9]+$' if ! [[ $LAST_GOOD_REV =~ $int_reg ]] ; then echo "Failed upgrade, rolling back to 0" helm rollback --force --recreate-pods --wait --timeout=600 $TARGET_ENV-$OFFLINE_COLOUR-$APP_NAME 0 else echo "Failed upgrade, rolling back to $LAST_GOOD_REV" helm rollback --force --recreate-pods --wait --timeout=600 $TARGET_ENV-$OFFLINE_COLOUR-$APP_NAME $LAST_GOOD_REV fi exit 1 fi
#!/bin/bash # # https://github.com/l-n-s/wireguard-install # # Copyright (c) 2018 Viktor Villainov. Released under the MIT License. WG_CONFIG="/etc/wireguard/wg0.conf" function get_free_udp_port { local port=$(shuf -i 2000-65000 -n 1) ss -lau | grep $port > /dev/null if [[ $? == 1 ]] ; then echo "$port" else get_free_udp_port fi } if [[ "$EUID" -ne 0 ]]; then echo "Sorry, you need to run this as root" exit fi if [[ ! -e /dev/net/tun ]]; then echo "The TUN device is not available. You need to enable TUN before running this script" exit fi if [ -e /etc/centos-release ]; then DISTRO="CentOS" elif [ -e /etc/debian_version ]; then DISTRO=$( lsb_release -is ) else echo "Your distribution is not supported (yet)" exit fi if [ "$( systemd-detect-virt )" == "openvz" ]; then echo "OpenVZ virtualization is not supported" exit fi if [ ! -f "$WG_CONFIG" ]; then ### Install server and add default client INTERACTIVE=${INTERACTIVE:-yes} PRIVATE_SUBNET=${PRIVATE_SUBNET:-"10.9.0.0/24"} PRIVATE_SUBNET_MASK=$( echo $PRIVATE_SUBNET | cut -d "/" -f 2 ) GATEWAY_ADDRESS="${PRIVATE_SUBNET::-4}1" if [ "$SERVER_HOST" == "" ]; then SERVER_HOST=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) if [ "$INTERACTIVE" == "yes" ]; then read -p "Servers public IP address is $SERVER_HOST. Is that correct? [y/n]: " -e -i "y" CONFIRM if [ "$CONFIRM" == "n" ]; then echo "Aborted. Use environment variable SERVER_HOST to set the correct public IP address" exit fi fi fi if [ "$SERVER_PORT" == "" ]; then SERVER_PORT=$( get_free_udp_port ) fi if [ "$CLIENT_DNS" == "" ]; then echo "Which DNS do you want to use with the VPN?" echo " 1) Cloudflare" echo " 2) Google" echo " 3) OpenDNS" read -p "DNS [1-3]: " -e -i 1 DNS_CHOICE case $DNS_CHOICE in 1) CLIENT_DNS="176.107.131.43,176.107.131.43" ;; 2) CLIENT_DNS="8.8.8.8,8.8.4.4" ;; 3) CLIENT_DNS="208.67.222.222,208.67.220.220" ;; esac fi if [ "$CLIENT_NAME" == "" ]; then read -p "Tell me a name for the client config file. Use one word only, no special characters: " -e -i "client" CLIENT_NAME fi if [ "$DISTRO" == "Ubuntu" ]; then apt-get install software-properties-common -y add-apt-repository ppa:wireguard/wireguard -y apt update apt install linux-headers-$(uname -r) wireguard qrencode iptables-persistent -y elif [ "$DISTRO" == "Debian" ]; then echo "deb http://deb.debian.org/debian/ unstable main" > /etc/apt/sources.list.d/unstable.list printf 'Package: *\nPin: release a=unstable\nPin-Priority: 90\n' > /etc/apt/preferences.d/limit-unstable apt-get install software-properties-common -y apt update apt install linux-headers-$(uname -r) wireguard qrencode iptables-persistent -y elif [ "$DISTRO" == "CentOS" ]; then curl -Lo /etc/yum.repos.d/wireguard.repo https://copr.fedorainfracloud.org/coprs/jdoss/wireguard/repo/epel-7/jdoss-wireguard-epel-7.repo yum install epel-release -y yum install wireguard-dkms qrencode wireguard-tools firewalld -y fi SERVER_PRIVKEY=$( wg genkey ) SERVER_PUBKEY=$( echo $SERVER_PRIVKEY | wg pubkey ) CLIENT_PRIVKEY=$( wg genkey ) CLIENT_PUBKEY=$( echo $CLIENT_PRIVKEY | wg pubkey ) CLIENT_ADDRESS="${PRIVATE_SUBNET::-4}3" mkdir -p /etc/wireguard touch $WG_CONFIG && chmod 600 $WG_CONFIG echo "# $PRIVATE_SUBNET $SERVER_HOST:$SERVER_PORT $SERVER_PUBKEY $CLIENT_DNS [Interface] Address = $GATEWAY_ADDRESS/$PRIVATE_SUBNET_MASK ListenPort = $SERVER_PORT PrivateKey = $SERVER_PRIVKEY SaveConfig = false" > $WG_CONFIG echo "# $CLIENT_NAME [Peer] PublicKey = $CLIENT_PUBKEY AllowedIPs = $CLIENT_ADDRESS/32" >> $WG_CONFIG echo "[Interface] PrivateKey = $CLIENT_PRIVKEY Address = $CLIENT_ADDRESS/$PRIVATE_SUBNET_MASK DNS = $CLIENT_DNS [Peer] PublicKey = $SERVER_PUBKEY AllowedIPs = 0.0.0.0/0, ::/0 Endpoint = $SERVER_HOST:$SERVER_PORT PersistentKeepalive = 25" > $HOME/$CLIENT_NAME-wg0.conf qrencode -t ansiutf8 -l L < $HOME/$CLIENT_NAME-wg0.conf echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf echo "net.ipv4.conf.all.forwarding=1" >> /etc/sysctl.conf echo "net.ipv6.conf.all.forwarding=1" >> /etc/sysctl.conf sysctl -p if [ "$DISTRO" == "CentOS" ]; then systemctl start firewalld systemctl enable firewalld firewall-cmd --zone=public --add-port=$SERVER_PORT/udp firewall-cmd --zone=trusted --add-source=$PRIVATE_SUBNET firewall-cmd --permanent --zone=public --add-port=$SERVER_PORT/udp firewall-cmd --permanent --zone=trusted --add-source=$PRIVATE_SUBNET firewall-cmd --direct --add-rule ipv4 nat POSTROUTING 0 -s $PRIVATE_SUBNET ! -d $PRIVATE_SUBNET -j SNAT --to $SERVER_HOST firewall-cmd --permanent --direct --add-rule ipv4 nat POSTROUTING 0 -s $PRIVATE_SUBNET ! -d $PRIVATE_SUBNET -j SNAT --to $SERVER_HOST else iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT iptables -A FORWARD -m conntrack --ctstate NEW -s $PRIVATE_SUBNET -m policy --pol none --dir in -j ACCEPT iptables -t nat -A POSTROUTING -s $PRIVATE_SUBNET -m policy --pol none --dir out -j MASQUERADE iptables -A INPUT -p udp --dport $SERVER_PORT -j ACCEPT iptables-save > /etc/iptables/rules.v4 fi systemctl enable wg-quick@wg0.service systemctl start wg-quick@wg0.service # TODO: unattended updates, apt install dnsmasq ntp echo "Client config --> $HOME/$CLIENT_NAME-wg0.conf" echo "Now reboot the server and enjoy your fresh VPN installation! :^)" else ### Server is installed, add a new client CLIENT_NAME="$1" if [ "$CLIENT_NAME" == "" ]; then echo "Tell me a name for the client config file. Use one word only, no special characters." read -p "Client name: " -e CLIENT_NAME fi CLIENT_PRIVKEY=$( wg genkey ) CLIENT_PUBKEY=$( echo $CLIENT_PRIVKEY | wg pubkey ) PRIVATE_SUBNET=$( head -n1 $WG_CONFIG | awk '{print $2}') PRIVATE_SUBNET_MASK=$( echo $PRIVATE_SUBNET | cut -d "/" -f 2 ) SERVER_ENDPOINT=$( head -n1 $WG_CONFIG | awk '{print $3}') SERVER_PUBKEY=$( head -n1 $WG_CONFIG | awk '{print $4}') CLIENT_DNS=$( head -n1 $WG_CONFIG | awk '{print $5}') LASTIP=$( grep "/32" $WG_CONFIG | tail -n1 | awk '{print $3}' | cut -d "/" -f 1 | cut -d "." -f 4 ) CLIENT_ADDRESS="${PRIVATE_SUBNET::-4}$((LASTIP+1))" echo "# $CLIENT_NAME [Peer] PublicKey = $CLIENT_PUBKEY AllowedIPs = $CLIENT_ADDRESS/32" >> $WG_CONFIG echo "[Interface] PrivateKey = $CLIENT_PRIVKEY Address = $CLIENT_ADDRESS/$PRIVATE_SUBNET_MASK DNS = $CLIENT_DNS [Peer] PublicKey = $SERVER_PUBKEY AllowedIPs = 0.0.0.0/0, ::/0 Endpoint = $SERVER_ENDPOINT PersistentKeepalive = 25" > $HOME/$CLIENT_NAME-wg0.conf qrencode -t ansiutf8 -l L < $HOME/$CLIENT_NAME-wg0.conf ip address | grep -q wg0 && wg set wg0 peer "$CLIENT_PUBKEY" allowed-ips "$CLIENT_ADDRESS/32" echo "Client added, new configuration file --> $HOME/$CLIENT_NAME-wg0.conf" fi
<reponame>upasanachatterjee/zally-edits<filename>server/src/main/java/de/zalando/zally/dto/SeverityBinder.java package de.zalando.zally.dto; import de.zalando.zally.rule.api.Severity; import org.springframework.util.StringUtils; import java.beans.PropertyEditorSupport; public class SeverityBinder extends PropertyEditorSupport { @Override public void setAsText(final String text) throws IllegalArgumentException { final Severity value = StringUtils.hasText(text) ? Severity.valueOf(text.toUpperCase()) : null; setValue(value); } }
import requests # API key api_key = '<API key>' # URL for the API url = "http://api.openweathermap.org/data/2.5/forecast" # Parameters parameters = { 'id': '3117732', # Madrid 'APPID': api_key, 'units': 'metric', 'cnt': 5 } # Make the request response = requests.get(url, params=parameters) # Get the response data data = response.json() # Calculate the average temperature total_temp = 0 for day in data['list']: total_temp += day['main']['temp'] average_temp = total_temp / len(data['list']) print(f'Average temperature: {average_temp:.2f} C')
#!/bin/bash -f #********************************************************************************************************* # Vivado (TM) v2020.1 (64-bit) # # Filename : fifo_generator_0.sh # Simulator : Aldec Active-HDL Simulator # Description : Simulation script for compiling, elaborating and verifying the project source files. # The script will automatically create the design libraries sub-directories in the run # directory, add the library logical mappings in the simulator setup file, create default # 'do/prj' file, execute compilation, elaboration and simulation steps. # # Generated by Vivado on Sat May 15 20:18:08 -0400 2021 # SW Build 2902540 on Wed May 27 19:54:49 MDT 2020 # # Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. # # usage: fifo_generator_0.sh [-help] # usage: fifo_generator_0.sh [-lib_map_path] # usage: fifo_generator_0.sh [-noclean_files] # usage: fifo_generator_0.sh [-reset_run] # # Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the # 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the # Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch # that points to these libraries and rerun export_simulation. For more information about this switch please # type 'export_simulation -help' in the Tcl shell. # # You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this # script with the compiled library directory path or specify this path with the '-lib_map_path' switch when # executing this script. Please type 'fifo_generator_0.sh -help' for more information. # # Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)' # #********************************************************************************************************* # Script info echo -e "fifo_generator_0.sh - Script generated by export_simulation (Vivado v2020.1 (64-bit)-id)\n" # Main steps run() { check_args $# $1 setup $1 $2 compile simulate } # RUN_STEP: <compile> compile() { # Compile design files source compile.do 2>&1 | tee -a compile.log } # RUN_STEP: <simulate> simulate() { runvsimsa -l simulate.log -do "do {simulate.do}" } # STEP: setup setup() { case $1 in "-lib_map_path" ) if [[ ($2 == "") ]]; then echo -e "ERROR: Simulation library directory path not specified (type \"./fifo_generator_0.sh -help\" for more information)\n" exit 1 fi map_setup_file $2 ;; "-reset_run" ) reset_run echo -e "INFO: Simulation run files deleted.\n" exit 0 ;; "-noclean_files" ) # do not remove previous data ;; * ) map_setup_file $2 esac # Add any setup/initialization commands here:- # <user specific commands> } # Map library.cfg file map_setup_file() { file="library.cfg" if [[ ($1 != "") ]]; then lib_map_path="$1" else lib_map_path="C:/Users/Aleksa/Documents/FPGA_Dev/Artix7_PCIe/DDR3_Optimization/dso_top_23256/dso_top_23256.cache/compile_simlib/activehdl" fi if [[ ($lib_map_path != "") ]]; then src_file="$lib_map_path/$file" if [[ -e $src_file ]]; then vmap -link $lib_map_path fi fi } # Delete generated data from the previous run reset_run() { files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl) for (( i=0; i<${#files_to_remove[*]}; i++ )); do file="${files_to_remove[i]}" if [[ -e $file ]]; then rm -rf $file fi done } # Check command line arguments check_args() { if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then echo -e "ERROR: Unknown option specified '$2' (type \"./fifo_generator_0.sh -help\" for more information)\n" exit 1 fi if [[ ($2 == "-help" || $2 == "-h") ]]; then usage fi } # Script usage usage() { msg="Usage: fifo_generator_0.sh [-help]\n\ Usage: fifo_generator_0.sh [-lib_map_path]\n\ Usage: fifo_generator_0.sh [-reset_run]\n\ Usage: fifo_generator_0.sh [-noclean_files]\n\n\ [-help] -- Print help information for this script\n\n\ [-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\ using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\ [-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\ from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\ -noclean_files switch.\n\n\ [-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n" echo -e $msg exit 1 } # Launch script run $1 $2
import Document, { Head, Main, NextScript } from "next/document"; import flush from "styled-jsx/server"; import { ServerStyleSheet } from "styled-components"; import Helmet from "react-helmet"; import configs from "configs"; export default class ReactConf extends Document { static async getInitialProps(...args) { const documentProps = await super.getInitialProps(...args); const styles = flush(); return { ...documentProps, helmet: Helmet.renderStatic(), styles }; } // should render on <html> get helmetHtmlAttrComponents() { return this.props.helmet.htmlAttributes.toComponent(); } // should render on <body> get helmetBodyAttrComponents() { return this.props.helmet.bodyAttributes.toComponent(); } // should render on <head> get helmetHeadComponents() { return Object.keys(this.props.helmet) .filter(el => el !== "htmlAttributes" && el !== "bodyAttributes") .map(el => this.props.helmet[el].toComponent()); } get helmetJsx() { return ( <Helmet htmlAttributes={{ lang: "en", dir: "ltr" }} title="ReactConf" meta={[ { name: "viewport", content: "width=device-width, initial-scale=1", }, ]} /> ); } render() { const sheet = new ServerStyleSheet(); const main = sheet.collectStyles(<Main />); const styleTags = sheet.getStyleElement(); return ( <html> <Head> {this.helmetHeadComponents} <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer',"${configs.analyticsKey}");`, }} /> <noscript dangerouslySetInnerHTML={{ __html: ` <iframe src="https://www.googletagmanager.com/ns.html?id=${ configs.analyticsKey }" height="0" width="0" style={{display:'none",visibility:"hidden"}} > </iframe> `, }} /> <style>{`body { margin: 0 }`}</style> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" /> <link rel="stylesheet" href="/static/css/font-awesome.css" /> <link rel="shortcut icon" href="/static/image/icon/favicon.ico" type="image/x-icon" /> <meta charset="utf-8" /> <title> ReactConf 2019 | Javascript & ReactJS Conference </title> <meta name="google-site-verification" content={`${configs.googleWebmaster}`} /> <meta name="robots" content="index, follow" /> <meta name="description" content="First Javascript & ReactJS Conference in IRAN, Algorithm, Data Structure,ReactJS,NodeJS,Graphql and etc…" /> <meta name="image" content="/static/image/reactconf.jpg" /> <meta itemprop="name" content="React Conf | Javascript & ReactJS Conference" /> <meta itemprop="description" content="First Javascript & ReactJS Conference in IRAN, Algorithm, Data Structure,ReactJS,NodeJS,Graphql and etc…" /> <meta itemprop="image" content="/static/image/reactconf.jpg" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:title" content="React Conf | Javascript & ReactJS Conference" /> <meta name="twitter:description" content="First Javascript & ReactJS Conference in IRAN, Algorithm, Data Structure,ReactJS,NodeJS,Graphql and etc…" /> <meta name="twitter:site" content="@reactconf_ir" /> <meta name="twitter:image:src" content="/static/image/icon/apple-touch-icon.png" /> <meta name="og:title" content="React Conf | Javascript & ReactJS Conference" /> <meta name="og:description" content="First Javascript & ReactJS Conference in IRAN, Algorithm, Data Structure,ReactJS,NodeJS,Graphql and etc…" /> <meta name="og:image" content="/static/image/reactconf.jpg" /> <meta name="og:url" content="http://reactconf.ir" /> <meta name="og:site_name" content="React Conf | Javascript & ReactJS Conference" /> <meta name="og:locale" content="en_US" /> <meta name="og:type" content="website" /> <link rel="apple-touch-icon" href="/static/image/icon/apple-touch-icon.png" /> <link rel="apple-touch-icon" sizes="57x57" href="/static/image/icon/apple-touch-icon-57x57.png" /> <link rel="apple-touch-icon" sizes="72x72" href="/static/image/icon/apple-touch-icon-72x72.png" /> <link rel="apple-touch-icon" sizes="76x76" href="/static/image/icon/apple-touch-icon-76x76.png" /> <link rel="apple-touch-icon" sizes="114x114" href="/static/image/icon/apple-touch-icon-114x114.png" /> <link rel="apple-touch-icon" sizes="120x120" href="/static/image/icon/apple-touch-icon-120x120.png" /> <link rel="apple-touch-icon" sizes="144x144" href="/static/image/icon/apple-touch-icon-144x144.png" /> <link rel="apple-touch-icon" sizes="152x152" href="/static/image/icon/apple-touch-icon-152x152.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/static/image/icon/apple-touch-icon-180x180.png" /> {styleTags} {this.helmetJsx} </Head> <body {...this.helmetBodyAttrComponents}> {main} <NextScript /> </body> </html> ); } }
/*! * locale * Copyright(c) 2015 <NAME> * MIT Licensed */ 'use strict'; /** * Module dependences. */ var delegate = require('delegates'); /** * Expose * * @param {Object} app * @param {String} key - locale key name. * * @returns {Object} app */ module.exports = function(app, key) { key = key || 'locale'; var request = app.request; // From query, `locale=en` Object.defineProperty(request, 'getLocaleFromQuery', { value: function() { return this.query[key]; } }); // From query, `locale=en` Object.defineProperty(request, 'getLocaleFromSubdomain', { value: function() { return this.subdomains.pop(); } }); // From accept-language, `Accept-Language: zh-CN` Object.defineProperty(request, 'getLocaleFromHeader', { value: function(multi) { var accept = this.acceptsLanguages() || '', reg = /(^|,\s*)([a-z-]+)/gi, locales = [], match; while ((match = reg.exec(accept))) { locales.push(match[2]) if (!multi && locales.length) { break; } } return multi ? locales : locales[0]; } }); // From cookie, `locale=zh-CN` Object.defineProperty(request, 'getLocaleFromCookie', { value: function() { return this.ctx.cookies.get(key); } }); // From URL, `http://koajs.com/en` Object.defineProperty(request, 'getLocaleFromUrl', { value: function(options) { var segments = this.path.substring(1).split('/'); return segments[options && options.offset || 0]; } }); // From The Latest Domain, `http://koajs.com`, `http://kojs.cn` Object.defineProperty(request, 'getLocaleFromTLD', { value: function() { return this.hostname.split('.').pop(); } }); /** * Delegate to this.ctx. */ delegate(app.context, 'request') .method('getLocaleFromQuery') .method('getLocaleFromSubdomain') .method('getLocaleFromHeader') .method('getLocaleFromCookie') .method('getLocaleFromUrl') .method('getLocaleFromTLD'); return app; };
from typing import List, Tuple def count_lenses(lens_phenomena: List[int]) -> Tuple[int, int]: positive_count = lens_phenomena.count(1) negative_count = lens_phenomena.count(0) return (positive_count, negative_count)
<filename>app/src/main/java/com/ulfy/master/ui/base/ContentView.java package com.ulfy.master.ui.base; import android.content.Context; import android.util.AttributeSet; import android.widget.FrameLayout; import com.ulfy.android.system.base.UlfyBaseView; import com.ulfy.android.ui_injection.Layout; import com.ulfy.android.ui_injection.ViewById; import com.ulfy.master.R; @Layout(id = R.layout.view_content) public abstract class ContentView extends UlfyBaseView { public ContentView(Context context) { super(context); } public ContentView(Context context, AttributeSet attrs) { super(context, attrs); } /* 声明为protected类型,便于子类直接访问 */ @ViewById(id = R.id.contentFL) protected FrameLayout contentFL; }
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" elif [ -L "${binary}" ]; then echo "Destination binary is symlinked..." dirname="$(dirname "${binary}")" binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Copies the bcsymbolmap files of a vendored framework install_bcsymbolmap() { local bcsymbolmap_path="$1" local destination="${BUILT_PRODUCTS_DIR}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/LTxConfig/LTxConfig.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/LTxConfig/LTxConfig.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
impl iter::Iterator for Fib { type Item = u64; fn next(&mut self) -> Option<u64> { let result = self.one_back + self.current; self.one_back = self.current; self.current = result; Some(result) } }
#!/usr/bin/env bash set -euxo pipefail TARGET="nixos@108.61.117.242" STATIC_DIR="${PWD}/{{cookiecutter.project_slug}}/static_all" NIX_SSHOPTS="-o IdentityFile=~/.ssh/id_rsa_nixos" if [ ! -d "$STATIC_DIR" ]; then nix-shell --pure --run "source .env; ./manage.py collectstatic --no-input" fi PROFILE_PATH="$(nix-build --no-out-link -A system ./nix/prod-system.nix)" nix-copy-closure --to --use-substitutes $TARGET $PROFILE_PATH ssh $TARGET -- "sudo nix-env --profile /nix/var/nix/profiles/system --set $PROFILE_PATH && sudo /nix/var/nix/profiles/system/bin/switch-to-configuration switch"
package com.siyuan.enjoyreading.widget; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import com.androidapp.utils.DensityUtil; import com.androidapp.utils.ImageLoaderUtils; import com.androidapp.widget.AppRoundImageView; import com.siyuan.enjoyreading.R; import java.io.File; import java.util.List; /** * des:显示1~N张图片的View * Created by xsf * on 2016.07.11:11 */ public class MultiImageView extends LinearLayout { public static int MAX_WIDTH = 0; // 照片的Url列表 private List<String> imagesList; /** * 长度 单位为Pixel **/ private int pxOneMaxWandH; // 单张图最大允许宽高 private int pxTwoH; // 单张图最大允许宽高 private int pxThreeH = 0;// 多张图的宽高 private int pxImagePadding = 0; private int MAX_PER_ROW_COUNT = 3;// 每行显示最大数 private LayoutParams oneParams; private LayoutParams moreTwo, threeParams; private OnItemClickListener mOnItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener) { mOnItemClickListener = onItemClickListener; } public MultiImageView(Context context) { super(context); pxImagePadding = DensityUtil.dip2px(getContext(), 3);// 图片间的间距 } public MultiImageView(Context context, AttributeSet attrs) { super(context, attrs); pxImagePadding = DensityUtil.dip2px(getContext(), 3);// 图片间的间距 } public void setList(List<String> lists) throws IllegalArgumentException { if (lists == null) { throw new IllegalArgumentException("imageList is null..."); } imagesList = lists; if (MAX_WIDTH > 0) { pxThreeH = (MAX_WIDTH - pxImagePadding * 3) / 3; //解决右侧图片和内容对不齐问题 pxTwoH = (MAX_WIDTH - pxImagePadding * 2) / 2; //解决右侧图片和内容对不齐问题 pxOneMaxWandH = MAX_WIDTH * 2 / 3; initImageLayoutParams(); } initView(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (MAX_WIDTH == 0) { int width = measureWidth(widthMeasureSpec); if (width > 0) { MAX_WIDTH = width; if (imagesList != null && imagesList.size() > 0) { setList(imagesList); } } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** * Determines the width of this view * * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text // result = (int) mTextPaint.measureText(mText) + getPaddingLeft() // + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by // measureSpec result = Math.min(result, specSize); } } return result; } private void initImageLayoutParams() { int wrap = LayoutParams.WRAP_CONTENT; int match = LayoutParams.MATCH_PARENT; oneParams = new LayoutParams(match, wrap); threeParams = new LayoutParams(pxThreeH, pxThreeH); threeParams.setMargins(pxImagePadding, 0, pxImagePadding, 0); moreTwo = new LayoutParams(pxTwoH, pxTwoH); moreTwo.setMargins(pxImagePadding, 0, pxImagePadding, 0); } // 根据imageView的数量初始化不同的View布局,还要为每一个View作点击效果 private void initView() { this.setOrientation(VERTICAL); this.removeAllViews(); if (MAX_WIDTH == 0) { //为了触发onMeasure()来测量MultiImageView的最大宽度,MultiImageView的宽设置为match_parent addView(new View(getContext())); return; } if (imagesList == null || imagesList.size() == 0) { return; } if (imagesList.size() == 1) { addView(createImageView(0, 1)); } else { int allCount = imagesList.size(); if (allCount == 4 ) { MAX_PER_ROW_COUNT = 2; } else { MAX_PER_ROW_COUNT = 3; } int rowCount = allCount / MAX_PER_ROW_COUNT + (allCount % MAX_PER_ROW_COUNT > 0 ? 1 : 0);// 行数 for (int rowCursor = 0; rowCursor < rowCount; rowCursor++) { LinearLayout rowLayout = new LinearLayout(getContext()); rowLayout.setOrientation(LinearLayout.HORIZONTAL); rowLayout.setLayoutParams(oneParams); if (rowCursor != 0) { rowLayout.setPadding(0, pxImagePadding, 0, 0); } int columnCount = allCount % MAX_PER_ROW_COUNT == 0 ? MAX_PER_ROW_COUNT : allCount % MAX_PER_ROW_COUNT;//每行的列数 if (rowCursor != rowCount - 1) { columnCount = MAX_PER_ROW_COUNT; } addView(rowLayout); int rowOffset = rowCursor * MAX_PER_ROW_COUNT;// 行偏移 for (int columnCursor = 0; columnCursor < columnCount; columnCursor++) { int position = columnCursor + rowOffset; rowLayout.addView(createImageView(position, MAX_PER_ROW_COUNT)); } } } } private ImageView createImageView(int position, int column) { String url = imagesList.get(position); AppRoundImageView imageView = new AppRoundImageView(getContext()); if (column == 1) { imageView.setAdjustViewBounds(true); imageView.setScaleType(ScaleType.CENTER_CROP); imageView.setMaxHeight(pxOneMaxWandH); imageView.setLayoutParams(oneParams); } else if (column == 2) { imageView.setScaleType(ScaleType.CENTER_CROP); imageView.setLayoutParams(moreTwo); } else { imageView.setScaleType(ScaleType.CENTER_CROP); imageView.setLayoutParams(threeParams); } imageView.setTag(R.string.zone_img_position, position); imageView.setId(url.hashCode()); imageView.setOnClickListener(mImageViewOnClickListener); ImageLoaderUtils.display(getContext(), imageView, getImageUrl(url)); return imageView; } // 图片点击事件 private OnClickListener mImageViewOnClickListener = new OnClickListener() { @Override public void onClick(View view) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(view, (Integer) view.getTag(R.string.zone_img_position)); } } }; public interface OnItemClickListener { void onItemClick(View view, int position); } private static String BASE_PHOTO_URL = ""; public static String getImageUrl(String url) { if (!TextUtils.isEmpty(url)) { if (url.contains("http") || new File(url).isFile()) { return url; } else { return BASE_PHOTO_URL + url; } } else { return ""; } } }
const child_process = require('child_process'); const Web3 = require('web3'); const HDWalletProvider = require("truffle-hdwallet-provider"); var web3 = new Web3(); var environment = process.env.CRUCIBLE_ENV || 'development'; var provider; if (environment !== 'development') { var providerUrl; if (environment === 'production') { providerUrl = 'https://mainnet.infura.io/'; } else if (environment === 'staging') { providerUrl = 'https://rinkeby.infura.io/'; } else if (environment === 'ropsten') { providerUrl = 'https://ropsten.infura.io/'; } else if (environment === 'kovan') { providerUrl = 'https://kovan.infura.io/'; } else { providerUrl = 'https://rinkeby.infura.io/'; } // unseal the vault child_process.execSync('./scripts/vault_unseal.js'); // Get our mnemonic and create an hdwallet var mnemonic = child_process.execSync( './scripts/vault_get_mnemonic.js' ).toString().replace(/\n/, ''); provider = new HDWalletProvider(mnemonic, providerUrl); } module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id }, staging: { provider: provider, gasPrice: web3.toWei('100', 'gwei'), network_id: '4', // Official rinkeby network id }, production: { provider: provider, gasPrice: web3.toWei('10', 'gwei'), network_id: "1", // Main Ethereum Network }, ropsten: { provider: provider, gasPrice: web3.toWei('10', 'gwei'), network_id: '3', // Official ropsten network id }, kovan: { provider: provider, gasPrice: web3.toWei('10', 'gwei'), network_id: '42', // Official kovan network id }, }, rpc: { // Use the default host and port host: "localhost", port: 8545, network_id: "*" // Match any network id } };