code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/** * ----------------------------------------------------------------------------- * @package smartVISU * @author Martin Gleiß * @copyright 2012 - 2015 * @license GPL [http://www.gnu.de] * ----------------------------------------------------------------------------- */ /** * Class for controlling all communication with a connected system. There are * simple I/O functions, and complex functions for real-time values. */ var io = { // the adress adress: '', // the port port: '', // ----------------------------------------------------------------------------- // P U B L I C F U N C T I O N S // ----------------------------------------------------------------------------- /** * Does a read-request and adds the result to the buffer * * @param the item */ read: function (item) { }, /** * Does a write-request with a value * * @param the item * @param the value */ write: function (item, val) { io.send({'cmd': 'item', 'id': item, 'val': val}); widget.update(item, val); }, /** * Trigger a logic * * @param the logic * @param the value */ trigger: function (name, val) { io.send({'cmd': 'logic', 'name': name, 'val': val}); }, /** * Initializion of the driver * * @param the ip or url to the system (optional) * @param the port on which the connection should be made (optional) */ init: function (address, port) { io.address = address; io.port = port; io.open(); }, /** * Lets the driver work */ run: function (realtime) { // old items widget.refresh(); // new items io.monitor(); }, // ----------------------------------------------------------------------------- // C O M M U N I C A T I O N F U N C T I O N S // ----------------------------------------------------------------------------- // The functions in this paragraph may be changed. They are all private and are // only be called from the public functions above. You may add or delete some // to fit your requirements and your connected system. /** * This driver version */ version: 3, /** * This driver uses a websocket */ socket: false, /** * Opens the connection and add some handlers */ open: function () { io.socket = new WebSocket('ws://' + io.address + ':' + io.port + '/'); io.socket.onopen = function () { io.send({'cmd': 'proto', 'ver': io.version}); io.monitor(); }; io.socket.onmessage = function (event) { var item, val; var data = JSON.parse(event.data); // DEBUG: console.log("[io.smarthome.py] receiving data: ", event.data); switch (data.cmd) { case 'item': for (var i = 0; i < data.items.length; i++) { item = data.items[i][0]; val = data.items[i][1]; /* not supported: if (data.items[i].length > 2) { data.p[i][2] options for visu }; */ // convert binary if (val === false) { val = 0; } if (val === true) { val = 1; } widget.update(item, val); } break; case 'series': data.sid = data.sid.substr(0, data.sid.length); widget.update(data.sid.replace(/\|/g, '\.'), data.series); break; case 'dialog': notify.info(data.header, data.content); break; case 'log': if (data.init) { widget.update(data.name, data.log); } else { var log = widget.get(data.name); // only a reference for (var i = 0; i < data.log.length; i++) { log.unshift(data.log[i]); if (log.length >= 50) { log.pop(); } } widget.update(data.name); } break; case 'proto': var proto = parseInt(data.ver); if (proto != io.version) { notify.warning('Driver: smarthome.py', 'Protocol mismatch<br />smartVISU driver is: v' + io.version + '<br />SmartHome.py is: v' + proto + '<br /><br /> Update the system!'); } break; case 'url': $.mobile.changePage(data.url); break; } }; io.socket.onerror = function (error) { notify.error('Driver: smarthome.py', 'Could not connect to smarthome.py server!<br /> Websocket error ' + error.data + '.'); }; io.socket.onclose = function () { notify.debug('Driver: smarthome.py', 'Connection closed to smarthome.py server!'); }; }, /** * Sends data to the connected system */ send: function (data) { if (io.socket.readyState == 1) { io.socket.send(unescape(encodeURIComponent(JSON.stringify(data)))); // DEBUG: console.log('[io.smarthome.py] sending data: ', JSON.stringify(data)); } }, /** * Monitors the items */ monitor: function () { if (widget.listeners().length) { // items io.send({'cmd': 'monitor', 'items': widget.listeners()}); } // plot (avg, min, max, on) var unique = Array(); widget.plot().each(function (idx) { var items = widget.explode($(this).attr('data-item')); for (var i = 0; i < items.length; i++) { var pt = items[i].split('.'); if (!unique[items[i]] && !widget.get(items[i]) && (pt instanceof Array) && widget.checkseries(items[i])) { var item = items[i].substr(0, items[i].length - 4 - pt[pt.length - 4].length - pt[pt.length - 3].length - pt[pt.length - 2].length - pt[pt.length - 1].length); io.send({'cmd': 'series', 'item': item, 'series': pt[pt.length - 4], 'start': pt[pt.length - 3], 'count': pt[pt.length - 1]}); unique[items[i]] = 1; } } }); // log widget.log().each(function (idx) { io.send({'cmd': 'log', 'name': $(this).attr('data-item'), 'max': $(this).attr('data-count')}); }); }, /** * Closes the connection */ close: function () { console.log("[io.smarthome.py] close connection"); if (io.socket.readyState > 0) { io.socket.close(); } io.socket = null; } };
lbernau/smartVISU-deprecated
driver/io_smarthome.py.js
JavaScript
gpl-3.0
5,820
{ aboutMessage: "Über ProjecQtOr …", aboutMessageLocale: "Lokal", aboutMessageWebsite: "Webseite", AccessProfile: "Zugriffsprofile", accessProfileGlobalCreator: "Ersteller+", accessProfileGlobalManager: "Manager+", accessProfileGlobalReader: "Leser+", accessProfileGlobalUpdater: "Änderer+", accessProfileNoAccess: "Kein Zugriff", accessProfileRestrictedCreator: "Ersteller", accessProfileRestrictedManager: "Manager", accessProfileRestrictedReader: "Leser", accessProfileRestrictedUpdater: "Änderer", accessReadOwnOnly: "Leser eigene", accessScopeAll: "Alle Elemente aller Projekte", accessScopeNo: "Kein Elemente", accessScopeOwn: "Eigene Elemente", accessScopeProject: "Elemente eigener Projekte", accessScopeResp: "Elemente für die er verantwortlich ist", Action: "Aktion", ActionType: "Aktionstyp", activeConnections: "Aktiver Status", Activity: "Aktivität", ActivityPrice: "Preis der Aktivität", ActivityType: "Aktivitätstyp", actualDueDate: "Berücksichtige anfängliches Endedatum", actualDueDateTime: "Berücksichtige anfängliches Endedatum/-zeit", addAffectation: "neue Zuordnung hinzufügen", addApprover: "Genehmiger hinzufügen", addAssignment: "Zuordnung hinzufügen", addAttachement: "Anhang hinzufügen", addDependency: "Abhängigkeit hinzufügen", addDependencyPredecessor: "Vorgänger hinzufügen", addDependencySuccessor: "Nachfolger hinzufügen", addDocumentVersion: "neue Version hinzufügen", addExpenseDetail: "Aufwandsdetail hinzufügen", addFilterClause: "Filterkriterium hinzufügen", addFilterClauseTitle: "Filterregel hinzufügen", addHyperlink: "Hyperlink für Datei oder Web-Seite hinzufügen", addLine: "Zeile hinzufügen", addLink: "Elementverknüpfung hinzufügen", addNote: "Notiz hinzufügen", addOrigin: "Ursprung hinzufügen", addPhoto: "Foto hinzufügen", addResourceCost: "Ressourcekosten hinzufügen", addTestCaseRun: "Testfall zu Testplan hinzufügen", addVersionProject: "Verbindung zwischen Version und Projekt", adminCronCheckDates: "Verzögerung für die Erzeugung von Alarmen = ${1} Sekunden", adminCronCheckEmails: "Emails Eingang Verzögerung = ${1} Sekunden", adminCronCheckImport: "Verzögerungen von automatischen Importen = ${1} Sekunden", adminCronSleepTime: "Generelle Cron Ruhezeit = ${1} Sekunden", advancedFilter: "Erweiterer Filter", Affectation: "Ressourcenzuordnung", affectTeamMembers: "Team zuweisen auf Projekt ", after: "dahinter", Alert: "Alarm", ALERT: "Alarm", alertChooseOneAtLeast: "Mindestens ein Element wählen", alertCronStatus: "Alarm Erstellung", alertInvalidForm: "Einige Felder enthalten ungültige Daten. <br/>Bitte erst korrigieren.", alertNoNewAssignment: "Keine Zuordnung auf ungenutztes Element möglich.", alertOngoingChange: "Aktuelle Änderungen nicht gesichert.<br/>Bitte vorher sichern oder abbrechen.", alertOngoingQuery: "Abfrage läuft<br/>Bitte warten", alertQuitOngoingChange: "Aktuelle Änderungen nicht gesichert.\nWollen Sie wirklich ProjecQtOr beenden?", alertValue: "Alarm Wert", all: "Alle", allProjects: "Alle Projekte", allUsers: "Alle Nutzer", alsoDeleteAttachement: "ACHTUNG, diese Aktion wird auch die ${1} verbundene(n) Anhangdatei(en) löschen.", always: "immer", amongst: "über", Anomaly: "Störung", anyChange: "beliebige Änderung", applicationStatus: "Status der Applikation ", applicationStatusClosed: "geschlossen", applicationStatusOpen: "offen", applicationTitle: "ProjeQtOr", approved: "genehmigt", approveNow: "jetzt genehmigen", approver: "Genehmiger", Approver: "Genehmiger", April: "April", Assignment: "Zuordnung", assignmentAdd: "Zuordnung hinzufügt", assignmentChange: "Zuordnung geändert", assignmentEditRight: "Zuweisungen bearbeiten", assignmentViewRight: "Zuweisungen anzeigen", Attachement: "Anhang", attachmentAdd: "Anhänge hinzufügen", attributeNotSelected: "Werte nicht gewählt", Audit: "Verbindung", August: "August", before: "davor", bigExportQuestion: "Der Export hat ${1} Zeilen. Weitermachen?", Bill: "Rechnung", billingTypeE: "gemäß Konditionen", billingTypeM: "manuelle Rechnungsstellung", billingTypeN: "nicht abgerechnet", billingTypeP: "nach gedeckelter Produktionszeit", billingTypeR: "nach erstellter Arbeit", BillLine: "Rechnungszeilen", BillType: "Rechnungstyp", blocked: "gesperrt", blockedTestCaseRun: "Testfall als gesperrt markieren", Browser: "Navigator", buttonBrowse: "Suchen …", buttonCancel: "Abbruch", buttonChangePassword: "Passwort ändern", buttonClear: "Löschen", buttonCollapse: "Zuklappen aller Gruppen", buttonCopy: "Kopiere den aktuellen ${1}", buttonDefault: "Standardwert", buttonDelete: "Lösche den aktuellen ${1}", buttonDeleteMultiple: "Lösche alle gewählten Elemente", buttonExpand: "Aufklappen aller Gruppen", buttonHideList: "Liste ausblenden", buttonHideMenu: "Menü ausblenden", buttonImportData: "Datenimport", buttonMail: "Email Details von ${1}", buttonMultiUpdate: "Mehrfachaktualisierung", buttonNew: "Erstelle neu ${1}", buttonNo: "Nein", buttonOK: "OK", buttonPlan: "Berechne geplante Aktivitäten", buttonPrint: "Drucke den aktuellen ${1}", buttonQuitMultiple: "Mehrfachaktualisierung verlassen", buttonRedoItem: "Gehe vorwärts", buttonRefresh: "Anzeige des aktuellen ${1} erneuern", buttonRefreshList: "Liste aktualisieren", buttonReset: "Rücksetzen", buttonSave: "Sichern der Änderung des aktuellen ${1} ([CTRL]+S)", buttonSaveImputation: "Sichern der Arbeitsauftrag ${1}", buttonSaveMultiple: "Mehrfachaktualisierung sichern", buttonSaveParameter: "Sichern der Parameter", buttonSaveParameters: "Sichern Parameter", buttonSelectAll: "Alle Elemente auswahlen", buttonSelectFiles: "Wähle Dateien …", buttonShowList: "Liste anzeigen", buttonShowMenu: "Menü anzeigen", buttonStandardMode: "Modus Standardanzeige", buttonSwitchedMode: "Modus Umschaltanzeige", buttonUndo: "Änderung rückgängig machen für aktuellen ${1}", buttonUndoImputation: "Änderung rückgängig machen für Arbeitsauftrag ${1}", buttonUndoItem: "Gehe zurück", buttonUnselectAll: "Alle Auswahlen aufheben", buttonYes: "Ja", byte: "Byte", byteLetter: "B", Calendar: "Kalender", CalendarDefinition: "Kalender", cancelled: "abgebrochen", cannotDeleteBilledTerm: "abgerechnete B", cannotGoto: "Kann nicht zu diesem Element gehen<br/>Bitte wählen Sie erst aus der ersten Liste auswählen.", changeActualDueDate: "Ändere geplantes Endedatum zu", changeActualDueDateTime: "Ändere aktuelles Endedatum/ -zeit zu", changeActualEndDate: "Ändere aktuelles Endedatum zu", changeInitialDueDate: "Ändere ursprüngl. Endedatum zu", changeInitialDueDateTime: "Ändere ursprüngl. Endedatum/ -zeit zu", changeInitialEndDate: "Ändere ursprüngl. Endedatum zu", changePlanningMode: "Ändere Planungsmodus zu", changeValidatedEndDate: "Ändere bestätigtes Endedatum zu", changeValidatedStartDate: "Ändere bestätigtes Startdatum zu", checkAsList: "Wähle Spalten für Anzeige", Checklist: "Checkliste", checklistAccess: "Zugriff auf Checklisten", ChecklistDefinition: "Checkliste", ChecklistDefinitionLine: "Checklistenzeilen", checkUncheckAll: "wählen / abwählen", chooseColumnExport: "Wähle Spalten für Export", chronological: "zeitlich", Client: "Kunde", ClientType: "Kundentyp", close: "Schließen", closeAlerts: "Schließe Alarme", closed: "abgeschlossen", closedMessage: "Meldung wenn Applikation im Wartungsmodus / Offline.", closedSinceMore: "schließe bei mehr als", closeEmails: "Schließe Mails", codDesignation: "Bezeichnung", colAccountable: "abrechenbar", colActionnee: "Akteur", colActualDueDate: "Zieldatum geplant", colActualDueDateTime: "Zieldatum aktuell", colActualEndDate: "Endedatum geplant", colAdd: "Änderung", colAddAmount: "Änderung Betrag", colAdditionalInfo: "zusätzl. Info", colAddNote: "(öffentliche) Notiz hinzufügen", colAddPricePerDayAmount: "Änderung Preis/Tag", colAddress: "Adresse", colAddToDescription: "Beschreibung hinzufügen", colAddToResult: "Ergebnis hinzufügen", colAddWork: "Änderung Arbeit", colAlert: "Alarm", colAlertDateTime: "Erinnerungsdatum", colAlertInitialDateTime: "Erstelle Datum", colAlertReadDateTime: "Lesedatum", colAlertReceiver: "Empfänger des Alarms", colAllowDuplicate: "erlaube Duplikat", colAllowDuplicateTestInSession: "erlaube Testfall Duplikat in Testplan", colAmount: "Betrag", colApiKey: "API Schlüssel", colAssigned: "zugewiesen", colAssignedCost: "zugewiesene Kosten", colAssignedWork: "zugewiesene Arbeit", colAttendees: "Anwesende", colBank: "Bank", colBillable: "abrechenbar", colBillContact: "Rechnung Vertrag", colBillId: "Rechnungsnummer", colBillingType: "Rechnungstyp", colBrowser: "Browser", colBrowserVersion: "Browserversion", colCancelled: "abgebrochen", colCapacity: "Kapazität", colCategory: "Kategorie", colCause: "Ursache", colChangeIssuer: "Ändere ${1} zu", colChangeProject: "Ändere ${1} zu", colChangeRequestor: "Ändere ${1} zu", colChangeResponsible: "Ändere ${1} zu", colChangeStatus: "Ändere Status zu", colChangeTargetVersion: "Ändere Zielversion zu", colChangeType: "Ändere Type zu", colChoice: "Auswahlmöglichkeit", colChoices: "Auswahlmöglichkeiten", colCity: "Stadt", colClient: "Kunde", colClientCode: "Kundencode", colClientName: "Kundenname", colClosureDate: "Abschlussdatum", colClosureDateTime: "Abschlussdatum/-zeit", colCode: "Code", colColor: "Farbe", colColumn: "Daten", colComment: "Kommentare", colCommissionCost: "Auftrag", colCompanyNumber: "Firmennummer", colComplement: "Zubehör", colConnection: "Erster Zugriff", colContactName: "Kontaktname", colContractCode: "Vertragscode", colContractor: "Hauptlieferant", colCost: "Kosten", colCountBlocked: "gesperrt", colCountFailed: "fehlgeschlagen", colCountIssues: "Problem", colCountLinked: "verbunden", colCountPassed: "erfolgreich", colCountPlanned: "geplant", colCountry: "Land ", colCountTests: "Anzahl Testfälle", colCountTotal: "gesamt", colCreationDate: "Erstellungsdatum", colCreationDateTime: "Erstellungsdatum/-zeit", colCriticality: "Kritikalität", colCriticalityShort: "Krit.", colCurrentDocumentVersion: "letzte Version", colDate: "Datum", colDecisionAccountable: "verantwortlich", colDecisionDate: "Entscheidungsdatum", colDefaultType: "Standardtyp", colDependencyDelay: "Verzug (zu spät)", colDependencyDelayComment: "Tage zwischen Start Vorgänger und Nachfolger", colDescription: "Beschreibung", colDesignation: "Bezeichnung", colDetail: "Detail", colDisplayName: "Name anzeigen", colDocumentReference: "Dokumentenreferenz", colDone: "erledigt", colDoneDate: "Erledigungsdatum", colDoneDateTime: "Erledigungsdatum/-zeit", colDontReceiveTeamMails: "Kein Empfang von Team Mails", colDueDate: "Zieldatum", colDuplicateTicket: "Doppeltes Ticket", colDuration: "Dauer", colEisDate: "geplanter Produktivbetrieb", colElement: "Element", colEmail: "Mail-Adresse", colEnd: "Ende", colEndDate: "Endedatum", colEndTime: "Endezeit", colEstimatedEffort: "geschätzer Aufwand", colEstimatedWork: "Arbeit geschätzt", colExclusive: "nur Einzelauswahl zulassen", colExclusiveShort: "Einzel.", colExpected: "erwarteter Fortschritt", colExpectedProgress: "erwarteter Fortschritt", colExpectedResult: "erwartetes Ergebnis", colExpense: "Aufwand", colExpenseAssignedAmount: "Aufwände zuweisen", colExpenseLeftAmount: "verbleibende Aufwände", colExpensePlannedAmount: "Plan-Aufwände", colExpenseRealAmount: "Ist-Aufwände", colExpenseValidatedAmount: "genehmigte Aufwände", colExternalReference: "Externe Referenz", colFax: "FAX", colFile: "Datei", colFilter: "Filter", colFirstDay: "Erster Tag", colFixPlanning: "Feste Planung", colFormat: "Skala", colFullAmount: "Gesamtbetrag", colHandled: "bearbeitet", colHandledDate: "bearbeitet am", colHandledDateTime: "bearbeitet um", colHyperlink: "Hyperlink", colIbanBban: "Kontonummer (BBAN)", colIbanCountry: "Land (IBAN)", colIbanKey: "Schlüssel (IBAN)", colIcon: "Icon", colId: "ID", colIdAccessScopeCreate: "Berechtigung 'Erstellen'", colIdAccessScopeDelete: "Berechtigung 'Löschen'", colIdAccessScopeRead: "Berechtigung 'Lesen'", colIdAccessScopeUpdate: "Berechtigung 'Ändern'", colIdActionType: "Aktionstyp", colIdActivityPlanningMode: "Planungstyp", colIdActivityPrice: "Aktivitätspreis", colIdActivityType: "Aktivitätstyp", colIdAuthor: "Author", colIdBill: "Rechnung", colIdBillType: "Rechnungstyp", colIdCalendarDefinition: "Kalender", colIdClient: "Kunde", colIdClientType: "Kundentyp", colIdCommandType: "Auftragstyp", colIdContact: "Kontakt", colIdContext: "Kontext", colIdContext1: "Umfeld", colIdContext2: "Betriebssystem", colIdContext3: "Navigator", colIdContextType: "Kontexttyp", colIdCriticality: "Kritikalität", colIdDecisionType: "Entscheidungstyp", colIdDocumentDirectory: "Verzeichnis", colIdEfficiency: "Effizienz", colIdFeasibility: "Machbarkeit", colIdHealth: "Projektstatus", colIdIndicator: "Indikator", colIdle: "abgeschlossen", colIdleDate: "geschlossen am", colIdleDateTime: "geschlossen um", colIdLikelihood: "Wahrscheinlichkeit", colIdLocker: "gesperrt durch", colIdMailable: "Element geändert", colIdMeetingType: "Besprechungstyp", colIdMessageType: "Meldungstyp", colIdMilestonePlanningMode: "Planungstyp", colIdMilestoneType: "Meilensteintyp", colIdOverallProgress: "Gesamtfortschritt", colIdPeriodicity: "Häufigkeit", colIdPlanningMode: "Planungsmodus", colIdPriority: "Priorität", colIdPrivacy: "Datenschutz", colIdProduct: "Produkt", colIdProfile: "Profile", colIdProject: "Projekt", colIdQuality: "Qualitätslevel", colIdQuestionType: "Fragentyp", colIdQuotationType: "Angebotstyp", colIdRecipient: "Empfänger", colIdReferencable: "Element", colIdRequirement: "Übergeordnete Anforderung", colIdRequirementType: "Typ", colIdResource: "Ressource", colIdRole: "Funktion", colIdSeverity: "Auswirkung", colIdSponsor: "Sponsor", colIdStatus: "Status", colIdTeam: "Team", colIdTerm: "Bedingung", colIdTestCase: "Übergeordneter Testfall", colIdTestCaseType: "Typ", colIdTestSession: "Testlauf", colIdTestSessionPlanningMode: "Planungsmodus", colIdTestSessionType: "Typ", colIdTicketType: "Tickettyp", colIdTrend: "Trend", colIdUrgency: "Dringlichkeit", colIdUser: "Benutzer", colIdVersion: "Version", colIdVersioningType: "Versionstyp", colIdWorkflow: "Workflow", colImpact: "Auswirkung", colImportElementType: "Elementtyp für Import", colImportFileType: "Dateiformat für Import", colInitial: "anfänglich", colInitialAmount: "Initial Betrag", colInitialDueDate: "Zieldatum anfängl.", colInitialDueDateTime: "Zieldatum anfängl.", colInitialDuration: "Dauer anfängl.", colInitialEisDate: "Start des Produktivbetriebs", colInitialEndDate: "Enddatum anfängl.", colInitialPricePerDayAmount: "Initial Preis/Tag", colInitials: "Initialen", colInitialStartDate: "Startdatum anfängl.", colInitialWork: "Arbeit anfängl.", colIsBilled: "angekündigt", colIsContact: "ist ein Kontakt", colIsEis: "ist im Produktivbetrieb", colIsLdap: "kommt von LDAP", colIsOffDay: "Abwesenheitstag", colIsPeriodic: "periodisch", colIsRef: "Referenz", colIsResource: "ist eine Ressource", colIsSubProductOf: "Unterprojekt von", colIsSubProject: "Teilprojekt von", colIssuer: "Aussteller", colIssuerShort: "Ausst.", colIsUser: "ist ein Benutzer", colLastAccess: "Letzter Zugriff", colLate: "zu spät", colLatitude: "Breitengrad", colLeft: "verbleibend", colLeftCost: "verbleibende Kosten", colLeftWork: "verbleibende Arbeit", colLikelihood: "Wahrscheinlichkeit", colLikelihoodShort: "%", colLineCount: "Anzahl Zeilen", colLineNumber: "Position", colLink: "Link", colLinkActivity: "verbundene Aktivität", colListShowMilestone: "Meilensteine anzeigen", colLocation: "Standort", colLockCancelled: "Sperre abgebrochen", colLockDone: "Sperre 'erledigt'", colLocked: "gesperrt", colLockedDate: "gesperrt seit", colLockHandled: "Sperre 'bearbeitet'", colLockIdle: "Sperre 'abgeschlossen'", colLockTags: "Sperre 'Prüfungen'", colLongitude: "Längengrad", colMailBody: "Text des Mails", colMailDateTime: "gesendet am", colMailMessage: "Nachricht", colMailStatus: "Sendestatus", colMailTitle: "Titel des Mails", colMailTo: "Empfänger", colMailToAssigned: "Zugewiesene Ressource", colMailToContact: "Antragsteller", colMailToLeader: "Projektleiter", colMailToManager: "Projektmanager", colMailToOther: "andere", colMailToProject: "Projektteam", colMailToResource: "Verantwortlich", colMailToUser: "Aussteller", colMainRole: "Hauptfunktion", colManager: "Manager", colMandatoryDescription: "Beschreibung", colMandatoryResourceOnHandled: "verantwortlich", colMandatoryResultOnDone: "Ergebnis", colMeetingDate: "Besprechungsdatum", colMeetingEndTime: "Endezeit", colMeetingStartTime: "Startzeit", colMessage: "Meldung", colMinutes: "Protokoll", colMobile: "Handy", colName: "Name", colNameClient: "Kunde", colNewStatus: "neuer Status", colNextDocumentVersion: "neue Version", colNote: "Notiz", colNotPlannedWork: "[not planned work]", colNoWork: "Keine Arbeit", colNumBank: "Bankleitzahl", colNumCompte: "Kontonummer", colNumOffice: "Postfachnummer", colNumTax: "Steuernummer", colOfferValidityEndDate: "Gültigkeit des Angebots", colOperation: "Vorgang", colOpportunityImprovement: "Verbesserung erwartet", colOpportunityImprovementShort: "Verbessg.", colOpportunitySource: "Chancenquelle", colOrContact: "oder Kontakt", colOrigin: "Ursprung", colOriginalVersion: "Ursprungsversion", colOriginId: "Ursprungs-ID", colOriginType: "Ursprungstyp", colOrLink: "oder Link", colOrNotSet: "oder nicht gesetzt", colOrOtherEvent: "oder anderes Ereignis", colOrProduct: "oder Product", colOrUser: "oder Benutzer", colOtherAttendees: "Weitere Anwesende", colOtherVersions: "Andere Versionen", colParameters: "Parameter", colParentActivity: "übergeordnete Aktivität", colParentDirectory: "Oberverzeichnis", colParentTestSession: "Ursprungs-Session", colPassword: "Passwort", colPaymentDelay: "Zahlungsziel (in Tagen)", colPct: "%", colPeriod: "Zyklus", colPeriodicityEndDate: "Endedatum", colPeriodicityOpenDays: "Nur offene Tage", colPeriodicityStartDate: "Startdatum", colPeriodicityTimes: "Wiederholungen", colPeriodicOccurence: "Wiederholung", colPhone: "Telefon", colPhoto: "Foto", colPlanned: "geplant", colPlannedAmount: "Plan-Betrag", colPlannedAmount2: "Plan-Betrag", colPlannedCost: "Plan-Kosten", colPlannedDate: "Plan-Datum", colPlannedDate2: "Plan-Datum", colPlannedDueDate: "Plan-Zieldatum", colPlannedDuration: "Plan-Dauer", colPlannedEis: "Plan-Datum für Produktivbetrieb", colPlannedEisDate: "Plan-Datum für Produktivbetrieb", colPlannedEnd: "Plan-Endedatum", colPlannedEndDate: "Plan-Endedatum", colPlannedStartDate: "Plan-Startdatum", colPlannedWork: "Plan-Arbeit", colPlanning: "Planung", colPlanningActivity: "Zugewiesene Aktivität", colPlatform: "Plattform", colPredefinedNote: "vordefinierte Notiz", colPrerequisite: "Voraussetzung", colPreviousStartDate: "Vorheriges Startdatum", colPrice: "Preis", colPriceCost: "Preis der Aktivität", colPricePerDay: "Preis/Tag", colPriority: "Priorität", colPriorityShort: "Prio", colProductName: "Produktname", colProductVersion: "Version", colProfileCode: "Profilcode", colProgress: "Fortschritt", colProjectCode: "Projektcode", colProjectName: "Projektname", colProjectType: "Projekttyp", colQuantity: "Menge", colRate: "Anteil in %", colReadFlag: "lesen", colReal: "ist", colRealAmount: "Ist-Betrag", colRealCost: "Ist-Kosten", colRealDate: "Ist-Datum", colRealDuration: "Ist-Dauer", colRealEis: "Ist-Datum für Produktivbetrieb", colRealEisDate: "Ist-Datum für Produktivbetrieb", colRealEnd: "Ist-Endedatum", colRealEndDate: "Ist-Endedatum", colRealName: "Tatsächl. Name", colRealStartDate: "Ist-Startdatum", colRealWork: "Ist-Arbeit", colReceptionDateTime: "Übermittlungsdatum", colRecipient: "Empfänger", colReference: "Referenz", colReferenceDocumentVersion: "Referenz Version", colReffType: "Elementtyp", colRefId: "Element ID", colRefType: "Elementtyp", colReplier: "Antwortender", colReport: "Bericht", colRequestDisconnection: "Abmeldung erbeten", colRequested: "gefordert", colRequestor: "Antragsteller", colResource: "Ressourcen", colResourceCost: "Resourcekosten", colResourceName: "Ressourcenname", colResponse: "Antwort", colResponsible: "verantwortlich", colResponsibleShort: "verantw.", colResult: "Ergebnis", colResultImport: "Importergebnis", colRib: "Bank ID", colSendDate: "Sendedatum", colSender: "Sender", colSendMail: "sende Mail an", colSessionId: "Sitzungs ID", colSetCancelledStatus: "abgebrochen Status", colSetDoneStatus: "Status 'erledigt'", colSetHandledStatus: "Status 'bearbeitet'", colSetIdleStatus: "Status 'abgeschlossen'", colSeverity: "Auswirkung", colSeverityShort: "Schw.", colShowDetail: "Zeige Detail", colShowInFlash: "im Blitzbericht anzeigen", colSize: "Größe", colSortOrder: "Sortierung", colSortOrderShort: "Sortierung", colStart: "Start", colStartDate: "Startdatum", colStartTime: "Startzeit", colState: "Land", colStatusDateTime: "Datum", colStreet: "Straße", colSubcontractor: "outgesourced", colSubcontractorCost: "Outsource Kosten", colSubDirectory: "Verzeichnis", colTargetVersion: "Zielversion", colTask: "Aufgabe", colTax: "Steuersatz (%)", colTaxFree: "steuerfrei", colTeam: "Team", colTechnicalRisk: "Technisches Risko", colTestCase: "Testfall", colTestCases: "Testfälle", colTestSession: "Testplan", colTestSummary: "Teststatus", colText: "Text", colTicket: "Ticket", colTicketWork: "Zusammenfassung Ticketaufwand", colTime: "Zeit", colTitle: "Titel", colTotalAssignedCost: "Zugewiesene Gesamtkosten", colTotalCost: "Gesamtkosten", colTotalLeftCost: "verbleibende Gesamtkosten", colTotalPlannedCost: "geplante Gesamtkosten", colTotalRealCost: "Ist-Gesamtkosten", colTotalValidatedCost: "genehmigte Gesamtkosten", colType: "Typ", columnSelector: "wähle Spalten für Anzeige", colUnit: "Einheit", colUntaxedAmount: "Nettobetrag", colUrgency: "Dringlichkeit", colUser: "Benutzer", colUserAgent: "Benutzer Agent", colUserName: "Benutzername", colValidated: "bestätigt", colValidatedAmount: "Gesamtbetrag", colValidatedAmount2: "Betrag", colValidatedAmount3: "Gesamtbetrag", colValidatedCost: "bestätigte Kosten", colValidatedDate: "bestätigtes Datum", colValidatedDueDate: "Zieldatum bestätigt", colValidatedDuration: "Dauer bestätigt", colValidatedEnd: "Endedatum bestätigt", colValidatedEndDate: "Endedatum bestätigt", colValidatedPricePerDayAmount: "bestätigter Gesamtpreis/Tag", colValidatedPricePerDayAmount2: "Preis/Tag", colValidatedStartDate: "Startdatum bestätigt", colValidatedWork: "Arbeit bestätigt", colValidatedWork2: "Arbeit", colValue: "Wert", colValueAfter: "Wert neu", colValueBefore: "Wert alt", colValueCost: "Wert", colValueUnit: "Wert / Einheit", colVersion: "Version", colVersionName: "Versionsname", colWarning: "Erinnerung", colWbs: "PSP", colWbsSortable: "PSP sortierbarer", colWeekday1: "Mo", colWeekday2: "Di", colWeekday3: "Mi", colWeekday4: "Do", colWeekday5: "Fr", colWeekday6: "Sa", colWeekday7: "So", colWork: "Arbeit", colWorkElementCount: "Nummer", colWorkElementEstimatedWork: "geschätzer Aufwand für Tickets", colWorkElementLeftWork: "verbleibender Aufwand für Tickets", colWorkElementRealWork: "Ist-Aufwand für Tickets", colWorkflowUpdate: "Workflow", colZip: "Postleitzahl", comboCloseButton: "Schließen", comboDetailAccess: "Schalter anzeigen 'Detail-Kombinationen'", comboNewButton: "Erstelle neues Element", comboSaveButton: "Sichere Element", comboSearchButton: "Suche ein Element", comboSelectButton: "Wähle dieses Element", Command: "Auftrag", CommandType: "Auftragstyp", commentDueDates: "Anf | Pln | Ist", confirmChangeLoosing: "Aktuelle Änderung nicht gespeichert.<br/>Die Änderungen gehen verloren.<br/>Wollen Sie weitermachen?", confirmControlDelete: "Folgende Abhängigkeiten werden gelöscht", confirmControlSave: "Folgende Abhängigkeiten werden geschlossen", confirmCopy: "Kopiere den ${1} #${2} ?", confirmDelete: "Lösche den ${1} #${2} ?", confirmDeleteAffectation: "Löschen der Zuordnung #${1} ?", confirmDeleteApprover: "Lösche Genehmiger '${1}' ?", confirmDeleteAssignment: "Zuordnung Ressource ${1} löschen?", confirmDeleteDocumentVersion: "Lösche Version '${1}' ?", confirmDeleteExpenseDetail: "Sollen Detailaufwand '${1}' gelöscht werden?", confirmDeleteLink: "Verbindung mit Element ${1} #${2} löschen?", confirmDeleteOrigin: "Lösche Ursprung ${1} #${2}?", confirmDeleteOtherVersion: "Lösche ${2} '${1}' ?", confirmDeleteResourceCost: "Ressourcekosten für Funktion ${1} löschen?", confirmDeleteTestCaseRun: "Lösche Testfall #${1} von Testplan?", confirmDeleteVersionProject: "Lösche Verbindung zwischen Version und Projekt?", confirmDisconnectAll: "Bestätigung 'Abmelden aller Nutzer' (außer Ihres eigenen Nutzers)", confirmDisconnection: "Wollen Sie sich abmelden?", confirmLocaleChange: "Sie haben die Sprache geändert.<br/>Möchten Sie die Seite aktualisieren, um die Änderung zu sehen?", confirmRemoveFilter: "Lösche Filter '${1}' ?", confirmResetList: "Setzt die Anzeige auf Standardwert zurück - weitermachen?", connectionsDurationPerDay: "Connections duration per day", connectionsNumberPerDay: "Verbindungen pro Tag", Console: "Konsolemeldungen", consolidateAlways: "immer", consolidateIfSet: "nur wenn gewählt (löscht nicht übergeordnete Aktivität)", consolidateNever: "nie", Contact: "Kontakt", contactAdministrator: "Kontaktieren Sie Ihren Administrator.", contacts: "Kontakte", contains: "enthält", Context: "Kontext", ContextType: "Kontexttyp", copiedFrom: "kopiert von", copyAssignments: "Kopiere Zuweisungen zu Aktivitäten (incl. Arbeit)", copyFromCalendar: "Importiere dieses Jahr zum Kalender", copyProjectAffectations: "Kopiere Zuweisungen zum Projekt (incl. Unterprojekte)", copyProjectStructure: "Kopieren der Projektstruktur (Aktivitäten & Meilensteine)", copySubProjects: "Kopiere Unterprojekt", copyToClass: "Kopiere als neu", copyToLinkOrigin: "Verbinde aktuelles Element zur Kopie", copyToName: "Kopiere Name", copyToOrigin: "Aktuelles Element als Original des kopierten Elements hinzufügen", copyToType: "Typ kopiertes Element", copyToWithAttachments: "Anhänge mitkopieren", copyToWithLinks: "Verknüpfungen mitkopieren", copyToWithNotes: "Notizen mitkopieren", copyWithStructure: "Kopieren gesamte Struktur (Unteraktivitäten & -Meilensteine)", costAccess: "Kosten anzeigen", count: "zähle", created: "erstellt", criteria: "Filter oder Sortierkriterien", Criticality: "Kritikalität", cronLogAsFile: "Protokollieren als Datei", cronLogAsMail: "Protokollieren als Datei und Mail", cronLogAsMailWithFile: "Protokollieren als Datei und Mail mit Protokoll", cronStatus: "Cron Status", cronTasks: "Hintergrundverarbeitung", csvFile: "CSV Datei (Comma Separated Value)", cumulated: "kumuliert", day: "Tag", days: "Tage", dbMaintenance: "Wartung von Daten", debugLevel0: "Keine Fehlerverfolgung", debugLevel1: "Fehlerverfolgung", debugLevel2: "Standard Fehlerverfolgung", debugLevel3: "Fehler/Debug Stufe", debugLevel4: "Funktionsverfolgung", December: "Dezember", Decision: "Entscheidung", DecisionType: "Entscheidungstyp", defaultFilterCleared: "Standard-Filter gelöscht", defaultFilterError: "Standard-Filter kann nicht auf '$ {1}' gesetzt werden.", defaultFilterSet: "Standard-Filter auf '$ {1}' gesetzt.", defaultValue: "Standardwert", deleteAlerts: "Lösche Alarme", deleteAudit: "Lösche Verbindungs Logbuch", deleteButton: "Löschen", deleteEmails: "Lösche Mails", Dependency: "Abhängigkeit", descriptionChange: "Beschreibung geändert", dialogAffectation: "Ressourcenzuordnung", dialogAlert: "Alarm", dialogApprover: "Wähle Genehmiger", dialogAssignment: "Zuordnung", dialogAttachement: "Anhang", dialogBillLine: "Rechnungszeile", dialogChecklist: "Checkliste", dialogChecklistDefinitionLine: "Auswahlmöglichkeiten für die Checklistenzeile", dialogConfirm: "Bestätigung", dialogCopy: "Kopiere Element", dialogCopyProject: "Kopiere Projekt", dialogDependency: "Abhängigkeit hinzufügen", dialogDependencyActivity: "Abhängigkeit zu Aktivität hinzufügen", dialogDependencyEdit: "Abhängigkeit ändern", dialogDependencyExtended: "Abhängigkeit zu Element ${1} #${2} hinzufügen", dialogDependencyProject: "Verbindung zu Projekt hinzufügen ", dialogDependencyRestricted: "Füge ${3} zu Element ${1} #${2} hinzu", dialogDetailCombo: "Details Listenelement", dialogDocumentVersion: "Dokumentversion", dialogError: "Fehler", dialogExpenseDetail: "Details Aufwand", dialogExport: "Export", dialogFilter: "Erweiterte Filterfunktion", dialogInformation: "Information", dialogLink: "Verbindung hinzufügen ", dialogLinkAction: "Verbindung zu Aktion hinzufügen", dialogLinkExtended: "Verbindung zu Element ${1} #${2} hinzufügen", dialogLinkIssue: "Verbindung zu eine Problem hinzufügen", dialogLinkRestricted: "Füge Verbindung zwischen Element ${1} #${2} und Element ${3} hinzu.", dialogLinkRisk: "Verbindung zu Risiko hinzufügen", dialogNote: "Notiz", dialogOrigin: "Ursprungselement hinzufügen", dialogOtherVersion: "Andere Versionen hinzufügen", dialogPlan: "Kalkuliere Planung für Projekt", dialogPlanSaveDates: "Speichere geplantes Datum in gefordertes und bestätigtes Datum", dialogPrint: "Druckvoransicht", dialogProjectSelectorParameters: "Projektauswahl Parameter", dialogQuestion: "Frage", dialogResourceCost: "Ressourcekosten", dialogTestCaseRun: "Testfall-Durchlauf", dialogTodayParameters: "Heute Parameter", dialogVersionProject: "Verbindung Projekt zu Version", dialogWorkflowParameter: "Wähle Status anzeigen / ausblenden", Diary: "Terminkalender", diaryAccess: "Zugriff auf Terminkalender", disconnect: "Abmeldung", disconnectAll: "Abmelden aller Nutzer", disconnected: "Ihre Sitzung wurde vom Administrator beendet<br/>Bitte neu (später) anmelden.", disconnectMessage: "Ende aktuelle Sitzung", disconnectSession: "Erzwinge Abmeldung dieser Sitzung", displayAlert: "Interner Alarm", displayAlertAndMail: "Interner Alarm & Mail", displayEndDate: "Anzeige bis", displayMail: "Mail", displayModeSelect: "Filterauswahl (mit Autovervollständigung)", displayModeStandard: "Standard (entspricht WBS Struktur)", displayNo: "Nein", displayStartDate: "Anzeige von", displayYes: "Ja", displayYesClosed: "Ja (kompakte Ansicht)", displayYesOpened: "Ja (ausführliche Ansicht)", displayYesShowOnClick: "Ja (Anzeige bei Mouseclick)", displayYesShowOnMouse: "Ja (Anzeige bei Mousebewegung)", document: "Dokumente", Document: "Dokument", DocumentDirectory: "Dokumentverzeichnis", documents: "Dokumente", DocumentType: "Dokumenttyp", documentUnlockRight: "Entsperre alle Dokumente", DocumentVersion: "Dokumentversion", documentVersionIsRef: "Diese Version ist die letzte Referenz für das Dokument (zuletzt geprüft)", documentVersionUpdate: "Aktualisiere", done: "erledigt", doneoperationclose: "geschlossen", doneoperationdelete: "gelöscht", dragAndDrop: "Dateien hierher Ziehen und Ablegen", duplicateAlreadyLinked: "Duplikat bereits verbunden mit anderem Duplikat", duplicateIsSame: "Duplikat von sich selbst nicht möglich", editAffectation: "Ressourcenzuordnung ändern", editAssignment: "Zuordnung ändern", editDependencyPredecessor: "Vorgänger ändern", editDependencySuccessor: "Nachfolger ändern", editDocumentVersion: "Bearbeite diese Version", editExpenseDetail: "Aufwandsdetails ändern", editLine: "Bearbeite diese Zeile", editNote: "Notiz ändern", editResourceCost: "Ressourcekosten ändern", editTestCaseRun: "Testfall-Durchlauf ändern", editVersionProject: "Verbindung Projekt und Version ändern", Efficiency: "Effizienz", elementHistoty: "Historie", emailMandatory: "Mail muss erfasst sein", end: "Ende", Environment: "Stammdaten", eolDefault: "Standard Format (\r\n)", eolPostfix: "Spezifisches Format für Postfix < 2.1 (\n)", ERROR: "Fehler", errorAck: "Fehler bei Bestätigung", errorConnection: "Verbindung abgebrochen. Bitte neu anmelden.", errorConnectionCNX: "SQL FEHLER<BR//>Verbindungsproblem bei '${1}' Für Nutzer '${2}'.<BR/>Überprüfe 'Parameter' Datei.", errorConnectionDB: "SQL FEHLER<BR/>Verbindungsproblem 'unbekannte Datenbank' '${1}'.<BR/>Überprüfe 'Parameter' Datei.", errorControlClose: "Element kann nicht geschlossen werden - es bestehen noch nicht geschlossene, aber abhängige Elemente", errorControlDelete: "Element kann nicht gelöscht werden, da es bestehende Abhängigkeiten gibt.", errorCreateRights: "Sie haben nicht das Recht zum Erstellen", errorDeleteCostStartDate: "Neuer Kostensatz kann nicht vor dem alten wirksam werden", errorDeleteDefaultCalendar: "Standard Kalender kann nicht gelöscht werden.", errorDeleteDoneBill: "Erledigte Rechnung kann nicht gelöscht werden.", errorDeleteRights: "Sie haben nicht das Recht zum Löschen", errorDependencyHierarchy: "Kann keine Abhängigkeit mit übergeordneten Element erstellen", errorDependencyLoop: "Kann keine gegenseitigen Abhängigkeiten erstellen.", errorDuplicateActivityPrice: "Ein Aktivitätspreis für das selbe Projekt und Typ bereits vorhanden", errorDuplicateAffectation: "Dupliziere Zuordnung", errorDuplicateApprover: "Genehmiger existiert bereits", errorDuplicateChecklistDefinition: "Checklisten Definition bereits vorhanden (gleiches Element, gleicher Typ)", errorDuplicateDependency: "Abhängigkeit besteht bereits", errorDuplicateDocumentVersion: "Version '${1}' gibt es bereits für dieses Dokument", errorDuplicateIndicator: "Doppelter Indikator", errorDuplicateLink: "Diese Verbindung besteht bereits", errorDuplicateStatusMail: "'Mail nach Statusänderung' für dieses Element in diesem Satus bereits definiert", errorDuplicateTestCase: "Testfall bereits zu Testplan verbunden - 'erlaube Duplikat' ist nicht aktiviert", errorDuplicateTicketDelay: "Definition 'Verzögerung' für diesen Type in dieser Dringlichkeit gibt es bereits", errorDuplicateUser: "Mit diesem Namen gibt es schon einen Nutzer", errorDuplicateVersionProject: "Zuordnung Projekt zu Version kann nur einmal erfolgen", errorEmptyBill: "Die Rechnung darf nicht leer sein", errorFinalizeMessage: "Fehler bei finalizeMessageDisplay('${1}') : <br/>Ziel ist kein Knoten und kein Steuerelement<br/>oder lastOperation oder lastOperationStatus ist kein Knoten<br/><br/>${2}", errorHierarchicLoop: "Kann keine Hierarchie-Abhängigkeiten erstellen.", errorIdleWithLeftWork: "Element mit offener Arbeit kann nicht geschlossen werden.", errorImportFormat: "<b>FEHLER - Feldtyp und gewähltes Dateiformat stimmen nicht überein</b><br/>Import abgebrochen", errorLoadContent: "Fehler bei loadContent('${1}', '${2}', '${3}', '${4}')<br/>Ziel '${5}' ist kein Knoten und kein Steuerelement", errorLockedBill: "Rechnung gesperrt", errorMagicQuotesGpc: "'magic_quotes_gpc' muss abgeschalten werden (Wert = false). <br/>Ändern Sie die Datei 'Php.ini'.", errorMandatoryValidatedDuration: "Gültige Dauer erforderlich.", errorMandatoryValidatedEndDate: "Gültiges Endedatum erforderlich.", errorMandatoryValidatedStartDate: "Gültiges Startdatum erforderlich.", errorMessage: "Fehler aufgetreten bei ${1} mit ${2}", errorMessageCopy: "${1} Fehler während des Kopierens", errorNoFile: "Keine Datei zum Hochladen vorhanden", errorNotFoundFile: "Importdatei nicht gefunden", errorObjectId: "Fehler mit Schalter NEU : objectId ist kein Knoten", errorRegisterGlobals: "'register_globals' muss abgeschalten werden (Wert = false). <br/>Ändern Sie die Datei 'Php.ini'.", errorStartEndDates: "${1}' darf nicht spätester als '${2}' sein.", errorSubmitForm: "Fehler bei 'submitForm('${1}', '${2}', '${3}')' : <br/> Form '${3}' ist kein Steuerelement.", errorTooBigFile: "Dateigröße übersteigt maximales Limit von ${1} Bytes (${2})", errorUpdateRights: "Sie haben nicht das Recht zum Ändern", errorUploadFile: "Fehler beim Hochladen der Datei. Fehler Kode = ${1}", errorValueWithoutUnit: "Einheit erforderlich, wenn ein Wert vorhanden ist", errorWorflow: "Dieser Status ist laut Workflow nicht zugelassen", errorXhrPost: "Fehler xhrPost return für loadContent('${1}', '${2}', '${3}', '${4}') : <br/> ${5}", estimated: "Arbeit geschätzt", evolutive: "Entwicklung", exceptionMessage: "Ein Ausnahmefall von ${1} bei ${2} ist aufgetreten", existingDirectoryName: "Dieses Verzeichnis existiert bereits", ExpenseDetail: "Aufwandsdetail", ExpenseDetailType: "Aufwandsdetailtyp", exportReferencesAs: "ID oder Name für Referenzen", external: "benutzerdefiniert", ExternalShortcuts: "Externe Abkürzungen", failed: "nicht erfolgreich", failedTestCaseRun: "Testfall als 'fehlgeschlagen' markieren", Feasibility: "Machbarkeit", February: "Februar", filterName: "Filtername", filterOnId: "Filter nach ID", filterOnName: "Filter nach Name", filterOnType: "Filter nach Typ", flashReport: "Blitzbericht", Friday: "Freitag", from: "von", Health: "Projektstatus", help: "Online Handbuch", helpAlertCheckTime: "Verzögerung in Sekunden vor neuer Prüfung, ob neuer Alarm vorhanden.", helpBillNumSize: "Zahl der Stellen für Rechnungsnummer", helpBillNumStart: "Startnummer für Rechnungen", helpBillPrefix: "Präfix für Rechnungsnummern", helpBillSuffix: "Anhang für Rechnungsnummern", helpBrowserLocaleDateFormat: "Format zur Darstellung des Datums - DD für Tag - MM für Monat - YYYY für Jahr", helpChangeReferenceOnTypeChange: "Ändere Referenz nach Typänderung", helpConsolidateValidated: "konsolidiere bestätigte Arbeit & Kosten bei Top-Aktivitäten und -Projekten", helpCronCheckDates: "Verzögerung für Erzeugung Alarme in Sekunden", helpCronCheckEmails: "Verzögerung (in Sek.) für Prüfung Maileingang, Speichern von Antworten als Notizen", helpCronCheckEmailsHost: "IMAP host Verbindungdaten zur Prüfung auf Maileingang, z. B. : {imap.gmail.com:993/imap/ssl}INBOX", helpCronCheckEmailsPassword: "IMAP password Maileingang", helpCronCheckEmailsUser: "IMAP Name Maileingang", helpCronCheckImport: "Verzögerungen autom. Importe in Sek.", helpCronDirectory: "Arbeitsverzeichnis für CRON Kennzeichen", helpCronImportDirectory: "Verzeichnis Integration von neuen Dateien", helpCronImportLogDestination: "Ort Ergebnisprotokoll der automatischen Integration", helpCronImportMailList: "Mail-Verteiler Ergebnisprotokoll autom. Integration", helpCronSleepTime: "Standard Cron Wartezeit in Sekunden", helpCsvSeparator: "Zeichentrennung je Feld im CSV Format für Im-/Export", helpCurrency: "Währungskennzeichen für Kostensicht", helpCurrencyPosition: "Position Währungskennzeichen", helpDayTime: "Anzahl Stunden für Arbeit pro Tag", helpDefaultProfile: "Standardprofil für neue Nutzer", helpDefaultProject: "Wähle das Standardprojekt für jede neue Anmeldung.", helpDefaultTheme: "Standard Benutzeroberfläche, wenn Nutzer keine individuelle Einstellung wählt", helpDisplayAttachement: "Anzeigemodus für Abschnitt Anhang", helpDisplayHistory: "Zeige die Änderungshistorie je Element an.", helpDisplayNote: "Anzeigemodus für Abschnitt Notiz", helpDisplayOnlyHandled: "Nur Aufgaben 'in Bearbeitung' im 'Ist-Arbeit-Report' anzeigen", helpDisplayResourcePlan: "Formatierungsoptionen für Ressourcen in Ganttplanung", helpDocumentReferenceFormat: "Format Dokumentenreferenz", helpDocumentRoot: "Wurzelverzeichnis für Dokumente", helpDontReceiveTeamMails: "keine Mails, wenn Empfänger ist aus 'Team' (Resourcen, die dem Projekt zugeordnet sind)", helpDownload: "Lade diese Datei herunter.", helpDraftSeparator: "Trennzeichen für ENTWURF im Versionsnamen", helpEndAM: "Endzeit der Standardarbeitszeit am Vormittag", helpEndPM: "Endzeit der Standardarbeitszeit am Nachmittag", helpFilenameCharset: "Zeichensatz für Dateien auf dem Server, um Nicht-ASCII-Zeichen zu berücksichtigen (z. B. ISO-8859-15)", helpGanttPlanningPrintOldStyle: "Drucke Gantt im alten Format - sofern Fehler beim Druck auftraten - Sie verlieren zwar Besonderheiten im Layout, gewinnen aber Stabilität", helpGetVersion: "Aktivitätstypen", helpHideMenu: "Verdecke oder zeige linkes 'Baum'-Menü", helpImport: "Anzeige der Feldnamen", helpImputationUnit: "Einheit für Ist-Arbeit: Tage oder Stunden", helpLang: "Wählen Sie ihre bevorzugte Sprache.", helpLdapDefaultProfile: "Standard Profil für neue Nutzer, die durch LDAP hinzugefügt werden.", helpLdapMsgOnUserCreation: "Nachrichtentyp oder Alarm an Adminstrator, bei neuen LDAP Nutzern", helpLogFile: "Log Dateiname (kann den Parameter ${date} enhalten, um 1 Datei pro Tage zu haben)", helpLogLevel: "Log Stufe", helpMaxDaysToBookWork: "Erfassung von IST-Arbeit in die Zukunft über die festgelegte Anzahl von Tagen hinaus, führt zur Sicherheitsmeldung", helpMaxProjectsToDisplay: "Maximale Anzahl von Projekten in der Datenbank ab der Projekte in der Planungssicht begrenzt werden", helpnitializePassword: "Automatische Passwort-Initialisierung bei neuen Nutzern", helpOtherEmail: "manuelle Eingabe Mail-Adresse", helpParamAdminMail: "E-Mail des Administrators", helpParamAttachementDirectory: "Verzeichnis für Anhänge", helpParamAttachementMaxSize: "Maximale Größe für Anhänge in byte - muss kleiner oder gleich zum PHP Parameter : upload_max_filesize sein", helpParamConfirmQuit: "Anzeige Abmelden-Bestätigung bei 'Schließen d. Tabs' oder 'Rücktaste'", helpParamDbDisplayName: "Datenbankname der in der Fußleiste angezeigt wird", helpParamDefaultLocale: "Standardsprache, wenn Nutzer keine individuelle Einstellung wählt", helpParamDefaultPassword: "Standard Password bei Nutzeranlage", helpParamDefaultTimezone: "Standard Zeitzone - liste siehe entsprechende Webseite", helpParamFadeLoadingMode: "Neue Bildschirme in Überblendemodus anzeigen", helpParamIconSize: "Größe der Icons in der Menübaumanzeige", helpParamLdap_allow_login: "Erlaube Verbindung mit LDAP Nutzer", helpParamLdap_base_dn: "LDAP Basis DN für ProjecQtOr Nutzer", helpParamLdap_host: "LDAP Hostadresse oder IP", helpParamLdap_port: "LDAP port - Standard ist 389", helpParamLdap_search_pass: "LDAP Password für Hauptnutzer", helpParamLdap_search_user: "LDAP Hauptnutzer für Verbindung und Suche in LDAP", helpParamLdap_user_filter: "LDAP Filter zur Suche nach Nutzernamen - Ergebnis %USERNAME% gefunden", helpParamLdap_version: "LDAP Protokollversion, um Kompatibilitätsprobleme zu lösen", helpParamLockAfterWrongTries: "lock user after a given number of wrong connexions", helpParamMailBodyApprover: "Text für Mails 'Genehmigung von Anforderungen'", helpParamMailBodyUser: "Text für Login Informations Mails", helpParamMailEol: "Zeilenende Format für Mails zur Problemlösung von Postfix < 2.1", helpParamMailReplyTo: "Antworten an' Mail-Adresse", helpParamMailReplyToName: "Name des Mail-Senders - auch für Antworten", helpParamMailSender: "Absender' Mail-Adresse", helpParamMailSendmailPath: "Pfad für 'sendmail' wenn nicht automatisch durch PHP identifiziert (im Zweifel leer lassen)", helpParamMailSmtpPassword: "SMTP login password", helpParamMailSmtpPort: "Port für email (smtp) server [Standardwert = 25]", helpParamMailSmtpServer: "Smtp server [Standard = 'localhost']", helpParamMailSmtpUsername: "SMTP login Name - notwendig für die Authentifizierung am Verbindungsserver", helpParamMailTitleAnyChange: "Mailtitel bei Änderungen", helpParamMailTitleApprover: "Titel für Mails 'Genehmigung von Anforderungen'", helpParamMailTitleAssignment: "Mailtitel für hinzugefügte Zuweisung", helpParamMailTitleAssignmentChange: "Mailtitel für geänderte Zuweisung", helpParamMailTitleAttachment: "Mailtitel für hinzugefügte Anhänge", helpParamMailTitleDescription: "Mailtitel für geänderte Beschreibungen", helpParamMailTitleDirect: "Mailtitel, die manuell (Mail Schalter) versandt werden", helpParamMailTitleNew: "Mailtitel für hinzugefügte Elemente", helpParamMailTitleNote: "Mailtitel für hinzugefügte Notizen", helpParamMailTitleNoteChange: "Mailtitel für geänderte Notizen", helpParamMailTitleResponsible: "Mailtitel für geänderte Verantwortliche", helpParamMailTitleResult: "Mailtitel für geänderte Ergebnisse", helpParamMailTitleStatus: "Mailtitel für Statusänderungen", helpParamMailTitleUser: "Titel für Login Informations Mail", helpParamMemoryLimitForPDF: "Speicherlimit in MB für PDF-Erstellung - zu wenig Speicher führt zu PDF Problemen und zu viel Speicher bringt den Server zum Absturz", helpParamPasswordMinLength: "Mindestzahl von Zeichen für das Password", helpParamReportTempDirectory: "Temporäres Verzeichnis für Berichte - muss im Web Dokumentenstamm sein, um Images zu bekommen ", helpParamTopIconSize: "Größe der Icons in der Top-Menü-Anzeige", helpPasswordValidityDays: "Passwort Gültigkeit (in Tage) bis zur Änderung-Aufforderung - 0 für dauerhafte Gültigkeit", helpPdfInNewWindow: "PDF Exporte in neuem Fenster (oder Tabulator) oder aktuellem Fenster voranzeigen", helpPreserveUploadedFileName: "Soll die Datei nach Download mit dem Ursprungs-Dateinamen (Ja) oder gemäß Formatierung (Nein) benannt werden.", helpPrintInNewWindow: "Voranzeige Druckausgabe in neuem Fenster (oder Tabulator) oder aktuellem Fenster", helpRealWorkOnlyForResponsible: "Nur Verantwortlicher kann IST-Aufwände im Ticket erfassen", helpReferenceFormatNumber: "Anzahl Stellen für Referenznummernzähler", helpReferenceFormatPrefix: "Präfix Format für Referenznummer", helpRefreshUpdates: "Aktualisiere Anzeige nach Änderungen.", helpRememberMe: "Erinnerung' Funktion für Autoverbindung erlauben", helpResetColor: "Farbe zurücksetzen - wird transparent", helpResetPassword: "Passwort zurücksetzen - Bitte sichern nach dieser Aktion.", helpSelectFile: "Wähle die Datei zum Hochladen.", helpSetHandledOnRealWork: "Aufgabe erst auf 'begonnen' setzen, wenn Ist-Arbeit erfaßt wurde", helpSetResponsibleIfNeeded: "Weise automatisch Verantwortlichen als Ressource zu, wenn eine Resource erforderlich ist.", helpSetResponsibleIfSingle: "Weise automatisch Verantwortlichen als Ressource zu, wenn nur eine Resource dem Projekt zugewiesen ist.", helpStartAM: "Start Standardarbeitszeit am Vormittag", helpStartPage: "Anzeige nach Logon", helpStartPM: "Start Standardarbeitszeit am Nachmittag", helpSwitchedMode: "Legt Anzeige zwischen Listen- und Detailanzeige fest", helpTheme: "Farbe für die Anzeige ändern", helpTitle: "Titel für Tooltip", helpVersionReferenceSuffix: "Anhang für Versions-Referenz", helpWorkUnit: "Einheit für Arbeit", hour: "Stunde", hours: "Stunden", iconSizeBig: "groß (32px)", iconSizeMedium: "mittel (22px)", iconSizeSmall: "klein (16px)", ifEmpty: "wenn leer", imputationAccess: "Zugriff auf Ressourcenzuordnung ", indentDecreaseButton: "Einrückung verringern", indentIncreaseButton: "Element unter Vorgänger einrücken", IndicatorDefinition: "Indikator", IndividualExpense: "Individueller Aufwand", IndividualExpenseType: "Individueller Aufwandstyp", INFO: "Information", infoLocaleChange: "Sie änderten die bevorzugte Sprache.<br/>Bis zur nächsten Neuanmeldung werden nicht alle Informationen korrekt angezeigt.<br/>Deshalb bitte speichern Sie die Parameter und melden sich neu an.", infoLocaleChangeShort: "Sie änderten die bevorzugte Sprache.", infoMessage: "Besuchen Sie die 'ProjecQtOr web Site'.", initialDueDate: "Berücksichtige anfängliches Startdatum", initialDueDateTime: "Berücksichtige anfängliches Startdatum/-zeit", initialEndDate: "Berücksichtige gewünschtes Endedatum", initialStartDate: "Berücksichtige gewünschtes Startdatum", invalidAccessAttempt: "Unzulässiger Zugriffsversuch", invalidDirectoryName: "Ungültiger Verzeichnisname", invalidGpsData: "Ungültige GPS Daten", invalidLogDir: "Log-Buch-Verzeichnis '${1}' ist ungültig. Überprüfen Sie die 'Parameter' Datei.", invalidLogin: "Ungültige Anmeldedaten.", invalidPasswordChange: "Ungültiges neues Passwort<br> - es muss mindestens ${1} Zeichen lang sein.<br/> - es muss unterschiedlich vom Standard-/Start-Wert sein.", Invoice: "Rechnung", InvoiceType: "Rechnungtyp", isEmpty: "ist leer", isIssuerOf: "ist Ersteller von", isNotEmpty: "ist nicht leer", isResponsibleOf: "ist verantwortlich für", Issue: "Probleme", IssueType: "Problemtyp", January: "Januar", July: "Juli", June: "Juni", labelDisplayOnlyCurrentWeekMeetings: "Zeige nur Besprechungen der aktuellen Woche", labelHideDone: "'nicht bearbeitete' Elemente ausblenden", labelHideNotHandled: "'erledigte' Elemente ausblenden", labelMultipleMode: "Mehrfach-Modus", labelShowIdle: "Zeige abgeschlossene Elemente", labelShowLeftWork: "Zeige verbleibende Arbeit", labelShowMilestone: "Meilensteine anzeigen", labelShowPlannedWork: "Zeige geplante Arbeit", labelShowProjectLevel: "Zeige Projektebene", labelShowResource: "Zeige Ressourcen", labelShowWbs: "Zeige PSP", langDe: "Deutsch", langEl: "Griechisch", langEn: "Englisch - English", langEs: "Spanisch - Español", langFa: "Farsi (Persian) - فارسی", langFr: "Französisch - Français", langJa: "Japanisch", langNl: "Holländisch - Nederlands", langPt: "Portugisisch - Português", langPtBr: "Portuguese (Brazil) - Português (Brazil)", langRu: "Russisch - Pусский", langZh: "Chinese - 简体中文", ldapError: "LDAP Fehler", left: "Arbeit verbleibend", Likelihood: "Wahrscheinlichkeit", limitedDisplay: "Liste ist gekürzt auf die ${1} ersten Positionen", Link: "Verbindung", linkElement: "verbundenes Element", linkType: "verbundener Elementtyp", listTodayItems: "Anzuzeigende Elemente", lockDocument: "Sperre dieses Dokument", lockedLogDir: "Logbuch-Verzeichnis '${1}' ist gesperrt. Logbuch-Funktion nicht verfügbar.", lockedUser: "Dieser Nutzer ist gesperrt.<br/>Bitte Kontakt mit Administrator aufnehmen.", lockRequirement: "Sperre Anforderung", login: "Anmeldung", loginOK: "Anmeldung war erfolgreich", Mail: "Mailausgang", mailSent: "Mail versandt", mailSentTo: "Mail versandt an '${1}'", mainProject: "Hauptprojekt", maintenanceDone: "${1} '${2}' ${3}", manageConnections: "Verwalte Verbindungen", mandatoryField: "erforderlich", mandatoryOnDoneStatus: "erforderlich bei 'erledigt'-Status", mandatoryOnHandledStatus: "erforderlich bei 'bearbeitet'-Status", March: "März", markAsRead: "Als gelesen markieren", max: "max", May: "Mai", mean: "mean", Meeting: "Besprechung", MeetingType: "Besprechungstyp", members: "Mitglieder", menu: "Menü", menuAccessProfile: "Zugriffsmodus", menuAccessRight: "Zugriff auf Daten", menuAction: "Aktionen", menuActionType: "Aktionstypen", menuActivity: "Aktivitäten", menuActivityPrice: "Aktivitätenpreis", menuActivityType: "Aktivitätstypen", menuAdmin: "Verwaltung", menuAffectation: "Ressourcenzuordnungen", menuAlert: "Alarme", menuAllAction: "Alle Aktionen", menuAllActivity: "Alle Aktivitäten", menuAllComponent: "Alle Komponenten", menuAllIssue: "Alle Probleme", menuAllMeeting: "Alle Besprechungen", menuAllRisk: "Alle Risiken", menuAnomaly: "Unregelmäßigkeiten", menuAudit: "Prüfe Verbindungen", menuAutomation: "Steuerung & Automatisierung", menuBarMoveLeft: "Balken nach links verschieben", menuBarMoveRight: "Balken nach rechts verschieben", menuBill: "Rechnungen", menuBillType: "Rechnungstypen", menuCalendar: "Kalender", menuCalendarDefinition: "Kalender", menuChecklistDefinition: "Checklisten", menuClient: "Kunden", menuClientType: "Kundentypen", menuCommand: "Aufträge", menuCommandType: "Auftragstypen", menuComponent: "Komponenten", menuContact: "Kontakte", menuContext: "Kontext", menuContextType: "Kontextypen", menuCriticality: "Kritikalitäten", menuDecision: "Entscheidungen", menuDecisionType: "Entscheidungstypen", menuDiary: "Terminkalender", menuDocument: "Dokumente", menuDocumentDirectory: "Dokumentenverzeichnis", menuDocumentType: "Dokumenttypen", menuEfficiency: "Effizienzen", menuEnvironment: "Stammdaten", menuEnvironmentalParameter: "Stammdaten", menuExpenseDetailType: "Aufwandsdetailtypen", menuFeasibility: "Machbarkeiten", menuFinancial: "Finanzen", menuFollowup: "Planung & Berichte", menuGlobalParameter: "Globale Parameter", menuHabilitation: "Zugriff auf Formulare", menuHabilitationOther: "Spezielle Zugriffe", menuHabilitationParameter: "Zugriffsrechte", menuHabilitationReport: "Zugriff auf Berichte", menuHealth: "Projektstatus", menuImportData: "Daten importieren", menuImputation: "Ist-Arbeit-Report ", menuIndicatorDefinition: "Indikatoren", menuIndividualExpense: "Individuelle Aufwände", menuIndividualExpenseType: "Individuelle Aufwandtypen", menuInvoice: "Rechnung", menuInvoiceType: "Rechnungstypen", menuIssue: "Probleme", menuIssueType: "Problemtypen", menuLikelihood: "Wahrscheinlichkeit", menuListOfValues: "Werte & Ausprägungen", menuMail: "Mailausgang", menuMeeting: "Besprechungen", menuMeetingType: "Besprechungstypen", menuMessage: "Meldungen", menuMessageType: "Meldungstypen", menuMilestone: "Meilensteine", menuMilestoneType: "Meilensteintypen", menuOpportunity: "Chancen", menuOpportunityType: "Chancentypen", menuOverallProgress: "Gesamt Fortschritt", menuParameter: "Parameter", menuPayment: "Zahlungen", menuPaymentType: "Zahlungstypen", menuPeriodicMeeting: "Regelmäßige Besprechungen", menuPlanning: "Planung", menuPortfolioPlanning: "Projekt Portfolio", menuPredefinedNote: "vordefinierte Notizen", menuPriority: "Prioritäten", menuProduct: "Produkte", menuProfile: "Profile", menuProject: "Projekte", menuProjectExpense: "Projektaufwände", menuProjectExpenseType: "Projektaufwandstypen", menuProjectLife: "Produkt-Lebenzyklus", menuProjectParameter: "Projekt Parameter", menuProjectType: "Projekttypen", menuQuality: "Qualitätslevel", menuQuestion: "Fragen", menuQuestionType: "Fragentypen", menuQuotation: "Angebote", menuQuotationType: "Angebotstypen", menuRecipient: "Empfänger", menuReports: "Berichte", menuRequestor: "Abfragegenerator", menuRequirement: "Anforderungen", menuRequirementTest: "Anforderungen & Tests", menuRequirementType: "Anforderungstypen", menuResource: "Ressourcen", menuResourcePlanning: "Ressourcenplanung", menuReview: "Protokolle / Logbücher", menuRisk: "Risiken", menuRiskLevel: "Risikoebenen", menuRiskManagementPlan: "Risiko & Problem Management", menuRiskType: "Risikotypen", menuRole: "Funktionen", menuSeverity: "Auswirkung", menuStatus: "Status", menuStatusMail: "Mails nach Statusänderungen", menuTeam: "Teams", menuTerm: "Konditionen", menuTestCase: "Testfälle", menuTestCaseType: "Testfalltypen", menuTestSession: "Testpläne", menuTestSessionType: "Testplantypen", menuTicket: "Tickets", menuTicketDelay: "Verzögerungen für Tickets", menuTicketSimple: "Tickets (einfach)", menuTicketType: "Tickettypen", menuToday: "Heute", menuTool: "Werkzeuge", menuTrend: "Trends", menuType: "Liste der Typen", menuUrgency: "Dringlichkeiten", menuUser: "Nutzer", menuUserParameter: "Nutzerparameter", menuVersion: "Versionen", menuWork: "Arbeit", menuWorkflow: "Workflow", Message: "Meldung", messageConfirmationNeeded: "Aktion erfordert Bestätigung", messageDateMandatoryWithTime: "Das Feld '${1}' muss Datum mit Zeit enthalten", messageError: "FEHLER", messageImputationSaved: "Ist-Aufwände gesichert", messageInvalidControls: "Ungültiges Steuerelement", messageInvalidDate: "Das Datum muss einen gültigen Wert haben.", messageInvalidDateNamed: "Das Feld '${1}' muss ein gültiges Datum haben.", messageInvalidNumeric: "Wert von ${1} ist nicht numerisch", messageInvalidTime: "Die Zeit muss einen gültigen Wert haben.", messageInvalidTimeNamed: "Das Feld '${1}' muss einen gültigen Wert haben.", messageItemDelete: "Element ${1} # ${2} wurde nicht in der Datenbank gefunden.", messageMandatory: "Feld '${1}' ist erforderlich", messageNoAccess: "Sie haben nicht die Zugriffsberechtigung für ${1}.", messageNoChange: "Keine Änderung vorhanden.", messageNoData: "Nr. ${1} ist ausgewählt.", messageNoImputationChange: "Keine Änderung bei Ist-Arbeit vorhanden.", messageParametersNoChangeSaved: "Keine Änderung bei Parametern vorhanden.", messageParametersSaved: "Parameter sind gesichert.", messagePreview: "Bereite Druckvorschau vor …", messageSelectedNotAvailable: "Sie wählten '${1}'.<br/>Die Funktionalität ist nicht verfügbar in dieser Version von ProjecQtOr.<br/>Tut uns leid …", messageTextTooLong: "Länge für ${1} überschreitet ${2} Zeichen", MessageType: "Meldungstyp", Milestone: "Meilenstein", MilestoneType: "Meilensteintyp", min: "min", minute: "Minuten", Monday: "Montag", month: "Monat", moveCancelled: "Verschiebung nicht möglich.", moveDone: "Element erfolgreich verschoben", msgCannotDeleteContact: "Kontakt kann nicht gelöscht werden, denn er ist auch ein Benutzer.", msgCannotDeleteProfile: "Dieses Profil kann nicht gelöscht werden", msgCannotDeleteProjectType: "Dieser Typ von Projekten kann nicht gelöscht werden", msgCannotDeleteResource: "Ressource kann nicht gelöscht werden, denn sie ist auch ein Benutzer.", msgCannotDeleteStatus: "Dieser Standardstatus kann nicht gelöscht werden", msgEnterPlannedDA: "Geplantes Datum und Betrag müssen beide erfaßt werden.", msgEnterRealDA: "Ist-Datum und -Betrag müssen beide erfaßt werden.", msgEnterRPAmount: "Betrag (geplant oder ist) muss erfaßt werden.", msgEnterRPDate: "Datum (geplant oder ist) muss erfaßt werden.", msgIncorrectReceiver: "Empfänger kann für dieses Element nicht ausgewählt werden.", msgNotGranted: "Sie haben nicht das Recht für diese Operation", msgParentActivityInSameProject: "Übergeordnete Aktivität muss im selben Projekt vorhanden sein.", msgParentRequirementInSameProjectProduct: "Übergeordnete Anforderung muss im selben Projekt vorhanden sein.", msgParentTestCaseInSameProjectProduct: "Übergeordneter Testfall muss im selben Projekt vorhanden sein.", msgPdfDosabled: "PDF export ist deaktiviert.", msgPlanningActivityInSameProject: "Planungstyp muss im selben Projekt vorhanden sein.", msgRealWorkInTheFuture: "Ihre IST-Aufwand-Meldung liegt über den zugelassenen ${1} Tagen in der Zukunft - Wollen Sie das?", msgTranslatable: "Achtung - dieses Feld wird gemäß lokalen Einstellungen übersetzt.", msgTranslation: "Übersetzung", msgUnableToDeleteRealWork: "Kann nicht gelöscht werden, da Ist-Arbeit gebucht ist.", never: "nie", newLine: "<br/><br/>", newParameters: "${1} neue Paramenter in Version ${2}", newPassword: "Neues Passwort", newUser: "Neuer Nutzer", newUserMessage: "Nutzer '${1}' von LDAP erstellt", newVersion: "Neue Version ${1} auf ProjecQtOr Webseite verfügbar", nextDays: "Nächste Tage", noChecklistDefined: "Keine Checkliste für dieses Element", noDataToDisplay: "Keine Daten zur Anzeige verfügbar", noFilterClause: "Keine Filterklausel", noItemSelected: "Kein Element ausgewählt", noMailSent: "Kann Mail nicht an '${1}'. ${2} senden.", noStoredFilter: "Keine gespeicherten Filter", notAbleToStopCron: "Cron Prozess kann nicht gestoppt werden. Bitte nochmals versuchen oder löschen Sie '/file/cron/RUNNING file'", notAmongst: "nicht über", notApproved: "nicht genehmigt", notAssignedWork: "nicht zugewiesene Arbeit", notContains: "enthält nicht", Note: "Notiz", noteAdd: "Notiz hinzugefügt", noteChange: "Notiz geändert", noteFromEmail: "Notiz als Mail erhalten", notPlanned: "nicht geplant", November: "November", October: "Oktober", openDays: "offene Tage", openHours: "offene Stunden", OperatingSystem: "OS", operationDelete: "gelöscht", operationInsert: "eingefügt", operationUpdate: "aktualisiert", operatorNotSelected: "Operator ist verpflichtend", Opportunity: "Chance", OpportunityType: "Chancentype", Origin: "Ursprung", originElement: "Ursprungselement", originType: "Urspungstyp", OtherVersion: "Andere Version", otherVersionAdd: "Andere Version hinzufügen", otherVersionDelete: "Andere Version löschen", otherVersionSetMain: "Setze diese Version als Hauptversion", OverallProgress: "Gesamt Fortschritt", paramAlertCheckTime: "Verzögerung um Alarme prüfen in Sek.", paramBillNumSize: "Zahl der Stellen für Rechnungsnummer", paramBillNumStart: "Startnummer für Rechnungen", paramBillPrefix: "Vorspann für Rechnungsnummern", paramBillSuffix: "Anhang für Rechnungsnummern", paramBrowserLocaleDateFormat: "Format zur Darstellung des Datums", paramChangeReferenceOnTypeChange: "Ändere Referenz nach Typänderung", paramConsolidateValidated: "konsolidiere bestätigte Arbeit & Kosten", paramCronCheckDates: "Verzögerung Erzeugung Alarme in Sek.", paramCronCheckEmails: "Verzögerung Maileingangprüfung in Sek.", paramCronCheckEmailsHost: "IMAP host zur Prüfung auf Maileingang", paramCronCheckEmailsPassword: "IMAP password Maileingang", paramCronCheckEmailsUser: "IMAP Name Maileingang", paramCronCheckImport: "Verzögerungen autom. Importe in Sek.", paramCronDirectory: "CRON Arbeitsverzeichnis", paramCronImportDirectory: "Verzeichnis automatisch integrierter Dateien", paramCronImportLogDestination: "Ort für Protokolle", paramCronImportMailList: "Mailverteiler für Protokolle", paramCronSleepTime: "Generelle Cron Wartezeit in Sekunden", paramCsvSeparator: "Trenner für CSV Dateien", paramCurrency: "Währung", paramCurrencyPosition: "Position Währungskennzeichens in Kostensicht", paramDayTime: "Anzahl Stunden pro Tag", paramDefaultProfile: "Standarprofil bei neuen Nutzern", paramDefaultProject: "Standard Projekt", paramDefaultTheme: "Standard Benutzeroberfläche", paramDisplayAttachement: "Zeige Anhänge", paramDisplayHistory: "Zeige Historie", paramDisplayNote: "Zeige Notizen", paramDisplayOnlyHandled: "Nur 'begonnen' Aufgaben anzeigen", paramDisplayResourcePlan: "Anzeige Ressourcen im Gantt", paramDocumentReferenceFormat: "Format Dokumentenreferenz", paramDocumentRoot: "Wurzelverzeichnis für Dokumente", paramDontReceiveTeamMails: "Kein Empfang von Team Mails", paramDraftSeparator: "Trennzeichen für DRAFT im Versionsnamen", paramEndAM: "Endezeit Vormittag", paramEndPM: "Endezeit Nachmittag", paramFilenameCharset: "Zeichensatz für Dateien auf dem Server", paramGanttPlanningPrintOldStyle: "Drucke Gantt im alten Format", paramGetVersion: "Prüfung, auf neue Version", paramHideMenu: "Menü ausblenden", paramImputationUnit: "Einheit für Ist-Arbeit", paramInitializePassword: "Passwort-Initialisierung bei neuen Nutzern", paramLang: "Sprache", paramLdapDefaultProfile: "Standard-Profil für LDAP Nutzer", paramLdapMsgOnUserCreation: "Nachricht bei neuen Nutzer durch LDAP", paramLogFile: "Log Dateiname", paramLogLevel: "Log Stufe", paramMaxDaysToBookWork: "Max. Tage um IST-Aufwände zu buchen", paramMaxItemsInTodayLists: "Maximale Positionen in 'Heute' Ansicht", paramMaxProjectsToDisplay: "Maximal anzuzeigende Projekte", paramNone: "keine", paramParamAdminMail: "E-Mail des Administrators", paramParamAttachementDirectory: "Verzeichnis für Anhänge", paramParamAttachementMaxSize: "Maximale Größe für Anhänge", paramParamConfirmQuit: "Bitte bestätigen Sie die Abmeldung", paramParamDbDisplayName: "Name der Datenbank", paramParamDefaultLocale: "Standardsprache", paramParamDefaultPassword: "Standard Password", paramParamDefaultTimezone: "Zeitzone", paramParamFadeLoadingMode: "Anzeige im Überblendmodus", paramParamIconSize: "Icon Größe im Menü", paramParamLdap_allow_login: "Verbindung mit LDAP Nutzer", paramParamLdap_base_dn: "LDAP Basis DN", paramParamLdap_host: "LDAP Host", paramParamLdap_port: "LDAP Port", paramParamLdap_search_pass: "LDAP Password", paramParamLdap_search_user: "LDAP Nutzer", paramParamLdap_user_filter: "LDAP Nutzerfilter", paramParamLdap_version: "LDAP Version", paramParamLockAfterWrongTries: "lock user after wrong tries", paramParamMailBodyApprover: "Text für Mails 'Genehmigung von Anforderungen'", paramParamMailBodyUser: "Text für Mails an Nutzer", paramParamMailEol: "Zeilenende Format für Mails", paramParamMailReplyTo: "Antworten an' Mail-Adresse", paramParamMailReplyToName: "Name Mail-Sender - auch für Antworten", paramParamMailSender: "Absender' Mail-Adresse", paramParamMailSendmailPath: "Pfad für 'sendmail'", paramParamMailSmtpPassword: "SMTP login password", paramParamMailSmtpPort: "smtp Port", paramParamMailSmtpServer: "smtp Server", paramParamMailSmtpUsername: "SMTP login Name", paramParamMailTitleAnyChange: "Mailtitel für geänderte Zuweisung", paramParamMailTitleApprover: "Titel für Mails 'Genehmigung von Anforderungen'", paramParamMailTitleAssignment: "Mailtitel für geänderte Zuweisung", paramParamMailTitleAssignmentChange: "Mailtitel für geänderte Zuweisung", paramParamMailTitleAttachment: "Mailtitel für 'hinzugefügte Anhänge'", paramParamMailTitleDescription: "Mailtitel für geänderte Beschreibungen", paramParamMailTitleDirect: "Mailtitel, die manuell (Mail Schalter) versandt werden", paramParamMailTitleNew: "Mailtitel für 'hinzugefügte Elemente'", paramParamMailTitleNote: "Mailtitel für 'hinzugefügte Notizen'", paramParamMailTitleNoteChange: "Mailtitel für geänderte Notizen", paramParamMailTitleResponsible: "Mailtitel für 'geänderte Verantwortliche'", paramParamMailTitleResult: "Mailtitel für geänderte Ergebnisse", paramParamMailTitleStatus: "Mailtitel für 'Statusänderungen'", paramParamMailTitleUser: "Mailtitel an Nutzer", paramParamMemoryLimitForPDF: "Speicherlimit in MB für PDF-Erstellung", paramParamPasswordMinLength: "Mindestzahl von Zeichen für das Password", paramParamReportTempDirectory: "Temporäres Verzeichnis für Berichte", paramParamTopIconSize: "Größe der Icons in der Top-Menü-Anzeige", paramPasswordValidityDays: "Passwort Gültigkeit (in Tage)", paramPdfInNewWindow: "PDF export in neuem Fenster", paramPreserveUploadedFileName: "Original Dateinamen zusätzlich speichern", paramPrintHistory: "Druck Historie", paramPrintInNewWindow: "Druck in neuem Fenster", paramProjectIndentChar: "Zeichen für Einrückung bei Projekten", paramRealWorkOnlyForResponsible: "Nur Verantwortlicher arbeitet an Ticket", paramReferenceFormatNumber: "Anzahl Stellen für Referenznummernzähler", paramReferenceFormatPrefix: "Präfix Format für Referenz", paramRefreshUpdates: "Wiederhole Aktualisierung", paramRememberMe: "Erinnerung' Funktion erlauben", paramSetHandledOnRealWork: "Aufgabe auf 'begonnen' setzen, wenn Ist-Arbeit erfaßt", paramSetResponsibleIfNeeded: "Verantwortlichen automatisch setzen, wenn erforderlich", paramSetResponsibleIfSingle: "Verantwortlichen automatisch setzen, wenn einzige Ressource", paramStartAM: "Startzeit Vormittag", paramStartPage: "erste Seite", paramStartPM: "Startzeit Nachmittag", paramSwitchedMode: "Umschaltmodus", paramTheme: "Thema", paramVersionReferenceSuffix: "Anhang für Versions-Referenz", paramWorkUnit: "Einheit für Arbeit", passed: "erfolgreich", passedTestCaseRun: "Testfall als 'erfolgreich' markieren", password: "Passwort", passwordChanged: "Passwort geändert.", passwordReset: "Passwort zurückgesetzt auf '${1}'.<br/>Bitte sichern, damit die Änderung wirksam wird.", passwordResetMessage: "Passwort zurückgesetzt auf '${1}'.<br>Sie müssen es bei der ersten Anmeldung ändern.", Payment: "Zahlung", PaymentType: "Zahlungstyp", percent: "%", periodForTasks: "Zeitraum für Aufgabenauswahl", periodicEvery: "alle", periodicFor: "für", periodicityDaily: "täglich", periodicityMonthlyDay: "gleicher Tag in jeden Monat", periodicityMonthlyWeek: "gleiche Woche in jeden Monat", periodicityWeekly: "gleicher Tag in jeder Woche", periodicityYearly: "gleicher Tag in jedem Jahr", PeriodicMeeting: "Regelmäßige Besprechungen", periodicMonths: "Monate", periodicOn: "an", periodicTh: "ste", periodicTimes: "Wiederholungen", periodicTo: "bis", periodicUntil: "bis", periodicWeeks: "Wochen", periodScale: "Skala", planDatesNotSaved: "kein geplantes Datum gespeichert", planDatesSaved: "geplantes Datum gespeichert", planDone: "Planung wird kalkuliert in ${1} Sekunden.", planDoneWithLimits: "Folgende Aufgaben konnten nicht geplant werden, da die Resoucenzuordnung endet &#58;", planned: "geplant", PlannedCostOverAssignedCost: "Vergleich geplante Kosten mit zugewiesenen Kosten", PlannedCostOverValidatedCost: "Vergleich geplante Kosten mit bestätigten Kosten", plannedEndDate: "Berücksichtige geplantes Endedatum", plannedStartDate: "Berücksichtige geplantes Startdatum", PlannedWorkOverAssignedWork: "Geplante Arbeit verglichen mit zugewiesener Arbeit", PlannedWorkOverValidatedWork: "Geplante Arbeit verglichen mit bestätigter Arbeit", PlanningModeALAP: "so spät wie möglich", PlanningModeASAP: "so früh wie möglich", PlanningModeFDUR: "Feste Dauer", PlanningModeFIXED: "fester Meilenstein", PlanningModeFLOAT: "flexibler Meilenstein", PlanningModeFULL: "normal in ganzen Tagen", PlanningModeGROUP: "zusammenarbeiten", PlanningModeHALF: "normal in halben Tagen", PlanningModeREGUL: "normal zwischen Datum", planningRight: "Planung kalkulieren", Predecessor: "Vorgänger", PredefinedNote: "vordefinierte Notizen", print: "Druck", printList: "drucke die Liste", printPlanning: "drucke die Planung", Priority: "Priorität", private: "privat", Product: "Produkt", Profile: "Profile", profileAdministrator: "Administrator", profileExternalProjectLeader: "Externer Projektleiter", profileExternalTeamMember: "Externes Projektteammitglied", profileGuest: "Gastzugang", profileProjectLeader: "Projektleiter", profileSupervisor: "Vorgesetzter", profileTeamMember: "Projektteam", progress: "Fortschritt", Project: "Projekt", ProjectExpense: "Projektaufwand", ProjectExpenseType: "Projektaufwandstyp", projectListDisplayMode: "Projektlisten Anzeigemodus", projects: "Projekte", projectSelector: "Projekt", ProjectType: "Projekttyp", public: "öffentlich", Quality: "Qualitätslevel", quarter: "Quartal", Question: "Frage", QuestionType: "Fragentyp", quickSearch: "Suche", Quotation: "Angebot", QuotationType: "Angebotstyp", real: "Ist-Arbeit", RealWorkOverAssignedWork: "Vergleich Ist-Arbeit mit zugewiesener Arbeit", RealWorkOverValidatedWork: "Vergleich Ist-Arbeit mit bestätigter Arbeit", Recipient: "Empfänger", refreshUpdatesNo: "Nein (nur manuelle Aktualisierung)", refreshUpdatesYes: "Ja (automatische Aktualisierung)", rememberMe: "Erinnerung", rememberMETitle: "Erinnerungsfunktion nicht auf öffentlichen oder unsicheren Computern nutzen", remind: "erinnern", remindMeIn: "erinnere mich in", removeAffectation: "lösche diese Ressourcenzuordnung", removeAllFilters: "lösche alle Filterkriterien", removeApprover: "Lösche Genehmiger", removeAssignment: "lösche diese Zuordnung", removeAttachement: "lösche Anhang", removeDependency: "lösche diese Abhängigkeit", removeDependencyPredecessor: "lösche diesen Vorgänger", removeDependencySuccessor: "lösche diesen Nachfolger", removeDocumentVersion: "Lösche diese Version", removeExpenseDetail: "lösche Aufwandsdetail", removeFilter: "lösche diese Filterkriterien", removeLine: "Lösche diese Zeile", removeLink: "lösche dieses verbundenene Element", removeNote: "lösche diese Notiz", removeOrigin: "lösche Ursprung", removePhoto: "Foto löschen", removeResourceCost: "lösche diese Ressourcekosten", removeStoredFilter: "lösche diesen gespeicherten Filter", removeTestCaseRun: "Testfall löschen", removeVersionProject: "lösche Verbindung zwischen Version und Projekt", reportAudit: "Verbindungsprüfung", reportAvailabilityPlan: "Ressourcenverfügbarkeit - monatlich", reportAvailabilitySynthesis: "verfügbare Übersichten", reportBill: "Rechnungen", reportCategoryBill: "Fakturierung", reportCategoryCost: "Kosten", reportCategoryHistory: "Historie", reportCategoryMisc: "Verschiedenes", reportCategoryPlan: "Planung", reportCategoryRequirementTest: "Anforderungen & Tests", reportCategoryStatus: "Aktueller Status", reportCategoryTicket: "Tickets", reportCategoryWork: "Arbeit", reportCostDetail: "Kostenübersicht je Aktivität", reportCostMonthly: "Monatliche Kosten", reportExpenseCostTotal: "Gesamtaufwand und -kosten - monatlich", reportExpenseProject: "Projektaufwand - monatlich", reportExpenseResource: "Individueller Aufwand - monatlich", reportExpenseTotal: "Gesamtaufwand - monatlich", reportExportMSProject: "Export MS-Project XML Format", reportFacture: "Rechnungen", reportGlobalWorkPlanningMonthly: "Arbeitsplan - monatlich", reportGlobalWorkPlanningWeekly: "Arbeitsplan - wöchentlich", reportHistoryDetail: "Historie für ein Element", reportHistoryDeteled: "Gelöschte Positionen", reportNoData: "Keine Daten zur Anzeige verfügbar", reportOpportunityPlan: "Chancen Plan", reportPlanActivityMonthly: "Planung Projekten/Aktivitäten/Ressourcen - monatlich", reportPlanColoredMonthly: "Ressourcenplanung - in Farbe - monatlich", reportPlanDetail: "Aktivitätenplanung - detailliert - monatlich", reportPlanGantt: "Gantt", reportPlannedDates: "Sichere geplantes Datum in", reportPlanProjectMonthly: "Projektplanung - detailliert - monatlich", reportPlanResourceMonthly: "Ressourcenplanung - detailliert - monatlich", reportPortfolioGantt: "Portfolio Ganttplanung", reportPrint: "Drucke Bericht", reportPrintCsv: "Export im CSV Format", reportPrintPdf: "Export im PDF Format", reportProductTest: "Test Produktabdeckung", reportProductTestDetail: "Testfall Details", reportProject: "Projekt Dashboard", reportRequirementTest: "Test Anforderungsabdeckung", reportRiskManagementPlan: "Risiko Management Plan", Reports: "Berichte", reportShow: "Bericht anzeigen", reportStatusAll: "Status der gesamten Arbeit", reportStatusOngoing: "Status der laufenden Arbeit", reportTermMonthly: "Monatliche Konditionen", reportTermTitle: "Setze Stichtage für Periode", reportTermWeekly: "Wöchentliche Konditionen", reportTestSession: "Testplan Zusammenfassung", reportTicketGlobalCrossReport: "Tickets - je Qualifikation - gesamt", reportTicketGlobalSynthesis: "Tickets - offen - gesamt", reportTicketMonthlyCrossReport: "Tickets - je Qualifikation - monatlich", reportTicketMonthlySynthesis: "Tickets - offen - monatlich", reportTicketWeeklyCrossReport: "Tickets - je Qualifikation - wöchentlich", reportTicketWeeklySynthesis: "Tickets - offen - wöchentlich", reportTicketYearly: "Tickets - jährlich", reportTicketYearlyByType: "Tickets - je Typ - jährlich", reportTicketYearlyCrossReport: "Tickets - je Qualifikation - jährlich", reportTicketYearlySynthesis: "Tickets - offen - jährlich", reportVersionDetail: "Versionsdetails", reportVersionStatus: "Versionsstatus", reportWorkDetailMonthly: "Arbeit - detailliert - je Ressource - monatlich", reportWorkDetailWeekly: "Arbeit - detailliert - je Ressource - wöchentlich", reportWorkDetailYearly: "Arbeit - detailliert - je Ressource - jährlich", reportWorkMonthly: "Arbeit - monatlich", reportWorkPerActivity: "Arbeitsübersicht je Aktivität", reportWorkPlan: "Arbeitsübersicht je Aktivität", reportWorkWeekly: "Arbeit - wöchentlich", reportWorkYearly: "Arbeit - jährlich", Requirement: "Anforderung", RequirementType: "Anforderungstyp", requirementUnlockRight: "Entsperre alle Anforderungen", resetColor: "zurücksetzen", resetPassword: "Passwort zurücksetzen", Resource: "Ressource", ResourceCost: "Ressourcekosten", resourcePlanningRight: "Zugriff auf Ressourcenplanung für andere", resources: "Ressourcen", responsibleChange: "Änderung des Verantwortlichen", resultChange: "Ergebnis geändert", resultClosed: "geschlossen", resultCopied: "kopiert als", resultDeleted: "gelöscht", resultError: "Elemente mit Fehler", resultInserted: "eingefügt", resultOk: "Elemente geändert", resultSave: "gesichert", resultUpdated: "geändert", resultWarning: "Elemente nicht geändert", rightClickToCopy: "Rechts click und Kopierlink wählen oder click and [CTRL]+C um den Direktlink dieses Objektes zu kopieren", Risk: "Risiko", RiskLevel: "Risiko Ebene", RiskType: "Risikotyp", Role: "Funktion", run: "Start", running: "läuft", Saturday: "Samstag", saveDates: "sichere die Daten", saveFilter: "Sichere diesen Filter", savePlannedDates: "speichere geplantes Datum in gefordertes und bestätigtes Datum", second: "Sekunde", sectionAbacus: "Rechenhilfe", sectionActiveFilter: "Aktiver Filter", sectionAddress: "Adresses", sectionAffectations: "Ressourcenzuordnungen", sectionAlerts: "Alarm Verwaltung", sectionAnswer: "Antwort", sectionApprovers: "Genehmiger", sectionAssignment: "Zuordnung", sectionAssignmentManagement: "Zuweisungsmanagement", sectionAttachements: "Anhänge", sectionBehavior: "Verhalten", sectionBilling: "Rechnungsstellung", sectionBillLines: "Rechnungspositionen", sectionButtons: "Schalter anzeigen", sectionCalendar: "Kalendertage", sectionChecklistLines: "Checklistenzeilen", sectionComboDetail: "Schalter anzeigen 'Detail-Kombinationen'", sectionConnectionStatus: "Verbindungsstatus", sectionContacts: "Kontakte", sectionCron: "Steuerung automatisierte Services (CRON)", sectionDailyHours: "Tägliche Arbeitszeit", sectionDates: "Datum", sectionDebug: "Fehlersuche", sectionDescription: "Beschreibung", sectionDetail: "Detail", sectionDisplay: "Anzeige", sectionDisplayParameter: "Anzeige-Parameter", sectionDocument: "Dokument", sectionDocumentUnlock: "Dokument entsperren", sectionFiles: "Dateien und Verzeichnisse", sectionFunctionCost: "Funktion & Kosten", sectionIBAN: "Internationale Bank-Konto-Nummer (IBAN)", sectionIHM: "Standard-Bildschirmanzeige", sectionImputation: "Ist-Arbeit-Buchung", sectionImputationDiary: "Ist-Arbeit-Buchung und Terminkalender", sectionInternalAlert: "Empfänger interner Alarme", sectionLdap: "LDAP Verwaltung der Parameter", sectionLink: "verbundenes Element", sectionLinkAction: "verbundene Aktion", sectionLinkDecision: "gefällte Entscheidungen", sectionLinkIssue: "verbundene Probleme", sectionLinkMeeting: "diskutiert in Besprechung", sectionLinkQuestion: "neue oder gelöste Fragen", sectionLinkRisk: "verbundene Risiken", sectionLocalization: "Lokale Einstellung", sectionLock: "Sperre", sectionMail: "E-Mail-Versand", sectionMailDescription: "Mailbeschreibung", sectionMailItem: "betroffener Punkt", sectionMailText: "Text des Mails", sectionMailTitle: "Haupttitel", sectionMembers: "Teammitglieder", sectionMessage: "Meldung", sectionMiscellaneous: "Verschiedenes", sectionNotes: "Notizen", sectionObjectDetail: "Details der Elemente", sectionPassword: "Password", sectionPeriodicity: "Wiederholung", sectionPlanning: "Planung", sectionPlanningRight: "Planungskalkulation", sectionPredecessor: "Vorgänger Element", sectionPrice: "Festpreis", sectionPrintExport: "Druck & Export Parameter", sectionProgress: "Fortschritt", sectionProjects: "Projekte", sectionReferenceFormat: "Format für Referenznummerierung", sectionResponsible: "Verantwortliche", sectionSendMail: "Mailadresse", sectionStoredFilters: "Gespeicherte Filter", sectionSubprojects: "Teilprojekte", sectionSuccessor: "Nachfolger Element", sectionTestCaseRun: "Testfall-Durchläufe", sectionTreatment: "Behandlung", sectionTrigger: "Auslöserelement für diese Kondition", sectionUnlock: "Entsperre Positionen", sectionUserAndPassword: "Nutzer und Passwort", sectionValidation: "Überprüfung", sectionVersion: "Versionen", sectionVersionproject_projects: "verbundene Projekte", sectionVersionproject_versions: "verbundenene Versionen", sectionVersions: "Produkt Versionen", sectionWorkCost: "Arbeit und Kosten anzeigen", sectionWorkflowDiagram: "Workflow Diagramm", sectionWorkflowStatus: "Vorgaben für Änderungen von einem zum anderen Status", sectionWorkUnit: "Einheit für Arbeit", sectionYear: "Jahr", selectedItemsCount: "Anzahl gewählter Elemente", selectProjectToPlan: "Sie müssen ein Projekt wählen", selectStoredFilter: "Wähle diesen gespeicherten Filter", send: "Senden", sendAlert: "Sende einen internen Alarm", sendInfoToApprovers: "Erinnerungs-Mail an Genehmiger schicken", sendInfoToUser: "Sende Informationen zum Nutzer", sendMailToAttendees: "E-Mail-Einladung", sendToPrinter: "Sende Dokument zum Drucker", sentAlertTo: "Alarm versandt an ${1} Nutzer", sentSinceMore: "versandt vor mehr als", September: "September", sequential: "sequenziell", setApplicationToClosed: "Schließe Applikation", setApplicationToOpen: "Starte Applikation", Severity: "Auswirkung", shortDay: "T", shortHour: "S", shortMinute: "Mn", shortMonth: "M", shortQuarter: "Q", shortSecond: "S", shortWeek: "W", shortYear: "J", showDetail: "Suche / Anzeige", showDirectAccess: "Gehe zu diesem Element", showIdleElements: "Zeige inaktive Elemente", showInToday: "Füge Report zu Heute-Übersicht", showLeftWork: "Zeige offene Arbeit rechts des Ganttbalkens", showPlannedWork: "Zeige geplante Arbeit", showProjectLevel: "Zeige Projektebene über Aktivitäten", showResources: "Zeige Ressourcen rechts vom Ganttbalken", showWbs: "Zeige PSP mit Namen", Software: "Software", sortAsc: "aufsteigend", sortDesc: "absteigend", sortFilter: "sortieren", sqlError: "SQL Fehler", startWork: "Starte Arbeit", Status: "Status", StatusMail: "Mail nach Statusänderung", statusMustChangeCancelled: "'abgebrochen' muss durch Statusänderung erfolgen", statusMustChangeDone: "'erledigt' muss durch Statusänderung erfolgen", statusMustChangeHandled: "'bearbeitet' muss durch Statusänderung erfolgen", statusMustChangeIdle: "'abgeschlossen' muss durch Statusänderung erfolgen", stop: "Stopp", stopped: "gestoppt", stopWork: "Stoppe Arbeit", storedFilters: "Gespeicherte Filter", submittedWorkPeriod: "abgegeben am <br/>${1}", submitWorkPeriod: "Ist-Arbeit melden", subProjects: "Teilprojekte", Successor: "Nachfolger", sum: "Summe", Sunday: "Sonntag", targetValue: "Zielwert", Team: "Team", team: "Team", Term: "Kondition", TestCase: "Testfall", TestCaseRun: "Testfall-Durchlauf", TestCaseType: "Testfalltyp", TestSession: "Testplan", TestSessionType: "Testplantyp", themeBlue: "dunkelblau", themeBlueContrast: "kontrastierendes blau", themeBlueLight: "hellblau", themeGreen: "dunkelgrün", themeGreenContrast: "kontrastierendes grün", themeGreenLight: "hellgrün", themeGrey: "dunkelgrau", themeGreyContrast: "kontrastierendes grau", themeGreyLight: "hellgrau", themeOrange: "dunkelorange", themeOrangeContrast: "kontrastierendes orange", themeOrangeLight: "hellorange", themeProjectom: "Projectom", themeProjectOrRIA: "ProjecQtOr", themeProjectOrRIAContrasted: "ProjecQtOr kontrastierend", themeProjectOrRIALight: "ProjecQtOr hell", themeProjeQtOr: "ProjeQtOr", themeProjeQtOrDark: "ProjeQtOr Dark", themeProjeQtOrEarth: "ProjeQtOr Earth", themeProjeQtOrFire: "ProjeQtOr Fire", themeProjeQtOrForest: "ProjeQtOr Forest", themeProjeQtOrLight: "ProjeQtOr Light", themeProjeQtOrWater: "ProjeQtOr Water", themeProjeQtOrWine: "ProjeQtOr Wine", themeRandom: "zufällig", themeRed: "dunkelrot", themeRedContrast: "kontrastierendes rot", themeRedLight: "hellrot", themeWhite: "schwarz & weiß", Thursday: "Donnerstag", Ticket: "Ticket", TicketDelay: "Verspätung für Tickets", TicketSimple: "Ticket", TicketType: "Tickettyp", titleCountAll: "alle", titleCountNotClosed: "nicht geschlossen", titleCountScope: "Bereich gezählte Elemente:", titleCountTodo: "zu erledigen", titleNbAll: "gesamt", titleNbClosed: "geschlossen", titleNbDone: "erledigt", titleNbTodo: "zu erledigen", titleResetList: "Setze Anzeige auf Standard zurück", to: "an", today: "Heute", Today: "Element von Heute-Übersicht", todayAssignedTasks: "Aufgabe zugewiesen an", todayIs: "Heute ist", todayIssuerRequestorTasks: "Aussteller oder Anforderer der Arbeit", todayProjects: "Projekte", todayProjectsTasks: "Alle Projekt-Arbeiten zugewiesen an", todayResponsibleTasks: "Verantwortlicher d. Arbeit", Trend: "Trend", Tuesday: "Dienstag", undefinedValue: "nicht definiert", unlockDocument: "Entsperre Dokument", unlockRequirement: "Entsperre Anforderung", unSubmitWorkPeriod: "Ist-Arbeit zurückziehen", unValidateWorkPeriod: "Ist-Arbeit ablehnen", updatedReference: "Referenz für Element '${1}' geändert", updateInitialDates: "gefordertes Datum", updateReference: "Ändere Referenz für", updateValidatedDates: "bestätigtes Datum", Urgency: "Dringlichkeit", User: "Nutzer", userMailMessage: "Ihre Anmeldung zu ProjecQtOr ist '${1}'.<br/>${2}<br/>Bei Problemen wenden Sie sich bitte an Ihren Administrator ${3}.", userMailTitle: "[ProjecQtOr Meldung] Ihre Zugangsdaten", validatedEndDate: "Berücksichtige bestätigtes Endedatum", validatedStartDate: "Berücksichtige bestätigtes Startdatum", validatedWorkPeriod: "geprüft durch ${2} am <br/>${1}", validatePassword: "Überprüfen Sie Ihr Passwort", validateWorkPeriod: "Arbeit gutheißen", valueNotSelected: "Wert kann nicht leer sein", Version: "Version", versionDraftUpdate: "Entwurf", versionMajorUpdate: "wesentlich", versionMinorUpdate: "geringfügig", versionNoUpdate: "kein", VersionProject: "Verbindung Projekt-Version", versions: "Versionen", visibilityScopeAll: "Alle sichtbaren", visibilityScopeNo: "Keine anzeigen", visibilityScopeValid: "Nur bestätigte anzeigen", WARNING: "Warnung", warningValue: "Warnungswert", Wednesday: "Mittwoch", week: "Woche", welcomeMessage: "Willkommen", Work: "Arbeit", workAccess: "Arbeit anzeigen", Workflow: "Workflow", workflowParameters: "Wähle Status anzeigen / ausblenden", workStarted: "Arbeit gestartet", workStartedAt: "gestartet um ${1}", workStartedBy: "gestartet durch ${1}", workStartedSince: "gestartet seit ${1} Tag(en)", workStopped: "Arbeit gestoppt", workValidate: "Ist-Arbeit gutheißen", wrongMaintenanceUser: "Upgrade wird gerade durchgeführt.<br/>Nur der Administrator kann sich verbinden.", xlsxFile: "xlsx Datei (Excel 2010)", year: "Jahr", currentLocaleOfFile: "de" }
nikochan2k/projeqtor-ja
tool/i18n/nls/de/lang.js
JavaScript
gpl-3.0
84,654
// Core functionality inspired by http://www.ghosthorses.co.uk/production-diary/super-simple-responsive-progress-bar/ jQuery(function($) { moveProgressBar(); $(window).resize(function() { moveProgressBar(); }); function moveProgressBar() { $('.rprogress-wrap').each(function(i, e) { var getPercent = ($(e).data('progress-percent') / 100); var getProgressWrapWidth = $(e).width(); var progressTotal = getPercent * getProgressWrapWidth; var animationLength = $(e).data('speed'); $(e).find('.rprogress-bar').stop().animate({ left: progressTotal }, animationLength); }); } });
wp-plugins/responsive-progress-bar
assets/js/responsive-progressbar.js
JavaScript
gpl-3.0
642
import Modal from '../../src/modal' import EventHandler from '../../src/dom/event-handler' import ScrollBarHelper from '../../src/util/scrollbar' /** Test helpers */ import { clearBodyAndDocument, clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' describe('Modal', () => { let fixtureEl beforeAll(() => { fixtureEl = getFixture() }) afterEach(() => { clearFixture() clearBodyAndDocument() document.body.classList.remove('modal-open') document.querySelectorAll('.modal-backdrop') .forEach(backdrop => { backdrop.remove() }) }) beforeEach(() => { clearBodyAndDocument() }) describe('VERSION', () => { it('should return plugin version', () => { expect(Modal.VERSION).toEqual(jasmine.any(String)) }) }) describe('Default', () => { it('should return plugin default config', () => { expect(Modal.Default).toEqual(jasmine.any(Object)) }) }) describe('DATA_KEY', () => { it('should return plugin data key', () => { expect(Modal.DATA_KEY).toEqual('bs.modal') }) }) describe('constructor', () => { it('should take care of element either passed as a CSS selector or DOM element', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modalBySelector = new Modal('.modal') const modalByElement = new Modal(modalEl) expect(modalBySelector._element).toEqual(modalEl) expect(modalByElement._element).toEqual(modalEl) }) }) describe('toggle', () => { it('should call ScrollBarHelper to handle scrollBar on body', done => { fixtureEl.innerHTML = [ '<div class="modal"><div class="modal-dialog"></div></div>' ].join('') spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough() spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough() const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('shown.bs.modal', () => { expect(ScrollBarHelper.prototype.hide).toHaveBeenCalled() modal.toggle() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(ScrollBarHelper.prototype.reset).toHaveBeenCalled() done() }) modal.toggle() }) }) describe('show', () => { it('should show a modal', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('show.bs.modal', event => { expect(event).toBeDefined() }) modalEl.addEventListener('shown.bs.modal', () => { expect(modalEl.getAttribute('aria-modal')).toEqual('true') expect(modalEl.getAttribute('role')).toEqual('dialog') expect(modalEl.getAttribute('aria-hidden')).toBeNull() expect(modalEl.style.display).toEqual('block') expect(document.querySelector('.modal-backdrop')).not.toBeNull() done() }) modal.show() }) it('should show a modal without backdrop', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { backdrop: false }) modalEl.addEventListener('show.bs.modal', event => { expect(event).toBeDefined() }) modalEl.addEventListener('shown.bs.modal', () => { expect(modalEl.getAttribute('aria-modal')).toEqual('true') expect(modalEl.getAttribute('role')).toEqual('dialog') expect(modalEl.getAttribute('aria-hidden')).toBeNull() expect(modalEl.style.display).toEqual('block') expect(document.querySelector('.modal-backdrop')).toBeNull() done() }) modal.show() }) it('should show a modal and append the element', done => { const modalEl = document.createElement('div') const id = 'dynamicModal' modalEl.setAttribute('id', id) modalEl.classList.add('modal') modalEl.innerHTML = '<div class="modal-dialog"></div>' const modal = new Modal(modalEl) modalEl.addEventListener('shown.bs.modal', () => { const dynamicModal = document.getElementById(id) expect(dynamicModal).not.toBeNull() dynamicModal.remove() done() }) modal.show() }) it('should do nothing if a modal is shown', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(EventHandler, 'trigger') modal._isShown = true modal.show() expect(EventHandler.trigger).not.toHaveBeenCalled() }) it('should do nothing if a modal is transitioning', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(EventHandler, 'trigger') modal._isTransitioning = true modal.show() expect(EventHandler.trigger).not.toHaveBeenCalled() }) it('should not fire shown event when show is prevented', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('show.bs.modal', event => { event.preventDefault() const expectedDone = () => { expect().nothing() done() } setTimeout(expectedDone, 10) }) modalEl.addEventListener('shown.bs.modal', () => { throw new Error('shown event triggered') }) modal.show() }) it('should be shown after the first call to show() has been prevented while fading is enabled ', done => { fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) let prevented = false modalEl.addEventListener('show.bs.modal', event => { if (!prevented) { event.preventDefault() prevented = true setTimeout(() => { modal.show() }) } }) modalEl.addEventListener('shown.bs.modal', () => { expect(prevented).toBeTrue() expect(modal._isAnimated()).toBeTrue() done() }) modal.show() }) it('should set is transitioning if fade class is present', done => { fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('show.bs.modal', () => { setTimeout(() => { expect(modal._isTransitioning).toEqual(true) }) }) modalEl.addEventListener('shown.bs.modal', () => { expect(modal._isTransitioning).toEqual(false) done() }) modal.show() }) it('should close modal when a click occurred on data-bs-dismiss="modal" inside modal', done => { fixtureEl.innerHTML = [ '<div class="modal fade">', ' <div class="modal-dialog">', ' <div class="modal-header">', ' <button type="button" data-bs-dismiss="modal"></button>', ' </div>', ' </div>', '</div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]') const modal = new Modal(modalEl) spyOn(modal, 'hide').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { btnClose.click() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(modal.hide).toHaveBeenCalled() done() }) modal.show() }) it('should close modal when a click occurred on a data-bs-dismiss="modal" with "bs-target" outside of modal element', done => { fixtureEl.innerHTML = [ '<button type="button" data-bs-dismiss="modal" data-bs-target="#modal1"></button>', '<div id="modal1" class="modal fade">', ' <div class="modal-dialog">', ' </div>', '</div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]') const modal = new Modal(modalEl) spyOn(modal, 'hide').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { btnClose.click() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(modal.hide).toHaveBeenCalled() done() }) modal.show() }) it('should set .modal\'s scroll top to 0', done => { fixtureEl.innerHTML = [ '<div class="modal fade">', ' <div class="modal-dialog">', ' </div>', '</div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('shown.bs.modal', () => { expect(modalEl.scrollTop).toEqual(0) done() }) modal.show() }) it('should set modal body scroll top to 0 if modal body do not exists', done => { fixtureEl.innerHTML = [ '<div class="modal fade">', ' <div class="modal-dialog">', ' <div class="modal-body"></div>', ' </div>', '</div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const modalBody = modalEl.querySelector('.modal-body') const modal = new Modal(modalEl) modalEl.addEventListener('shown.bs.modal', () => { expect(modalBody.scrollTop).toEqual(0) done() }) modal.show() }) it('should not trap focus if focus equal to false', done => { fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { focus: false }) spyOn(modal._focustrap, 'activate').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { expect(modal._focustrap.activate).not.toHaveBeenCalled() done() }) modal.show() }) it('should add listener when escape touch is pressed', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(modal, 'hide').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { const keydownEscape = createEvent('keydown') keydownEscape.key = 'Escape' modalEl.dispatchEvent(keydownEscape) }) modalEl.addEventListener('hidden.bs.modal', () => { expect(modal.hide).toHaveBeenCalled() done() }) modal.show() }) it('should do nothing when the pressed key is not escape', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(modal, 'hide') const expectDone = () => { expect(modal.hide).not.toHaveBeenCalled() done() } modalEl.addEventListener('shown.bs.modal', () => { const keydownTab = createEvent('keydown') keydownTab.key = 'Tab' modalEl.dispatchEvent(keydownTab) setTimeout(expectDone, 30) }) modal.show() }) it('should adjust dialog on resize', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(modal, '_adjustDialog').and.callThrough() const expectDone = () => { expect(modal._adjustDialog).toHaveBeenCalled() done() } modalEl.addEventListener('shown.bs.modal', () => { const resizeEvent = createEvent('resize') window.dispatchEvent(resizeEvent) setTimeout(expectDone, 10) }) modal.show() }) it('should not close modal when clicking outside of modal-content if backdrop = false', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { backdrop: false }) const shownCallback = () => { setTimeout(() => { expect(modal._isShown).toEqual(true) done() }, 10) } modalEl.addEventListener('shown.bs.modal', () => { modalEl.click() shownCallback() }) modalEl.addEventListener('hidden.bs.modal', () => { throw new Error('Should not hide a modal') }) modal.show() }) it('should not close modal when clicking outside of modal-content if backdrop = static', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { backdrop: 'static' }) const shownCallback = () => { setTimeout(() => { expect(modal._isShown).toEqual(true) done() }, 10) } modalEl.addEventListener('shown.bs.modal', () => { modalEl.click() shownCallback() }) modalEl.addEventListener('hidden.bs.modal', () => { throw new Error('Should not hide a modal') }) modal.show() }) it('should close modal when escape key is pressed with keyboard = true and backdrop is static', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { backdrop: 'static', keyboard: true }) const shownCallback = () => { setTimeout(() => { expect(modal._isShown).toEqual(false) done() }, 10) } modalEl.addEventListener('shown.bs.modal', () => { const keydownEscape = createEvent('keydown') keydownEscape.key = 'Escape' modalEl.dispatchEvent(keydownEscape) shownCallback() }) modal.show() }) it('should not close modal when escape key is pressed with keyboard = false', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { keyboard: false }) const shownCallback = () => { setTimeout(() => { expect(modal._isShown).toEqual(true) done() }, 10) } modalEl.addEventListener('shown.bs.modal', () => { const keydownEscape = createEvent('keydown') keydownEscape.key = 'Escape' modalEl.dispatchEvent(keydownEscape) shownCallback() }) modalEl.addEventListener('hidden.bs.modal', () => { throw new Error('Should not hide a modal') }) modal.show() }) it('should not overflow when clicking outside of modal-content if backdrop = static', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog" style="transition-duration: 20ms;"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { backdrop: 'static' }) modalEl.addEventListener('shown.bs.modal', () => { modalEl.click() setTimeout(() => { expect(modalEl.clientHeight).toEqual(modalEl.scrollHeight) done() }, 20) }) modal.show() }) it('should not queue multiple callbacks when clicking outside of modal-content and backdrop = static', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog" style="transition-duration: 50ms;"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl, { backdrop: 'static' }) modalEl.addEventListener('shown.bs.modal', () => { const spy = spyOn(modal, '_queueCallback').and.callThrough() modalEl.click() modalEl.click() setTimeout(() => { expect(spy).toHaveBeenCalledTimes(1) done() }, 20) }) modal.show() }) it('should trap focus', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(modal._focustrap, 'activate').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { expect(modal._focustrap.activate).toHaveBeenCalled() done() }) modal.show() }) }) describe('hide', () => { it('should hide a modal', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('shown.bs.modal', () => { modal.hide() }) modalEl.addEventListener('hide.bs.modal', event => { expect(event).toBeDefined() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(modalEl.getAttribute('aria-modal')).toBeNull() expect(modalEl.getAttribute('role')).toBeNull() expect(modalEl.getAttribute('aria-hidden')).toEqual('true') expect(modalEl.style.display).toEqual('none') expect(document.querySelector('.modal-backdrop')).toBeNull() done() }) modal.show() }) it('should close modal when clicking outside of modal-content', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('shown.bs.modal', () => { modalEl.click() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(modalEl.getAttribute('aria-modal')).toBeNull() expect(modalEl.getAttribute('role')).toBeNull() expect(modalEl.getAttribute('aria-hidden')).toEqual('true') expect(modalEl.style.display).toEqual('none') expect(document.querySelector('.modal-backdrop')).toBeNull() done() }) modal.show() }) it('should do nothing is the modal is not shown', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modal.hide() expect().nothing() }) it('should do nothing is the modal is transitioning', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modal._isTransitioning = true modal.hide() expect().nothing() }) it('should not hide a modal if hide is prevented', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) modalEl.addEventListener('shown.bs.modal', () => { modal.hide() }) const hideCallback = () => { setTimeout(() => { expect(modal._isShown).toEqual(true) done() }, 10) } modalEl.addEventListener('hide.bs.modal', event => { event.preventDefault() hideCallback() }) modalEl.addEventListener('hidden.bs.modal', () => { throw new Error('should not trigger hidden') }) modal.show() }) it('should release focus trap', done => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(modal._focustrap, 'deactivate').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { modal.hide() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(modal._focustrap.deactivate).toHaveBeenCalled() done() }) modal.show() }) }) describe('dispose', () => { it('should dispose a modal', () => { fixtureEl.innerHTML = '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) const focustrap = modal._focustrap spyOn(focustrap, 'deactivate').and.callThrough() expect(Modal.getInstance(modalEl)).toEqual(modal) spyOn(EventHandler, 'off') modal.dispose() expect(Modal.getInstance(modalEl)).toBeNull() expect(EventHandler.off).toHaveBeenCalledTimes(3) expect(focustrap.deactivate).toHaveBeenCalled() }) }) describe('handleUpdate', () => { it('should call adjust dialog', () => { fixtureEl.innerHTML = '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>' const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) spyOn(modal, '_adjustDialog') modal.handleUpdate() expect(modal._adjustDialog).toHaveBeenCalled() }) }) describe('data-api', () => { it('should toggle modal', done => { fixtureEl.innerHTML = [ '<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal"></button>', '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') modalEl.addEventListener('shown.bs.modal', () => { expect(modalEl.getAttribute('aria-modal')).toEqual('true') expect(modalEl.getAttribute('role')).toEqual('dialog') expect(modalEl.getAttribute('aria-hidden')).toBeNull() expect(modalEl.style.display).toEqual('block') expect(document.querySelector('.modal-backdrop')).not.toBeNull() setTimeout(() => trigger.click(), 10) }) modalEl.addEventListener('hidden.bs.modal', () => { expect(modalEl.getAttribute('aria-modal')).toBeNull() expect(modalEl.getAttribute('role')).toBeNull() expect(modalEl.getAttribute('aria-hidden')).toEqual('true') expect(modalEl.style.display).toEqual('none') expect(document.querySelector('.modal-backdrop')).toBeNull() done() }) trigger.click() }) it('should not recreate a new modal', done => { fixtureEl.innerHTML = [ '<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal"></button>', '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const modal = new Modal(modalEl) const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') spyOn(modal, 'show').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { expect(modal.show).toHaveBeenCalled() done() }) trigger.click() }) it('should prevent default when the trigger is <a> or <area>', done => { fixtureEl.innerHTML = [ '<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>', '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') spyOn(Event.prototype, 'preventDefault').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { expect(modalEl.getAttribute('aria-modal')).toEqual('true') expect(modalEl.getAttribute('role')).toEqual('dialog') expect(modalEl.getAttribute('aria-hidden')).toBeNull() expect(modalEl.style.display).toEqual('block') expect(document.querySelector('.modal-backdrop')).not.toBeNull() expect(Event.prototype.preventDefault).toHaveBeenCalled() done() }) trigger.click() }) it('should focus the trigger on hide', done => { fixtureEl.innerHTML = [ '<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>', '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') spyOn(trigger, 'focus') modalEl.addEventListener('shown.bs.modal', () => { const modal = Modal.getInstance(modalEl) modal.hide() }) const hideListener = () => { setTimeout(() => { expect(trigger.focus).toHaveBeenCalled() done() }, 20) } modalEl.addEventListener('hidden.bs.modal', () => { hideListener() }) trigger.click() }) it('should not prevent default when a click occurred on data-bs-dismiss="modal" where tagName is DIFFERENT than <a> or <area>', done => { fixtureEl.innerHTML = [ '<div class="modal">', ' <div class="modal-dialog">', ' <button type="button" data-bs-dismiss="modal"></button>', ' </div>', '</div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const btnClose = fixtureEl.querySelector('button[data-bs-dismiss="modal"]') const modal = new Modal(modalEl) spyOn(Event.prototype, 'preventDefault').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { btnClose.click() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(Event.prototype.preventDefault).not.toHaveBeenCalled() done() }) modal.show() }) it('should prevent default when a click occurred on data-bs-dismiss="modal" where tagName is <a> or <area>', done => { fixtureEl.innerHTML = [ '<div class="modal">', ' <div class="modal-dialog">', ' <a type="button" data-bs-dismiss="modal"></a>', ' </div>', '</div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const btnClose = fixtureEl.querySelector('a[data-bs-dismiss="modal"]') const modal = new Modal(modalEl) spyOn(Event.prototype, 'preventDefault').and.callThrough() modalEl.addEventListener('shown.bs.modal', () => { btnClose.click() }) modalEl.addEventListener('hidden.bs.modal', () => { expect(Event.prototype.preventDefault).toHaveBeenCalled() done() }) modal.show() }) it('should not focus the trigger if the modal is not visible', done => { fixtureEl.innerHTML = [ '<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal" style="display: none;"></a>', '<div id="exampleModal" class="modal" style="display: none;"><div class="modal-dialog"></div></div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') spyOn(trigger, 'focus') modalEl.addEventListener('shown.bs.modal', () => { const modal = Modal.getInstance(modalEl) modal.hide() }) const hideListener = () => { setTimeout(() => { expect(trigger.focus).not.toHaveBeenCalled() done() }, 20) } modalEl.addEventListener('hidden.bs.modal', () => { hideListener() }) trigger.click() }) it('should not focus the trigger if the modal is not shown', done => { fixtureEl.innerHTML = [ '<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>', '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>' ].join('') const modalEl = fixtureEl.querySelector('.modal') const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') spyOn(trigger, 'focus') const showListener = () => { setTimeout(() => { expect(trigger.focus).not.toHaveBeenCalled() done() }, 10) } modalEl.addEventListener('show.bs.modal', event => { event.preventDefault() showListener() }) trigger.click() }) it('should call hide first, if another modal is open', done => { fixtureEl.innerHTML = [ '<button data-bs-toggle="modal" data-bs-target="#modal2"></button>', '<div id="modal1" class="modal fade"><div class="modal-dialog"></div></div>', '<div id="modal2" class="modal"><div class="modal-dialog"></div></div>' ].join('') const trigger2 = fixtureEl.querySelector('button') const modalEl1 = document.querySelector('#modal1') const modalEl2 = document.querySelector('#modal2') const modal1 = new Modal(modalEl1) modalEl1.addEventListener('shown.bs.modal', () => { trigger2.click() }) modalEl1.addEventListener('hidden.bs.modal', () => { expect(Modal.getInstance(modalEl2)).not.toBeNull() expect(modalEl2.classList.contains('show')).toBeTrue() done() }) modal1.show() }) }) describe('jQueryInterface', () => { it('should create a modal', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') jQueryMock.fn.modal = Modal.jQueryInterface jQueryMock.elements = [div] jQueryMock.fn.modal.call(jQueryMock) expect(Modal.getInstance(div)).not.toBeNull() }) it('should create a modal with given config', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') jQueryMock.fn.modal = Modal.jQueryInterface jQueryMock.elements = [div] jQueryMock.fn.modal.call(jQueryMock, { keyboard: false }) spyOn(Modal.prototype, 'constructor') expect(Modal.prototype.constructor).not.toHaveBeenCalledWith(div, { keyboard: false }) const modal = Modal.getInstance(div) expect(modal).not.toBeNull() expect(modal._config.keyboard).toBe(false) }) it('should not re create a modal', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') const modal = new Modal(div) jQueryMock.fn.modal = Modal.jQueryInterface jQueryMock.elements = [div] jQueryMock.fn.modal.call(jQueryMock) expect(Modal.getInstance(div)).toEqual(modal) }) it('should throw error on undefined method', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') const action = 'undefinedMethod' jQueryMock.fn.modal = Modal.jQueryInterface jQueryMock.elements = [div] expect(() => { jQueryMock.fn.modal.call(jQueryMock, action) }).toThrowError(TypeError, `No method named "${action}"`) }) it('should call show method', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') const modal = new Modal(div) jQueryMock.fn.modal = Modal.jQueryInterface jQueryMock.elements = [div] spyOn(modal, 'show') jQueryMock.fn.modal.call(jQueryMock, 'show') expect(modal.show).toHaveBeenCalled() }) it('should not call show method', () => { fixtureEl.innerHTML = '<div class="modal" data-bs-show="false"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') jQueryMock.fn.modal = Modal.jQueryInterface jQueryMock.elements = [div] spyOn(Modal.prototype, 'show') jQueryMock.fn.modal.call(jQueryMock) expect(Modal.prototype.show).not.toHaveBeenCalled() }) }) describe('getInstance', () => { it('should return modal instance', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') const modal = new Modal(div) expect(Modal.getInstance(div)).toEqual(modal) expect(Modal.getInstance(div)).toBeInstanceOf(Modal) }) it('should return null when there is no modal instance', () => { fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>' const div = fixtureEl.querySelector('div') expect(Modal.getInstance(div)).toBeNull() }) }) describe('getOrCreateInstance', () => { it('should return modal instance', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') const modal = new Modal(div) expect(Modal.getOrCreateInstance(div)).toEqual(modal) expect(Modal.getInstance(div)).toEqual(Modal.getOrCreateInstance(div, {})) expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal) }) it('should return new instance when there is no modal instance', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') expect(Modal.getInstance(div)).toEqual(null) expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal) }) it('should return new instance when there is no modal instance with given configuration', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') expect(Modal.getInstance(div)).toEqual(null) const modal = Modal.getOrCreateInstance(div, { backdrop: true }) expect(modal).toBeInstanceOf(Modal) expect(modal._config.backdrop).toEqual(true) }) it('should return the instance when exists without given configuration', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') const modal = new Modal(div, { backdrop: true }) expect(Modal.getInstance(div)).toEqual(modal) const modal2 = Modal.getOrCreateInstance(div, { backdrop: false }) expect(modal).toBeInstanceOf(Modal) expect(modal2).toEqual(modal) expect(modal2._config.backdrop).toEqual(true) }) }) })
kmcurry/3Scape
public/bower_components/bootstrap/js/tests/unit/modal.spec.js
JavaScript
gpl-3.0
35,285
/** * Dokuwiki Namespaced template java file * * @link https://www.dokuwiki.org/template:namespaced * @author Simon DELAGE <[email protected]> * @license GPL 2 (https://www.gnu.org/licenses/gpl-2.0.html) * * Here comes java magic * * We handle several device classes based on browser width. * - desktop: > __tablet_width__ (as set in style.ini) * - mobile: * - tablet <= __tablet_width__ * - phone <= __phone_width__ */ var device_class = ''; // not yet known var device_classes = 'desktop mobile tablet phone'; var $docHeight = jQuery(document).height(); var $sitenavH = 0; if (jQuery('#namespaced__site_nav').hasClass("sticky")) $sitenavH = jQuery('#namespaced__site_nav').outerHeight(); var $pagenavH = 0; if (jQuery('#namespaced__page_nav').hasClass("sticky")) $pagenavH = jQuery('#namespaced__page_nav').outerHeight(); var $scrollDelta = $sitenavH + $pagenavH; //// blur when clicked //jQuery('#dokuwiki__pagetools div.tools>ul>li>a').on('click', function(){ // this.blur(); //}); // RESIZE WATCHER jQuery(function(){ var resizeTimer; dw_page.makeToggle('#namespaced__aside h6.toggle','#namespaced__aside div.content'); tpl_dokuwiki_mobile(); jQuery(window).on('resize', function(){ if (resizeTimer) clearTimeout(resizeTimer); resizeTimer = setTimeout(tpl_dokuwiki_mobile,200); } ); }); function tpl_dokuwiki_mobile(){ // the z-index in mobile.css is (mis-)used purely for detecting the screen mode here var screen_mode = jQuery('#screen__mode').css('z-index') + ''; // determine our device pattern // TODO: consider moving into dokuwiki core switch (screen_mode) { case '2002': if (device_class.match(/extract-sidebar/)) return; device_class = 'desktop extract-sidebar'; break; case '2001': if (device_class.match(/extract-toc/)) return; device_class = 'desktop extract-toc'; break; case '1001': if (device_class.match(/phone/)) return; device_class = 'mobile phone'; break; default: if (device_class == 'desktop') return; device_class = 'desktop'; } jQuery('html').removeClass(device_classes).addClass(device_class); // handle some layout changes based on change in device var $handle = jQuery('#namespaced__aside h6.toggle'); var $toc = jQuery('#dw__toc h3'); if (device_class == 'desktop') { // reset for desktop mode if($handle.length) { $handle[0].setState(1); //$handle.hide(); } if($toc.length) { $toc[0].setState(1); } } if (device_class.match(/mobile/)){ // toc and sidebar hiding if($handle.length) { //$handle.show(); $handle[0].setState(-1); } if($toc.length) { $toc[0].setState(-1); } } } // SCROLL WATCHER // Watch scroll to show/hide got-to-top/bottom page tools jQuery(document).scroll(function() { var $scrollTop = jQuery(document).scrollTop(); if ($scrollTop >= 600) { // user scrolled 600 pixels or more; jQuery('#namespaced__pagetools ul li.top').fadeIn(500); if ($scrollTop >= $docHeight - 1200) { // user scrolled 600 pixels or more; jQuery('#namespaced__pagetools ul li.bottom').fadeOut(0); } else { jQuery('#namespaced__pagetools ul li.bottom').fadeIn(500); } } else { jQuery('#namespaced__pagetools ul li.top').fadeOut(0); } }); // CLICK WATCHER // Add scroll delta from stickies when clicking a link //jQuery('a[href*="#"]:not([href="#spacious__main"])').click(function(e) { jQuery('a[href*="#"]').click(function() { var $target = jQuery(this.hash); //if ($target.length == 0) target = jQuery('a[name="' + this.hash.substr(1) + '"]'); if ($target.length == 0) $target = jQuery('html'); // Move to intended target with delta depending on stickies jQuery('html, body').scrollTop($target.offset().top - $scrollDelta ); return false; }); //jQuery(document).ready(function() { // jQuery('#namespaced__updown .up').fadeIn(0); //});
geekitude/dokuwiki-template-namespaced
script.js
JavaScript
gpl-3.0
4,265
const teams = [ { id: "sln", full: "St. Louis Cardinals", location: "St. Louis", nickname: "Cardinals", }, { id: "mil", full: "Milwaukee Brewers", location: "Milwaukee", nickname: "Brewers", }, { id: "atl", full: "Atlanta Braves", location: "Atlanta", nickname: "Braves", }, { id: "nyn", full: "New York Mets", location: "New York", nickname: "Mets", }, { id: "nya", full: "New York Yankees", location: "New York", nickname: "Yankees", }, { id: "was", full: "Washington Nationals", location: "Washington", nickname: "Nationals", }, { id: "tor", full: "Toronto Blue Jays", location: "Toronto", nickname: "Blue Jays", }, { id: "chn", full: "Chicago Cubs", location: "Chicago", nickname: "Cubs", }, { id: "cha", full: "Chicago White Sox", location: "Chicago", nickname: "White Sox", }, { id: "bos", full: "Boston Red Sox", location: "Boston", nickname: "Red Sox", }, { id: "phi", full: "Philadelphia Phillies", location: "Philadelphia", nickname: "Phillies", }, { id: "bal", full: "Baltimore Orioles", location: "Baltimore", nickname: "Orioles", }, { id: "cin", full: "Cincinnati Reds", location: "Cincinnati", nickname: "Reds", }, { id: "cle", full: "Cleveland Indians", location: "Cleveland", nickname: "Indians", }, { id: "det", full: "Detroit Tigers", location: "Detroit", nickname: "Tigers", }, { id: "min", full: "Minnesota Twins", location: "Minnesota", nickname: "Twins", }, { id: "lan", full: "Los Angeles Dodgers", location: "Los Angeles", nickname: "Dodgers", }, { id: "ana", full: "Los Angeles Angels", location: "Los Angeles", nickname: "Angels", }, { id: "mia", full: "Miami Marlins", location: "Miami", nickname: "Marlins", }, { id: "sea", full: "Seattle Mariners", location: "Seattle", nickname: "Mariners", }, { id: "pit", full: "Pittsburgh Pirates", location: "Pittsburgh", nickname: "Pirates", }, { id: "oak", full: "Oakland Athletics", location: "Oakland", nickname: "Athletics", }, { id: "sfn", full: "San Francisco Giants", location: "San Francisco", nickname: "Giants", }, { id: "col", full: "Colorado Rockies", location: "Colorado", nickname: "Rockies", }, { id: "sdn", full: "San Diego Padres", location: "San Diego", nickname: "Padres", }, { id: "hou", full: "Houston Astros", location: "Houston", nickname: "Astros", }, { id: "kca", full: "Kansas City Royals", location: "Kansas City", nickname: "Royals", }, { id: "tex", full: "Texas Rangers", location: "Texas", nickname: "Rangers", }, { id: "tba", full: "Tampa Bay Rays", location: "Tampa Bay", nickname: "Rays", }, { id: "ari", full: "Arizona Diamondbacks", location: "Arizona", nickname: "Diamondbacks", }, ]; module.exports = teams;
Conrad2134/pitchfx
src/teams.js
JavaScript
gpl-3.0
2,914
"use strict"; const { BrowserWindow } = require("electron"); module.exports = (dirname, storage) => { let win; let init = () => { if (win === null || win === undefined) { createWindow(); } }; let createWindow = () => { const { screen } = require("electron"); const { width, height } = screen.getPrimaryDisplay().workAreaSize; win = new BrowserWindow({ frame: false, autoHideMenuBar: true, width: width, height: height, transparent: true, alwaysOnTop: true, resizable: false, movable: false, hasShadow: false, }); win.loadURL(`file://${dirname}/views/support.html`); win.on("closed", () => { win = undefined; }); }; let getWindow = () => win; return { init: init, getWindow: getWindow, }; };
Toinane/colorpicker
src/browsers/support.js
JavaScript
gpl-3.0
950
define(['backbone'], function(Backbone){ var Role = Backbone.Model.extend({ idAttribute: 'UID', url: '/api/role' }); var role = new Role(); role.fetch(); return role; });
gsmlg/oneblog
app/assets/javascript/app/role.js
JavaScript
gpl-3.0
207
"use strict"; var TransitionHookPhase; (function (TransitionHookPhase) { TransitionHookPhase[TransitionHookPhase["CREATE"] = 0] = "CREATE"; TransitionHookPhase[TransitionHookPhase["BEFORE"] = 1] = "BEFORE"; TransitionHookPhase[TransitionHookPhase["RUN"] = 2] = "RUN"; TransitionHookPhase[TransitionHookPhase["SUCCESS"] = 3] = "SUCCESS"; TransitionHookPhase[TransitionHookPhase["ERROR"] = 4] = "ERROR"; })(TransitionHookPhase = exports.TransitionHookPhase || (exports.TransitionHookPhase = {})); var TransitionHookScope; (function (TransitionHookScope) { TransitionHookScope[TransitionHookScope["TRANSITION"] = 0] = "TRANSITION"; TransitionHookScope[TransitionHookScope["STATE"] = 1] = "STATE"; })(TransitionHookScope = exports.TransitionHookScope || (exports.TransitionHookScope = {})); //# sourceMappingURL=interface.js.map
DigitalCookiesGroup/SWEDesigner
Front-End/node_modules/@uirouter/core/lib/transition/interface.js
JavaScript
gpl-3.0
852
import Ember from 'ember'; import { module, test } from 'qunit'; import startApp from 'azureexplorer/tests/helpers/start-app'; module('Integration | Notifications', { afterEach: function() { Ember.run(this.application, 'destroy'); this.store = null; } }); test('Notifications show up for batch download', function (assert) { this.application = startApp({}, assert); this.store = this.application.__container__.lookup('store:main'); Ember.run(() => { this.store.findAll('account').then(accounts => { accounts.content.forEach(account => { account.record.deleteRecord(); account.record.save(); }); }); }); andThen(() => { Ember.run(() => { let newAccount = this.store.createRecord('account', { name: 'Testaccount', key: 'n+ufPpP3UwY+REvC3/zqBmHt2hCDdI06tQI5HFN7XnpUR5VEKMI+8kk/ez7QLQ3Cmojt/c1Ktaug3nK8FC8AeA==', active: true }); newAccount.save(); }); visit('/'); }); andThen(function () { visit('/explorer').then(function () { // replace file input as text box to avoid native dialog displaying Ember.$('#nwSaveDirectory').attr('type', 'text'); Ember.$('#nwSaveInput').attr('type', 'text'); // select all blobs return click('#selectAllCheckbox'); }) .then(function () { return click('.fa-download'); }) .then(function () { return triggerEvent('#nwSaveDirectory', 'change'); }) .then(function () { return click('.handle'); }) .then(function () { assert.equal(find('.mdi-action-done').length, 4); }); }); });
ritazh/xplat
tests/acceptance/notification-test.js
JavaScript
gpl-3.0
1,845
// sparkly effect for xmas stuff // a blue icey glow with occasional sparkles // sparkles led.led_rnd(0, led.leds); led.color(255, 255, 255); led.fade_mode(2); led.fade_speed(20); led.draw(); //blue glow led.repeat_begin_rnd(0,100); led.led_rnd(0, led.leds); led.color_rnd(0, 0, 0, 0, 100, 250); led.fade_mode(1); led.fade_speed(1); led.draw(); led.delay(0); led.repeat_end();
psy0rz/ledanim
web/repo/xmas/sparkle.js
JavaScript
gpl-3.0
390
export default { div: 'Div', aside: 'Aside', main: 'Main', h1: 'Heading', h2: 'Heading', h3: 'Heading', h4: 'Heading', h5: 'Heading', h6: 'Heading', p: 'Paragraph', span: 'Span', ul: 'Unordered List', li: 'List Item', img: 'Image', strong: 'Strong Text', em: 'Emphasised Text', i: 'Icon', a: 'Link', input: 'Input', blockquote: 'Quote', figcaption: 'Caption', button: 'Button', header: 'Header', footer: 'Footer' };
builify/builify
src/javascript/components/canvas/click-toolbox/html-tagnames.js
JavaScript
gpl-3.0
512
// watch "use strict"; module.exports = { options: { livereload: false }, // docs: { // files: [ // "<%= pkg.source %>" + "/javascript/**/*.js" // ], // tasks: [ // "docs" // ] // }, js: { files: [ "<%= pkg.source %>" + "/javascript/**/*.js" ], tasks: [ // 'clean:js', "newer:copy:js", "newer:copy:libs" ] }, html: { files: [ "<%= pkg.source %>" + "/html/**/*.html" ], tasks: [ // 'clean:html', "newer:copy:html" ] }, less: { files: [ "<%= pkg.source %>" + "/css/**/*.less" ], tasks: [ "less:dev", "postcss:dev" ] }, images: { files: [ "<%= pkg.source %>" + "/images/**/*.{png,jpg,jpeg,gif}" ], tasks: [ "newer:imagemin:dev" ] }, livereload: { options: { livereload: true }, files: [ "<%= pkg.development %>" + "/**/*" ] } };
LOA-SEAD/cuidando-bem
grunt/options/watch.js
JavaScript
gpl-3.0
1,178
/* Copyright 2010-2012 Infracom & Eurotechnia ([email protected]) This file is part of the Webcampak project. Webcampak 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. Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 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 Webcampak. If not, see http://www.gnu.org/licenses/. */ console.log('Log: Load: Webcampak.controller.dashboard.SourceDiskUsage'); Ext.define('Webcampak.controller.dashboard.SourceDiskUsage', { extend: 'Ext.app.Controller', stores: [ 'dashboard.SourceDiskUsage', 'permissions.sources.Sources' ], models: [ 'dashboard.SourceDiskUsage' ], views: [ 'dashboard.sourcediskusage.SourceDiskUsageWindow', 'dashboard.sourcediskusage.SourceDiskUsage', 'dashboard.sourcediskusage.SourcesList' ], refs: [ {ref: 'sourcediskusagewindow', selector: 'sourcediskusagewindow', xtype: 'sourcediskusagewindow'}, {ref: 'sourcediskusage', selector: 'sourcediskusage', xtype: 'sourcediskusage'}, {ref: 'statssourceslist', selector: 'statssourceslist', xtype: 'statssourceslist'} ], onLaunch: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller onLaunch: function()'); /* //Show Files Graph window (stats about size of pictures per day) if(!this.getSourcediskusagewindow().isVisible()) { this.getSourcediskusagewindow().show(); console.log('Log: Controller->Menu: openPhotos - getSourcepicturefileswindow().show()'); //Load the sources store this.getPermissionsSourcesSourcesStore().on('load',this.loadGraphContent,this,{single:true}); this.getPermissionsSourcesSourcesStore().load(); } else { this.getSourcediskusagewindow().hide(); console.log('Log: Controller->Menu: openPhotos - getSourcepicturefileswindow().hide()'); } */ }, init: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller init: function()'); // Start listening for events on views this.control({ 'sourcediskusagewindow button[action=reload]': {click: this.reloadGraph}, 'sourcediskusagewindow button[action=save]': {click: this.saveGraph}, 'statssourceslist': {select: this.onSourceSelected}, 'sourcediskusagewindow combo[action=updateRange]': {select: this.onUpdateRange}, 'sourcediskusagewindow': {resize: this.windowResize} }); }, loadGraphContent: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: loadGraphContent: function()'); }, windowResize: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: windowResize: function()'); this.getSourcediskusage().axes.items[1].setTitle(Ext.getStore('permissions.sources.Sources').first().get('name')); Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('sourceid', Ext.getStore('permissions.sources.Sources').first().get('sourceid')); //Load the latest picture for the selected source this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true}); this.getDashboardSourceDiskUsageStore().load(); }, onUpdateRange: function(selModel, selection) { console.log('Log: Controller->Dashboard->SourceDiskUsage: onUpdateRange: function()'); console.log('Log: Controller->Dashboard->SourceDiskUsage: onUpdateRange: Selected range is:' + selection[0].get('name')); Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('range', selection[0].get('value')); //Load the latest picture for the selected source this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true}); this.getDashboardSourceDiskUsageStore().load(); }, onSourceSelected: function(selModel, selection) { console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: function()'); console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: Selected name is:' + selection[0].get('name')); console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: Selected Sourceid is:' + selection[0].get('sourceid')); Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('sourceid', selection[0].get('sourceid')); //Set Sourcename as the title // this.getSourcediskusagewindow().setTitle(i18n.gettext('Graph: Disk usage per source') + " (" + selection[0].get('name') + ")"); this.getSourcediskusage().axes.items[1].setTitle(selection[0].get('name')); //Load the latest picture for the selected source this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true}); this.getDashboardSourceDiskUsageStore().load(); }, reloadGraph: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller reloadGraph: function()'); this.getDashboardSourceDiskUsageStore().load(); }, saveGraph: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller saveGraph: function()'); currentChart = this.getSourcediskusage(); Ext.MessageBox.confirm(i18n.gettext('Confirm Download'), i18n.gettext('Would you like to download the chart as an image?'), function(choice){ if(choice == 'yes'){ currentChart.save({ type: 'image/png' }); } }); } });
Webcampak/v2.0
src/www/interface/dev/app/controller/dashboard/SourceDiskUsage.js
JavaScript
gpl-3.0
5,637
var NAVTREEINDEX1 = { "var__init_8h.html#a0764b32f40bbe284b6ba2a1fee678d6c":[2,0,0,16,4], "var__init_8h.html#a2fd24bcbadb8b59c176dccc6f13250e9":[2,0,0,16,3], "var__init_8h.html#a3482785bd2a4c8b307f9e0b6f54e2c36":[2,0,0,16,8], "var__init_8h.html#a6b57f01d3c576db5368dd0efc2f435a4":[2,0,0,16,1], "var__init_8h.html#a78fa3957d73de49cb81d047857504218":[2,0,0,16,5], "var__init_8h.html#a8194731fdeea643e725e3a89d2f7ec59":[2,0,0,16,6], "var__init_8h.html#ab454541ae58bcf6555e8d723b1eb95e7":[2,0,0,16,7], "var__init_8h.html#abe06f96c5aeacdb02e4b66e34e609982":[2,0,0,16,2], "var__init_8h.html#ae86e3a2639bfd6cac9c94470ec2825c8":[2,0,0,16,9], "var__init_8h_source.html":[2,0,0,16] };
SimonItaly/duckhunt
doc/html/navtreeindex1.js
JavaScript
gpl-3.0
675
var a00572 = [ [ "Nrf_bootloader", "a00573.html", null ], [ "Nrf_dfu", "a00574.html", null ], [ "Nrf_dfu_transport", "a00575.html", null ], [ "Nrf_bootloader_util", "a00576.html", null ], [ "Ble_sdk_app_bootloader_main", "a00577.html", null ] ];
DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware
nrf51_sdk/Documentation/s120/html/a00572.js
JavaScript
gpl-3.0
265
import React from 'react'; import Grafico from './Grafico'; class Grafici extends React.Component { render() { return ( <div> <h5 className="mt-3">Grafici</h5> <Grafico titolo="Latenza" xtitle="Misurazioni" ytitle="ms" label="Ping" data={this.props.dataPing} colors={["#ffc107"]}/> <Grafico titolo="Download" xtitle="Misurazioni" ytitle="kb/s" label="Banda" data={this.props.dataDownload} colors={["#007bff"]}/> <Grafico titolo="Upload" xtitle="Misurazioni" ytitle="kb/s" label="Banda" data={this.props.dataUpload} colors={["#28a745"]}/> </div> ) } } export default Grafici;
fondazionebordoni/misurainternet-ui
src/Grafici.js
JavaScript
gpl-3.0
633
var searchData= [ ['ajoutercarte',['ajouterCarte',['../interface_small_world_1_1_inter_monteur_partie.html#a473c91ad26ee485f07261df1fcae0e8b',1,'SmallWorld.InterMonteurPartie.ajouterCarte()'],['../class_small_world_1_1_monteur_partie.html#ad8cedb326193c0f0ff5f2d6705867156',1,'SmallWorld.MonteurPartie.ajouterCarte()']]], ['ajouterjoueur',['ajouterJoueur',['../interface_small_world_1_1_inter_monteur_partie.html#ae52498262dd36230b0c0d090cb59ff07',1,'SmallWorld.InterMonteurPartie.ajouterJoueur()'],['../class_small_world_1_1_monteur_partie.html#ac1e20f04d1ca796c1aa0ab504ecb1d2a',1,'SmallWorld.MonteurPartie.ajouterJoueur()']]], ['ajoutjoueur',['ajoutJoueur',['../interface_small_world_1_1_inter_createur_partie.html#af3fa5aaff01c6709b99eff93b6252da5',1,'SmallWorld.InterCreateurPartie.ajoutJoueur()'],['../class_small_world_1_1_createur_partie.html#a1388144440304d2d82879a15e0e58e1f',1,'SmallWorld.CreateurPartie.ajoutJoueur()']]], ['attaquer',['attaquer',['../interface_small_world_1_1_inter_unite.html#a9bce76356ba4531ed90ca35cc659af5f',1,'SmallWorld.InterUnite.attaquer()'],['../class_small_world_1_1_unite.html#af370920ab6c2b9478f0c12d7f1d22638',1,'SmallWorld.Unite.attaquer()']]] ];
damien-cremilleux/SmallWorld
Documentation/html/search/functions_61.js
JavaScript
gpl-3.0
1,198
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2019, Joyent, Inc. */ var mod_fs = require('fs'); var mod_path = require('path'); var mod_assert = require('assert-plus'); var DEFAULT_DEBOUNCE_TIME = 600; var DEFAULT_RETAIN_TIME = 0; var LOGSETS; function load_logsets() { var NAMES_SEEN = []; LOGSETS = JSON.parse(mod_fs.readFileSync(mod_path.join(__dirname, '..', 'etc', 'logsets.json'), 'utf8')); for (var i = 0; i < LOGSETS.length; i++) { var ls = LOGSETS[i]; ls.regex = new RegExp(ls.regex); mod_assert.optionalString( ls.search_dirs_pattern, 'search_dirs_pattern'); mod_assert.arrayOfString(ls.search_dirs, 'search_dirs'); mod_assert.optionalBool(ls.no_upload, 'no_upload'); mod_assert.string(ls.manta_path, 'manta_path'); mod_assert.optionalNumber(ls.debounce_time, 'debounce_time'); if (!ls.debounce_time) ls.debounce_time = DEFAULT_DEBOUNCE_TIME; mod_assert.optionalNumber(ls.retain_time, 'retain_time'); if (!ls.retain_time) ls.retain_time = DEFAULT_RETAIN_TIME; mod_assert.ok(NAMES_SEEN.indexOf(ls.name) === -1, 'duplicate logset name'); NAMES_SEEN.push(ls.name); } } var COPY_FIELDS = [ 'search_dirs', 'search_dirs_pattern', 'manta_path', 'date_string', 'date_adjustment', 'debounce_time', 'retain_time', 'customer_uuid', 'no_upload' ]; /* * Create a JSON-safe object for transport across the wire to the actor: */ function format_logset(logset, zonename, zonerole) { var o = { name: logset.name + (zonename ? '@' + zonename : ''), zonename: zonename || 'global', zonerole: zonerole || 'global', regex: logset.regex.source }; for (var i = 0; i < COPY_FIELDS.length; i++) { var cf = COPY_FIELDS[i]; o[cf] = logset[cf]; } return (o); } function logsets_for_server(zone_list_for_server) { var out = []; for (var i = 0; i < LOGSETS.length; i++) { var ls = LOGSETS[i]; /* * This logset applies to the global zone: */ if (ls.zones.indexOf('global') !== -1) { out.push(format_logset(ls)); } for (var j = 0; j < zone_list_for_server.length; j++) { var zz = zone_list_for_server[j]; if (ls.zones.indexOf(zz.role) !== -1) { out.push(format_logset(ls, zz.uuid, zz.role)); } } } return (out); } /* * Initialisation: */ load_logsets(); /* * API: */ module.exports = { logsets_for_server: logsets_for_server }; /* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
joyent/sdc-hermes
lib/logsets.js
JavaScript
mpl-2.0
2,593
/* * Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ define([ 'require', 'module', 'jquery', '{lodash}/lodash', '{angular}/angular', '[text]!{w20-business-theme}/templates/topbar.html', '[text]!{w20-business-theme}/templates/sidebar.html', '{angular-sanitize}/angular-sanitize', '{w20-core}/modules/ui', '{w20-core}/modules/notifications', '{w20-core}/modules/culture', '{w20-core}/modules/utils' ], function (require, module, $, _, angular, topbarTemplate, sidebarTemplate) { 'use strict'; var w20BusinessTheme = angular.module('w20BusinessTheme', ['w20CoreCulture', 'w20CoreUtils', 'w20CoreUI', 'w20CoreNotifications', 'ngSanitize']), _config = module && module.config() || {}, showTopbar = true, showSidebar = _config.sidebar && typeof _config.sidebar.show === 'boolean' ? _config.show : true, includes = _.contains || _.includes; w20BusinessTheme.directive('w20Topbar', ['ApplicationService', 'EventService', 'EnvironmentService', 'DisplayService', 'MenuService', 'NavigationService', function (applicationService, eventService, environmentService, displayService, menuService, navigationService) { return { template: topbarTemplate, replace: true, restrict: 'A', scope: true, link: function (scope, iElement, iAttrs) { scope.navActions = menuService.getActions; scope.navAction = menuService.getAction; scope.envtype = environmentService.environment; scope.buildLink = navigationService.buildLink; scope.title = iAttrs.title || '\'' + applicationService.applicationId + '\''; scope.description = iAttrs.subtitle || ''; scope.logo = _config.logo; scope.brandFixedWidth = true; if (_config.brand) { scope.brandFixedWidth = _config.brand.fixedWidth === false ? _config.brand.fixedWidth : true; scope.brandBackgroundColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined; scope.brandTextColor = _config.brand.textColor ? _config.brand.textColor : undefined; } scope.showTopbar = function () { return showTopbar; }; scope.toggleSidebar = function () { eventService.emit('SidebarToggleEvent'); }; displayService.registerContentShiftCallback(function () { return [showTopbar ? 50 : 0, 0, 0, 0]; }); } }; }]); w20BusinessTheme.directive('w20Sidebar', ['EventService', 'DisplayService', 'NavigationService', 'MenuService', '$location', '$window', function (eventService, displayService, navigationService, menuService, $location, $window) { return { template: sidebarTemplate, replace: true, restrict: 'A', scope: true, link: function (scope) { var previousSidebarState = showSidebar; if (_config.sidebar) { scope.sideBarWidth = _config.sidebar.width ? _config.sidebar.width : undefined; } scope.menuSections = menuService.getSections; scope.menuActiveSectionName = scope.menuSections()[0]; scope.showSidebar = function () { return showSidebar; }; scope.menuSection = function (name) { return name ? menuService.getSection(name) : null; }; eventService.on('SidebarToggleEvent', function () { showSidebar = !showSidebar; previousSidebarState = showSidebar; displayService.computeContentShift(); }); displayService.registerContentShiftCallback(function () { return [10, 0, 0, showSidebar ? (scope.sideBarWidth || 270) : 0]; }); angular.element($window).bind('resize', function () { showSidebar = $(window).width() < 768 ? false : previousSidebarState; scope.$apply(); displayService.computeContentShift(); }); } }; }]); w20BusinessTheme.filter('routeFilter', ['CultureService', 'SecurityExpressionService', function (cultureService, securityExpressionService) { function isRouteVisible(route) { return !route.hidden && (typeof route.security === 'undefined' || securityExpressionService.evaluate(route.security)); } return function (routes, expected) { if (!expected) { return; } return _.filter(routes, function (route) { if (isRouteVisible(route) && cultureService.displayName(route).toLowerCase().indexOf(expected.toLowerCase()) !== -1) { return route; } }); }; }]); w20BusinessTheme.controller('W20btViewsController', ['$scope', 'NavigationService', 'CultureService', '$route', '$location', function ($scope, navigationService, cultureService, $route, $location) { var openedCategories = navigationService.expandedRouteCategories(); function recursiveOpen(tree) { openedCategories.push(tree.categoryName); for (var key in tree) { if (tree.hasOwnProperty(key)) { var subTree = tree[key]; if (subTree instanceof Array) { recursiveOpen(subTree); } } } } $scope.routes = $route.routes; $scope.filteredRoutes = []; $scope.menuTree = navigationService.routeTree; $scope.subMenuTree = navigationService.computeSubTree; $scope.topLevelCategories = navigationService.topLevelRouteCategories; $scope.topLevelRoutes = navigationService.topLevelRoutes; $scope.routesFromCategory = navigationService.routesFromCategory; $scope.displayName = cultureService.displayName; $scope.buildLink = navigationService.buildLink; if (_config.brand) { $scope.brandColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined; } $scope.activeRoutePath = function () { return $location.path(); }; $scope.localizeCategory = function (categoryName) { var lastPartIndex = categoryName.lastIndexOf('.'); if (lastPartIndex !== -1) { return cultureService.localize('application.viewcategory.' + categoryName, undefined, null) || cultureService.localize('application.viewcategory.' + categoryName.substring(lastPartIndex + 1)); } else { return cultureService.localize('application.viewcategory.' + categoryName); } }; $scope.toggleTree = function (tree) { if ($scope.isOpened(tree.categoryName)) { openedCategories.splice(openedCategories.indexOf(tree.categoryName), 1); } else { openedCategories.push(tree.categoryName); } }; $scope.isOpened = function (categoryName) { return includes(openedCategories, categoryName); }; $scope.routeSortKey = function (route) { return route.sortKey || route.path; }; }]); w20BusinessTheme.run(['$rootScope', 'EventService', 'DisplayService', 'MenuService', 'CultureService', function ($rootScope, eventService, displayService, menuService, cultureService) { $rootScope.$on('$routeChangeSuccess', function (event, routeInfo) { if (routeInfo && routeInfo.$$route) { switch (routeInfo.$$route.navigation) { case 'none': showSidebar = false; showTopbar = false; break; case 'sidebar': showSidebar = true; showTopbar = false; break; case 'topbar': showSidebar = false; showTopbar = true; break; case 'full': /* falls through */ default: break; } displayService.computeContentShift(); } }); if (!_config.hideSecurity) { if (!_config.profileChooser) { menuService.addAction('login', 'w20-login', { sortKey: 100 }); } else { menuService.addAction('profile', 'w20-profile', { sortKey: 100 }); } } if (!_config.hideConnectivity) { menuService.addAction('connectivity', 'w20-connectivity', { sortKey: 200 }); } if (!_config.hideCulture) { menuService.addAction('culture', 'w20-culture', { sortKey: 300 }); } _.each(_config.links, function (link, idx) { if (idx < 10) { menuService.addAction('link-' + idx, 'w20-link', _.extend(link, { sortKey: 400 + idx })); } }); if (!_config.hideSecurity && !_config.profileChooser) { menuService.addAction('logout', 'w20-logout', { sortKey: 1000 }); } menuService.addSection('views', 'w20-views', { templateUrl: '{w20-business-theme}/templates/sidebar-views.html' }); eventService.on('w20.security.authenticated', function () { displayService.computeContentShift(); }); eventService.on('w20.security.deauthenticated', function () { displayService.computeContentShift(); }); eventService.on('w20.security.refreshed', function () { displayService.computeContentShift(); }); }]); return { angularModules: ['w20BusinessTheme'], lifecycle: { pre: function (modules, fragments, callback) { angular.element('body').addClass('w20-top-shift-padding w20-right-shift-padding w20-bottom-shift-padding w20-left-shift-padding'); callback(module); } } }; });
seedstack/w20-business-theme
modules/main.js
JavaScript
mpl-2.0
11,739
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const { Cu } = require('chrome'); const sp = require('sdk/simple-prefs'); const app = require('sdk/system/xul-app'); const { id, preferencesBranch } = require('sdk/self'); const { open } = require('sdk/preferences/utils'); const { getTabForId } = require('sdk/tabs/utils'); const { modelFor } = require('sdk/model/core'); const { getAddonByID } = require('sdk/addon/manager'); const { AddonManager } = Cu.import('resource://gre/modules/AddonManager.jsm', {}); require('sdk/tabs'); exports.testDefaultValues = function (assert) { assert.equal(sp.prefs.myHiddenInt, 5, 'myHiddenInt default is 5'); assert.equal(sp.prefs.myInteger, 8, 'myInteger default is 8'); assert.equal(sp.prefs.somePreference, 'TEST', 'somePreference default is correct'); } exports.testOptionsType = function*(assert) { let addon = yield getAddonByID(id); assert.equal(addon.optionsType, AddonManager.OPTIONS_TYPE_INLINE, 'options type is inline'); } exports.testButton = function(assert, done) { open({ id: id }).then(({ tabId, document }) => { let tab = modelFor(getTabForId(tabId)); sp.once('sayHello', _ => { assert.pass('The button was pressed!'); tab.close(done); }); tab.attach({ contentScript: 'unsafeWindow.document.querySelector("button[label=\'Click me!\']").click();' }); }); } if (app.is('Firefox')) { exports.testAOM = function(assert, done) { open({ id: id }).then(({ tabId }) => { let tab = modelFor(getTabForId(tabId)); assert.pass('the add-on prefs page was opened.'); tab.attach({ contentScriptWhen: "end", contentScript: 'self.postMessage({\n' + 'someCount: unsafeWindow.document.querySelectorAll("setting[title=\'some-title\']").length,\n' + 'somePreference: getAttributes(unsafeWindow.document.querySelector("setting[title=\'some-title\']")),\n' + 'myInteger: getAttributes(unsafeWindow.document.querySelector("setting[title=\'my-int\']")),\n' + 'myHiddenInt: getAttributes(unsafeWindow.document.querySelector("setting[title=\'hidden-int\']")),\n' + 'sayHello: getAttributes(unsafeWindow.document.querySelector("button[label=\'Click me!\']"))\n' + '});\n' + 'function getAttributes(ele) {\n' + 'if (!ele) return {};\n' + 'return {\n' + 'pref: ele.getAttribute("pref"),\n' + 'type: ele.getAttribute("type"),\n' + 'title: ele.getAttribute("title"),\n' + 'desc: ele.getAttribute("desc"),\n' + '"data-jetpack-id": ele.getAttribute(\'data-jetpack-id\')\n' + '}\n' + '}\n', onMessage: msg => { // test against doc caching assert.equal(msg.someCount, 1, 'there is exactly one <setting> node for somePreference'); // test somePreference assert.equal(msg.somePreference.type, 'string', 'some pref is a string'); assert.equal(msg.somePreference.pref, 'extensions.' + id + '.somePreference', 'somePreference path is correct'); assert.equal(msg.somePreference.title, 'some-title', 'somePreference title is correct'); assert.equal(msg.somePreference.desc, 'Some short description for the preference', 'somePreference description is correct'); assert.equal(msg.somePreference['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); // test myInteger assert.equal(msg.myInteger.type, 'integer', 'myInteger is a int'); assert.equal(msg.myInteger.pref, 'extensions.' + id + '.myInteger', 'extensions.test-simple-prefs.myInteger'); assert.equal(msg.myInteger.title, 'my-int', 'myInteger title is correct'); assert.equal(msg.myInteger.desc, 'How many of them we have.', 'myInteger desc is correct'); assert.equal(msg.myInteger['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); // test myHiddenInt assert.equal(msg.myHiddenInt.type, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.pref, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.title, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.desc, undefined, 'myHiddenInt was not displayed'); // test sayHello assert.equal(msg.sayHello['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); tab.close(done); } }); }) } // run it again, to test against inline options document caching // and duplication of <setting> nodes upon re-entry to about:addons exports.testAgainstDocCaching = exports.testAOM; } exports.testDefaultPreferencesBranch = function(assert) { assert.equal(preferencesBranch, id, 'preferencesBranch default the same as self.id'); } require('sdk/test/runner').runTestsFromModule(module);
Yukarumya/Yukarum-Redfoxes
addon-sdk/source/test/addons/simple-prefs/lib/main.js
JavaScript
mpl-2.0
5,341
function (user, context, callback) { // dictionary of applications and their related mozillians groups to worry about const applicationGroupMapping = { 'EnEylt4OZW6i7yCWzZmCxyCxDRp6lOY0': 'mozilliansorg_ghe_saml-test-integrations_users', }; const fetch = require('[email protected]'); const AUTH0_TIMEOUT = 5000; // milliseconds const PERSONAPI_BEARER_TOKEN_REFRESH_AGE = 64770; // 18 hours - 30 seconds for refresh timeout allowance const PERSONAPI_TIMEOUT = 5000; // milliseconds const USER_ID = context.primaryUser || user.user_id; const getBearerToken = async () => { // if we have the bearer token stored, we don't need to fetch it again if (global.personapi_bearer_token && global.personapi_bearer_token_creation_time && Date.now() - global.personapi_bearer_token_creation_time < PERSONAPI_BEARER_TOKEN_REFRESH_AGE) { return global.personapi_bearer_token; } const options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, timeout: AUTH0_TIMEOUT, body: JSON.stringify({ audience: configuration.personapi_audience, client_id: configuration.personapi_read_profile_api_client_id, client_secret: configuration.personapi_read_profile_api_secret, grant_type: 'client_credentials', }) }; try { //console.log(configuration.personapi_oauth_url); const response = await fetch(configuration.personapi_oauth_url, options); const data = await response.json(); // store the bearer token in the global object, so it's not constantly retrieved global.personapi_bearer_token = data.access_token; global.personapi_bearer_token_creation_time = Date.now(); console.log(`Successfully retrieved bearer token from Auth0`); return global.personapi_bearer_token; } catch (error) { throw Error(`Unable to retrieve bearer token from Auth0: ${error.message}`); } }; const getPersonProfile = async () => { // Retrieve a bearer token to gain access to the person api // return the profile data const bearer = await getBearerToken(); const options = { method: 'GET', headers: { 'Authorization': `Bearer ${bearer}`, }, timeout: PERSONAPI_TIMEOUT, }; const url = `${configuration.personapi_url}/v2/user/user_id/${encodeURI(USER_ID)}`; //console.log(`Fetching person profile of ${USER_ID}`); //console.log("url is " + url); const response = await fetch(url, options); return await response.json(); }; // We only care about SSO applications that exist in the applicationGroupMapping // If the SSO ID is undefined in applicationGroupMapping, skip processing and return callback() if(applicationGroupMapping[context.clientID] !== undefined) { getPersonProfile().then(profile => { let githubUsername = null; // Get githubUsername from person api, otherwise we'll redirect try { githubUsername = profile.usernames.values['HACK#GITHUB']; // Explicitely setting githubUsername to null if undefined if(githubUsername === undefined) { githubUsername = null; } // If somehow dinopark allows a user to store an empty value // Let's set to null to be redirected later if(githubUsername.length === 0) { console.log("empty HACK#GITHUB"); githubUsername = null; } //console.log("githubUsername: " + githubUsername); } catch (e) { // Unable to do the githubUsername lookup } // Confirm the user has the group defined from mozillians matching the application id // confirm the user has a githubUsername stored in mozillians, otherwise redirect if(!user.app_metadata.groups.includes(applicationGroupMapping[context.clientID]) || githubUsername === null) { context.redirect = { url: configuration.github_enterprise_wiki_url }; } return callback(null, user, context); }); // Nothing matched, return callback() and proceed rules processing } else { return callback(null, user, context); } }
mozilla-iam/auth0-deploy
rules/GHE-Groups.js
JavaScript
mpl-2.0
4,302
var toolURL = { 'application/x-popcorn': 'https://popcorn.webmaker.org', 'application/x-thimble': 'https://thimble.webmaker.org', 'application/x-x-ray-goggles': 'https://goggles.mozilla.org' }; module.exports = function (options) { var moment = require('moment'); var MakeClient = require('makeapi-client'); function generateGravatar(hash) { var DEFAULT_AVATAR = 'https%3A%2F%2Fstuff.webmaker.org%2Favatars%2Fwebmaker-avatar-44x44.png', DEFAULT_SIZE = 44; return 'https://secure.gravatar.com/avatar/' + hash + '?s=' + DEFAULT_SIZE + '&d=' + DEFAULT_AVATAR; } // Create a make client with or without auth function createMakeClient(url, hawk) { var options = { apiURL: url }; if (hawk) { options.hawk = hawk; } var makeClient = new MakeClient(options); // Moment.js default language is 'en'. This function will override // the default language globally on the coming request for the homepage makeClient.setLang = function (lang) { moment.lang(lang); }; // Given a prefix for an app tag (e.g. "webmaker:p-") sort an array of makes based on that tag // The tag must be of the format "prefix-1", "prefix-2", etc. makeClient.sortByPriority = function (prefix, data) { var sortedData = [], duplicates = [], priorityIndex, regex = new RegExp('^' + prefix + '(\\d+)$'); function extractStickyPriority(tags) { var res; for (var i = tags.length - 1; i >= 0; i--) { res = regex.exec(tags[i]); if (res) { return +res[1]; } } } for (var i = 0; i < data.length; i++) { priorityIndex = extractStickyPriority(data[i].appTags); data[i].index = priorityIndex; if (sortedData[priorityIndex - 1]) { duplicates.push('Duplicate found for ' + prefix + priorityIndex); } else { sortedData[priorityIndex - 1] = data[i]; } } return { results: sortedData, errors: duplicates }; }; makeClient.process = function (callback, id) { makeClient.then(function (err, data, totalHits) { if (err) { return callback(err); } if (!Array.isArray(data)) { return callback('There was no data returned'); } data.forEach(function (make) { // Set the tool make.tool = make.contentType.replace(/application\/x\-/g, ''); make.toolurl = toolURL[make.contentType]; // Convert tags and set the "make.type" if (make.taggedWithAny(['guide'])) { make.type = 'guide'; } else if (make.taggedWithAny(['webmaker:template'])) { make.type = 'template'; } else if (make.contentType) { make.type = make.tool; } if (make.taggedWithAny(['beginner'])) { make.level = 'beginner'; } else if (make.taggedWithAny(['intermediate'])) { make.level = 'intermediate'; } else if (make.taggedWithAny(['advanced'])) { make.level = 'advanced'; } // Remove tutorial tags make.prettyTags = make.rawTags.filter(function (tag) { return !(tag.match(/^tutorial-/)); }); if (id) { make.hasBeenLiked = make.likes.some(function (like) { return like.userId === +id; }); } // Convert the created at and updated at to human time make.updatedAt = moment(make.updatedAt).fromNow(); make.createdAt = moment(make.createdAt).fromNow(); // Set the remix URL if (make.type !== 'Appmaker') { make.remixurl = make.url + '/remix'; } // Create a function for generating the avatar make.avatar = generateGravatar(make.emailHash); }); callback(err, data, totalHits); }); }; return makeClient; } module.exports = { authenticated: createMakeClient(options.authenticatedURL, options.hawk), readOnly: createMakeClient(options.readOnlyURL) }; };
mozilla/webmaker.org
lib/makeapi.js
JavaScript
mpl-2.0
4,168
// META: timeout=long // META: script=../util/helpers.js // META: script=failures.js run_test(["AES-CTR"]);
mbrubeck/servo
tests/wpt/web-platform-tests/WebCryptoAPI/generateKey/failures_AES-CTR.https.any.js
JavaScript
mpl-2.0
108
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pvc.BaseChart .add({ /** * A map of {@link pvc.visual.Role} by name. * Do NOT modify the returned object. * @type Object<string,pvc.visual.Role> */ visualRoles: null, /** * The array of all {@link pvc.visual.Role} instances used by the chart. * Do NOT modify the returned array. * @type pvc.visual.Role[] */ visualRoleList: null, /** * The array of all {@link pvc.visual.Role} instances used by the chart * that are considered measures. * @type pvc.visual.Role[] * @private */ _measureVisualRoles: null, /** * Obtains an existing visual role given its name. * An error is thrown if a role with the specified name is not defined. * * The specified name may be: * <ul> * <li>the name of a chart visual role, </li> * <li>the local name of a visual role of the chart's main plot, or</li> * <li>the fully qualified name of a plot's visual role: "<plot name or id>.<local role name>".</li> * </ul> * * @param {string} roleName The visual role name. * @type pvc.visual.Role */ visualRole: function(roleName) { var role = def.getOwn(this.visualRoles, roleName); if(!role) throw def.error.operationInvalid('roleName', "There is no visual role with name '{0}'.", [roleName]); return role; }, /** * Obtains the array of all {@link pvc.visual.Role} instances used by the chart * that are considered measures. * * This is made lazily because the effective "measure" status * depends on the binding of the visual role, and * of it becoming discrete or continuous. * * Do NOT modify the returned array. * * @return {pvc.visual.Role[]} The array of measure visual roles. */ measureVisualRoles: function() { if(this.parent) return this.parent.measureVisualRoles(); return this._measureVisualRoles || (this._measureVisualRoles = this.visualRoleList.filter(function(r) { return r.isBound() && !r.isDiscrete() && r.isMeasure; })); }, measureDimensionsNames: function() { return def.query(this.measureVisualRoles()) .selectMany(function(r) { return r.grouping.dimensionNames(); }) .distinct() .array(); }, /** * Obtains the chart-level visual roles played by a given dimension name, in definition order. * Do NOT modify the returned array. * @param {string} dimName The name of the dimension. * @return {pvc.visual.Role[]} The array of visual roles or <tt>null</tt>, if none. */ visualRolesOf: function(dimName) { var visualRolesByDim = this._visRolesByDim; if(!visualRolesByDim) { visualRolesByDim = this._visRolesByDim = {}; this.visualRoleList.forEach(function(r) { if(!r.plot) { var g = r.grouping; if (g) g.dimensionNames().forEach(function (n) { def.array.lazy(visualRolesByDim, n).push(r); }); } }); } return def.getOwn(visualRolesByDim, dimName, null); }, _constructVisualRoles: function(/*options*/) { var parent = this.parent; if(parent) { this.visualRoles = parent.visualRoles; this.visualRoleList = parent.visualRoleList; } else { this.visualRoles = {}; this.visualRoleList = []; } }, _addVisualRole: function(name, keyArgs) { keyArgs = def.set(keyArgs, 'index', this.visualRoleList.length); var role = new pvc.visual.Role(name, keyArgs), names = [name]; // There's a way to refer to chart visual roles without danger // of matching the main plot's visual roles. if(!role.plot) names.push("$." + name); return this._addVisualRoleCore(role, names); }, _addVisualRoleCore: function(role, names) { if(!names) names = role.name; this.visualRoleList.push(role); if(def.array.is(names)) names.forEach(function(name) { this.visualRoles[name] = role; }, this); else this.visualRoles[names] = role; return role; }, /** * Initializes the chart-level visual roles. * @virtual */ _initChartVisualRoles: function() { this._addVisualRole('multiChart', { defaultDimension: 'multiChart*', requireIsDiscrete: true }); this._addVisualRole('dataPart', { defaultDimension: 'dataPart', requireIsDiscrete: true, requireSingleDimension: true, dimensionDefaults: {isHidden: true, comparer: def.compare} }); }, _getDataPartDimName: function(useDefault) { var role = this.visualRoles.dataPart, preGrouping; return role.isBound() ? role.lastDimensionName() : (preGrouping = role.preBoundGrouping()) ? preGrouping.lastDimensionName() : useDefault ? role.defaultDimensionGroup : null; }, /** * Processes a view specification. * * An error is thrown if the specified view specification does * not have at least one of the properties <i>role</i> or <i>dims</i>. * * @param {Object} viewSpec The view specification. * @param {string} [viewSpec.role] The name of a visual role. * @param {string|string[]} [viewSpec.dims] The name or names of the view's dimensions. */ _processViewSpec: function(viewSpec) { // If not yet processed if(!viewSpec.dimsKeys) { if(viewSpec.role) { var role = this.visualRoles[viewSpec.role], grouping = role && role.grouping; if(grouping) { viewSpec.dimNames = grouping.dimensionNames().slice().sort(); viewSpec.dimsKey = viewSpec.dimNames.join(","); } } else if(viewSpec.dims) { viewSpec.dimNames = viewSpec_normalizeDims(viewSpec.dims); viewSpec.dimsKey = String(viewSpec.dimNames); } else { throw def.error.argumentInvalid( "viewSpec", "Invalid view spec. No 'role' or 'dims' property."); } } } }); // TODO: expand dim* function viewSpec_normalizeDims(dims) { // Assume already normalized if(def.string.is(dims)) dims = dims.split(","); else if(!def.array.is(dims)) throw def.error.argumentInvalid('dims', "Must be a string or an array of strings."); return def.query(dims).distinct().sort().array(); }
Abpaula/ccc
package-res/ccc/core/base/chart/chart.visualRoles.js
JavaScript
mpl-2.0
7,092
/** * Add a context menu item to borderify the current tab. */ browser.menus.create({ id: "borderify-current-tab", title: "Borderify current tab", contexts: ["all"] }); /** * The borderify CSS. */ const borderCSS = 'body { border: 5px solid red };'; /* * Borderifies the current tab, and, using setTabValue, stores the fact * that this tab was borderified. */ async function borderify() { let tabArray = await browser.tabs.query({currentWindow: true, active: true}); let tabId = tabArray[0].id; await browser.tabs.insertCSS(tabId, {code: borderCSS}); await browser.sessions.setTabValue(tabId, "border-css", borderCSS); } browser.menus.onClicked.addListener(borderify); /* * When new tabs are created, we want to check, using getTabValue, whether * the tab has the borderified state. That would mean it was borderified, then * closed, then reopened, so we want to reapply the borderify CSS. * * But we can't insertCSS in onCreated, it's too early. So instead we make * an onUpdated listener, just for this tab. In onUpdated we check the tab ID, * and if this is our tab, insert the CSS and remove the listener. */ browser.tabs.onCreated.addListener((tab) => { async function borderifyRestored(targetTabId, thisTabId) { if (targetTabId === thisTabId) { let stored = await browser.sessions.getTabValue(targetTabId, "border-css"); if (stored) { let result = await browser.tabs.insertCSS(targetTabId, {code: stored}); } browser.tabs.onUpdated.removeListener(thisBorderifyRestored); } } let thisBorderifyRestored = borderifyRestored.bind(null, tab.id); browser.tabs.onUpdated.addListener(thisBorderifyRestored); });
mdn/webextensions-examples
session-state/background.js
JavaScript
mpl-2.0
1,698
define(['Container', 'NumberStyle'], function(Container, NumberStyle) { /** * Percentage, between cow and ship, that the beam should end at * @const * @type number */ var MAX_BEAM_DISTANCE = 100; /** * Percentage, between ship and cow, that the beam should start at * @const * @type number */ var MIN_BEAM_DISTANCE = 0; /** * how long the cow should stay tinted before earning a point * @const * @type number */ var COW_GET_DELAY = 250; /** * The color of the cow when it has been hit by the tractor beam * @type number * @const */ var COW_TINT = 0x77FF77; /** * The saucer profile that measures how close a player is to abducting a cow. * When the player has retrieved a cow, this emits an 'abduct' event. * * @param {Object=} options Configuration options * @param {number=} [options.color] The color for the ship. @see Color * @param {number=} [options.speed=3] how quickly the beam should descend or * ascend, between 1 and 5, 5 being the fastest. * * @example * var b = new Beam(); * b.on('abduct', functon doSomething(){console.log('something'}); * b.active = true; * * @constructor * @name Beam */ function Beam(options) { var _this = this, _ship = new PIXI.Sprite.fromFrame('purpleSaucer.png'), _beam = new PIXI.Sprite.fromFrame('tractorBeam.png'), _cow = new PIXI.Sprite.fromFrame('cowProfile.png'), /** * The color of the ship. @see Color * @name color * @memberof Beam * @type number */ _color, /** * Whether or not the ascent and descent functions should respond. * If this is true, tractor beam will neither ascend nor descend. * The beam will pause momentarily when the cow has been hit. * @type boolean * @private */ _paused = false, /** * How many cows the user has retrieved * @type number * @name points * @memberof Beam */ _points = 0, /** * The holder for the points */ _pointsText = new PIXI.Text(_points, NumberStyle), /** * A number between MIN_BEAM_DISTANCE and MAX_BEAM_DISTANCE, representing how close the beam is to the cow * @private * @memberof Beam * @type number */ _distance = MIN_BEAM_DISTANCE, /** * Whether or not the beam should be descending * @name active * @memberof Beam * @type boolean */ _enabled = false, /** * Maps chosen speeds to times * @type Object */ _speeds = { 1: 1000, 2: 850, 3: 700, 4: 650, 5: 500 }, _ascentInterval = null, _descentInterval = null, /** * The maximum height the beam can be before it touches the cow. * @type number */ _maxBeamHeight = null, options = options || {}, /** * The speed that the tractor beam moves * @memberof Beam * @type number * @name speed */ _speed = _speeds[3]; PIXI.DisplayObjectContainer.call(_this); function _init() { var pad_x = 10; // tall enough to fit the cow, the ship, with room for the beam var box_width = _ship.width + pad_x; var box_height = (_cow.height + _ship.height)*2.5 + 5; var box = new Container('Cow Meter', box_width, box_height); var height = box_height - box.textHeight; _this.addChild(box); _cow.anchor.x = 0.5; _cow.y = height - _cow.height; _cow.x = box_width/2; _ship.anchor.x = 0.5; _ship.x = box_width/2; _ship.y = box.textHeight; _beam.anchor.x = 0.5; _beam.y = _ship.y + _ship.height - 10; _beam.x = box_width/2; _beam.height = 0; _beam.opacity = 0.7; _maxBeamHeight = height - _cow.height - _beam.y; _pointsText.y = _cow.y + _cow.height + 5; _pointsText.x = box.width/2 - _pointsText.width/2 + box.getBounds().x; _this.addChild(_ship); _this.addChild(_beam); _this.addChild(_cow); _this.addChild(_pointsText); window.t = _pointsText; Beam._index++; // so we can dispatch events (@see _retrieveCow) PIXI.EventTarget.call(_this); }; /** * Sets the distance of the tractor beam * @param number value Must be between MIN_BEAM_DISTANCE and MAX_BEAM_DISTANCE * @see score */ function _setDistance(value) { if(Number.parseInt(value) < MIN_BEAM_DISTANCE || Number.parseInt(value) > MAX_BEAM_DISTANCE) { throw "Tractor beam distance must be between " + MIN_BEAM_DISTANCE + '-' + MAX_BEAM_DISTANCE + ". Given: " + value; } _distance = value; _beam.height = (_distance/100)*_maxBeamHeight; }; /** * Sets the speed of the tractor beam * @param number value A number, from 1 to 5, representing how fast the * tractor beam should move * @see speed * @private */ function _setSpeed(value) { var speed = _speeds[value]; if(speed === undefined) { throw "Tractor beam speed must be between 1-5. Given: " + value; } _speed = speed; _resetMotion(); }; /** * Sets the total score * @see points * @private */ function _setPoints(points) { if(isNaN(parseInt(points, 10))) { return; } _points = points;; _pointsText.setText(""+points); } /** * Resets tractor beam's motion, which depends on whether or not the beam * is enabled and the current speed of the beam */ function _resetMotion() { clearInterval(_descentInterval); clearInterval(_ascentInterval); if(_enabled) { _descentInterval = setInterval(_descend, _this.speed); } else { _ascentInterval = setInterval(_ascend, _this.speed); } } /** * Gets the speed of the tractor beam * @return number A number, from 1 to 5, representing how fast the tractor * beam is moving * @see speed */ function _getSpeed() { for(key in _speeds) { if(_speeds[key] === _speed) { return key; } } }; function _ascend() { if(_paused) { return; } if(_distance <= MIN_BEAM_DISTANCE) { return; } _setDistance(_distance-1); }; function _descend() { if(_paused) { return; } if(_distance >= MAX_BEAM_DISTANCE) { _retrieveCow(); return; } _setDistance(_distance+1); }; /** * @param boolean value Whether or not the beam should be enabled */ function _setEnabled(value) { if(value == _enabled) { return; } _enabled = !!value; _resetMotion(); }; /** * Used when a beam hits the cow */ function _retrieveCow() { _paused = true; _cow.tint = COW_TINT; setTimeout(function() { _cow.tint = 0xFFFFFF; _paused = false; _setDistance(MIN_BEAM_DISTANCE); _this.points++; _this.emit({type: 'abduct'}); }, COW_GET_DELAY); }; Object.defineProperties(_this, { color: { enumerable: true, get: function() { return _color; } }, speed: { enumerable: true, get: _getSpeed, set: _setSpeed }, active: { enumerable: true, get: function() { return _enabled; }, set: _setEnabled }, points: { enumerable: true, get: function() { return _points; }, set: _setPoints } }); _init(); }; /** * Keeps track of how many saucers have been created (for colorization's sake) * @type number */ Beam._index = 0; Beam.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); Beam.prototype.constructor = Beam; return Beam; });
BYU-ODH/vocal-abduction
app/js/Beam.js
JavaScript
mpl-2.0
8,135
var wirelib = (function() { var canvas, context, width, height, lines = [], cx, cy, cz, fl = 250, interval, loopCallback, running; function initWithCanvas(aCanvas) { canvas = aCanvas; if(canvas !== undefined) { width = canvas.width; height = canvas.height; cx = width / 2; cy = height / 2; cz = fl * 2; context = canvas.getContext("2d"); } } // fl stands for Focal length function project(p3d) { var p2d = {}, scale = fl / (fl + p3d.z + cz); p2d.x = cx + p3d.x * scale; p2d.y = cy + p3d.y * scale; return p2d; } function addLine() { var i, numPoints, points, line; points = (typeof arguments[0] === "object") ? arguments[0] : arguments; numPoints = points.length; if(numPoints >= 6) { line = {style:this.strokeStyle, width:this.lineWidth, points:[]}; lines.push(line); for(i = 0; i < numPoints; i += 3) { line.points.push({x:points[i], y:points[i + 1], z:points[i + 2]}); } } else { console.error("wirelib.addLine: You need to add at least two 3d points (6 numbers) to make a line."); } return line; } function addBox(x, y, z, w, h, d) { this.addLine(x - w / 2, y - h / 2, z - d / 2, x + w / 2, y - h / 2, z - d / 2, x + w / 2, y + h / 2, z - d / 2, x - w / 2, y + h / 2, z - d / 2, x - w / 2, y - h / 2, z - d / 2); this.addLine(x - w / 2, y - h / 2, z + d / 2, x + w / 2, y - h / 2, z + d / 2, x + w / 2, y + h / 2, z + d / 2, x - w / 2, y + h / 2, z + d / 2, x - w / 2, y - h / 2, z + d / 2); this.addLine(x - w / 2, y - h / 2, z - d / 2, x - w / 2, y - h / 2, z + d / 2); this.addLine(x + w / 2, y - h / 2, z - d / 2, x + w / 2, y - h / 2, z + d / 2); this.addLine(x + w / 2, y + h / 2, z - d / 2, x + w / 2, y + h / 2, z + d / 2); this.addLine(x - w / 2, y + h / 2, z - d / 2, x - w / 2, y + h / 2, z + d / 2); } function addRect(x, y, z, w, h) { this.addLine(x - w / 2, y - h / 2, z, x + w / 2, y - h / 2, z, x + w / 2, y + h / 2, z, x - w / 2, y + h / 2, z, x - w / 2, y - h / 2, z); } function addCircle(x, y, z, radius, segments) { var i, points = [], a; for(i = 0; i < segments; i += 1) { a = Math.PI * 2 * i / segments; points.push(x + Math.cos(a) * radius, y + Math.sin(a) * radius, z); } points.push(points[0], points[1], points[2]); this.addLine(points); } function draw() { var i, j, line, p2d; if(this.clearCanvas) { context.clearRect(0, 0, width, height); } for(i = 0; i < lines.length; i += 1) { context.beginPath(); line = lines[i]; p2d = project(line.points[0]); context.moveTo(p2d.x, p2d.y); for(j = 1; j < line.points.length; j += 1) { p2d = project(line.points[j]); context.lineTo(p2d.x, p2d.y); } context.lineWidth = line.width; context.strokeStyle = line.style; context.stroke(); } if(this.showCenter) { p2d = project({x:0, y:0, z:0}); context.strokeStyle = "#ff0000"; context.lineWidth = 0.5; context.beginPath(); context.arc(p2d.x, p2d.y, 5, 0, Math.PI * 2, false); context.stroke(); } } function loop(fps, callback) { if(!running) { var wl = this; running = true; loopCallback = callback; interval = setInterval(function() { loopCallback(); wl.draw(); }, 1000 / fps); } } function stop() { running = false; clearInterval(interval); } function rotateX(radians) { var i, j, p, y1, z1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; y1 = p.y * cos - p.z * sin; z1 = p.z * cos + p.y * sin; p.y = y1; p.z = z1; } } } function rotateY(radians) { var i, j, p, x1, z1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; z1 = p.z * cos - p.x * sin; x1 = p.x * cos + p.z * sin; p.x = x1; p.z = z1; } } } function rotateZ(radians) { var i, j, p, x1, y1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; y1 = p.y * cos - p.x * sin; x1 = p.x * cos + p.y * sin; p.x = x1; p.y = y1; } } } function translate(x, y, z) { var i, j, p, line; for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; p.x += x; p.y += y; p.z += z; } } } function jitter(amount) { var i, j, line; for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; p.x += Math.random() * amount * 2 - amount; p.y += Math.random() * amount * 2 - amount; p.z += Math.random() * amount * 2 - amount; } } } function setCenter(x, y, z) { cx = x === null ? cx : x; cy = y === null ? cy : y; cz = z === null ? cz : z; } return {initWithCanvas:initWithCanvas, addLine:addLine, addBox:addBox, addRect:addRect, addCircle:addCircle, draw:draw, rotateX:rotateX, rotateY:rotateY, rotateZ:rotateZ, translate:translate, jitter:jitter, clearCanvas:true, strokeStyle:"#000000", lineWidth:1, loop:loop, stop:stop, showCenter:false, setCenter:setCenter }; }());
heliogabalo/The-side-of-the-source
Codigo/Games/Efects/3D-wirelib/wirelib.js
JavaScript
mpl-2.0
7,221
function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); let decoder = new TextDecoder("utf-8"); let encoder = new TextEncoder(); filter.ondata = event => { let str = decoder.decode(event.data, {stream: true}); // Just change any instance of Example in the HTTP response // to WebExtension Example. str = str.replace(/Example/g, 'WebExtension Example'); filter.write(encoder.encode(str)); filter.disconnect(); } return {}; } browser.webRequest.onBeforeRequest.addListener( listener, {urls: ["https://example.com/*"], types: ["main_frame"]}, ["blocking"] );
mdn/webextensions-examples
http-response/background.js
JavaScript
mpl-2.0
667
/** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/. */ var caesar = require("./caesar"); exports["test encrypt/decrypt"] = function(assert) { /* verify decrypting the result of encryption yields the original response */ assert.strictEqual(caesar.decrypt(caesar.encrypt("flee at once", "errorscanocc"), "errorscanocc"), "flee at once", "fail if cannot decrypt encrypted text"); }; exports["test encrypt 0"] = function(assert) { /* !!!!! is equivalent to an offset of zero */ assert.strictEqual(caesar.encrypt("01234", "!!!!!"), "01234", "encrypt identity"); }; exports["test decrypt 0"] = function(assert) { /* !!!!! is equivalent to an offset of zero */ assert.strictEqual(caesar.decrypt("QRSTU", "!!!!!"), "QRSTU", "decrypt identity"); }; exports["test encrypt 3"] = function(assert) { /* $$$$$ is equivalent to an offset of three */ assert.strictEqual(caesar.encrypt("01234", "$$$$$"), "34567", "encrypt by 3"); }; exports["test decrypt 3"] = function(assert) { /* $$$$$ is equivalent to an offset of three */ assert.strictEqual(caesar.decrypt("34567", "$$$$$"), "01234", "decrypt by 3"); }; exports["test encrypt wrap"] = function(assert) { assert.strictEqual(caesar.encrypt("z", "$"), "#", "encrypt wrap"); }; exports["test decrypt wrap"] = function(assert) { assert.strictEqual(caesar.decrypt("#", "$"), "z", "decrypt wrap"); }; exports["test encrypt not a no-op"] = function(assert) { /* verify we cannot pass with a no op */ assert.notStrictEqual(caesar.encrypt("flee at once", "errors can o"), "flee at once", "fail if no-op"); }; require("sdk/test").run(exports);
jeffreystarr/plainsight-addon
test/test-caesar.js
JavaScript
mpl-2.0
1,791
/** * The title screen. */ // SDK imports import ui.View; import ui.ImageView; import ui.TextView as TextView; import ui.widget.ButtonView as ButtonView; exports = Class(ui.ImageView, function (supr) { this.init = function (opts) { this._config = JSON.parse(CACHE['resources/conf/config.json']); opts = merge(opts, { x: 0, y: 0, width: this._config.screenWidth, height: this._config.screenHeight, image: "resources/images/bg1.jpg" }); supr(this, 'init', [opts]); this.build(); }; this.build = function() { var buttonWidth = 294; var buttonHeight = 61; var deviceWidth = this._config.screenWidth; var deviceHeight = this._config.screenHeight; var textview = new TextView({ superview: this, x: 0, y: 15, width: this._config.screenWidth, height: 50, text: "WeeBubble", autoSize: false, size: 38, verticalAlign: 'middle', horizontalAlign: 'center', wrap: false, color: '#000099' }); var buttonview = new ButtonView({ superview: this, width: buttonWidth, height: buttonHeight, x: (deviceWidth - buttonWidth) / 2, y: 3 * deviceHeight / 4, images: { down: "resources/images/start_button_selected.jpg", up: "resources/images/start_button_unselected.jpg" }, on: { down: bind(this, function () { }), up: bind(this, function () { this.emit('titlescreen:start'); }) } }); }; });
spil-peter-forgacs/weebubble
src/TitleScreen.js
JavaScript
mpl-2.0
1,827
window.onload = function() { // We are the parent. Let's load the test. if (parent == this || location.search.indexOf("worklet_iframe") == -1) { SimpleTest.waitForExplicitFinish(); configureTest().then(() => { var iframe = document.createElement('iframe'); iframe.src = location.href + "?worklet_iframe"; document.body.appendChild(iframe); }); return; } // Here we are in the iframe. window.SimpleTest = parent.SimpleTest; window.is = parent.is; window.isnot = parent.isnot; window.ok = parent.ok; window.info = parent.info; runTestInIframe(); }
Yukarumya/Yukarum-Redfoxes
dom/worklet/tests/common.js
JavaScript
mpl-2.0
604
/*global define*/ define('app/reload-addon-reloaded-per-user', ['lodash', 'TelemetryPromises', 'DevToolsMetrics', 'LatestVersions', 'FIREFOX_RELEASES'], function(_, T, DevToolsMetrics, LatestVersions, FIREFOX_RELEASES) { var metric = 'DEVTOOLS_RELOAD_ADDON_RELOAD_PER_USER_FLAG'; var options = { sanitized: false }; var ID = 'devtools-reload-addon-reloaded-per-user-chart'; var chart = { title: 'Reload Addon Reloaded per User / Release (MAU)', description: 'Per user, per release metric indicating the DevTools are being reloaded at least once', width: 335, height: 320, left: 60, legend: T.ALL_CHANNELS.filter((c) => c === 'nightly'), markers: FIREFOX_RELEASES.nightly, colors: _.values(FIREFOX_RELEASES.colors), legend_target: '#' + ID + '-legend' }; function evolutionMap(channel, evolutions) { // map the data into the values we need // histogram, index, date return evolutions.map((h, i, date) => { return { channel: channel, value: h.sum, date: date }; }); } DevToolsMetrics.line(ID, chart); LatestVersions.getLatestVersion().then((versions) => { versions = _.filter(versions, { channel: "nightly"}); Promise.all(versions.map((target) => { target.versions = [_.max(target.versions)]; return T.getEvolutions(target.channel, target.versions, metric, options). then((evolutions) => T.reduceEvolutions(evolutions)). then((evolutions) => evolutionMap(target.channel, evolutions)). then(_.flatten); })).then((data) => { chart.data = data; DevToolsMetrics.line(ID, chart); }); }); }); // end define
clarkbw/devtools-metrics
js/app/reload-addon-reloaded-per-user.js
JavaScript
mpl-2.0
1,694
/** * Input Field for JSON-schema type:object. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code includes react-jsonschema-form * released under the Apache License 2.0. * https://github.com/mozilla-services/react-jsonschema-form * Date on whitch referred: Thu, Mar 08, 2018 1:08:52 PM */ 'use strict'; const SchemaUtils = require('./schema-utils'); const SchemaField = require('./schema-field'); const Utils = require('../utils'); class ObjectField { constructor(schema, formData, idSchema, name, definitions, onChange, required = false, disabled = false, readOnly = false) { this.retrievedSchema = SchemaUtils.retrieveSchema(schema, definitions, formData); this.schema = schema; this.formData = formData; this.idSchema = idSchema; this.name = name; this.definitions = definitions; this.onChange = onChange; this.required = required; this.disabled = disabled; this.readOnly = readOnly; } isRequired(name) { return ( Array.isArray(this.retrievedSchema.required) && this.retrievedSchema.required.includes(name) ); } sortObject(obj) { const keys = Object.keys(obj).sort(); const map = {}; keys.forEach((key) => { let val = obj[key]; if (typeof val === 'object') { val = this.sortObject(val); } map[key] = val; }); return map; } isSameSchema(schema1, schema2) { const json1 = JSON.stringify(this.sortObject(schema1)); const json2 = JSON.stringify(this.sortObject(schema2)); return json1 === json2; } onPropertyChange(name, field) { return (value) => { const schema = this.schema; const newFormData = {}; newFormData[name] = value; this.formData = Object.assign(this.formData, newFormData); // modify part of form based on form data. if (schema.hasOwnProperty('dependencies')) { const newRetrievedSchema = SchemaUtils.retrieveSchema(schema, this.definitions, this.formData); if (!this.isSameSchema(this.retrievedSchema, newRetrievedSchema)) { this.retrievedSchema = newRetrievedSchema; this.formData = SchemaUtils.getDefaultFormState(newRetrievedSchema, this.formData, this.definitions); this.renderField(field); } } if (this.onChange) { this.onChange(this.formData); } }; } renderField(field) { const id = Utils.escapeHtmlForIdClass(this.idSchema.$id); const description = this.retrievedSchema.description; let title = this.retrievedSchema.title ? this.retrievedSchema.title : this.name; if (typeof title !== 'undefined' && title !== null) { title = Utils.escapeHtml(title); title = this.required ? title + SchemaUtils.REQUIRED_FIELD_SYMBOL : title; } field.innerHTML = (title ? `<legend id="${`${id}__title`}">${title}</legend>` : '') + (description ? `<p id="${id}__description" class="field-description"> ${Utils.escapeHtml(description)}</p>` : ''); // TODO support to specific properties order const orderedProperties = Object.keys(this.retrievedSchema.properties); orderedProperties.forEach((name) => { const childSchema = this.retrievedSchema.properties[name]; const childIdPrefix = `${this.idSchema.$id}_${name}`; const childData = this.formData[name]; const childIdSchema = SchemaUtils.toIdSchema( childSchema, childIdPrefix, this.definitions, childData ); const child = new SchemaField( childSchema, childData, childIdSchema, name, this.definitions, this.onPropertyChange(name, field), this.isRequired(name), childSchema.disabled, childSchema.readOnly).render(); field.appendChild(child); }); } render() { const field = document.createElement('fieldset'); this.renderField(field); return field; } } module.exports = ObjectField;
mozilla-iot/gateway
static/js/schema-form/object-field.js
JavaScript
mpl-2.0
4,632
/* All emon_widgets code is released under the GNU General Public License v3. See COPYRIGHT.txt and LICENSE.txt. Part of the OpenEnergyMonitor project: http://openenergymonitor.org Author: Trystan Lea: [email protected] If you have any questions please get in touch, try the forums here: http://openenergymonitor.org/emon/forum */ function vis_widgetlist(){ var widgets = { "realtime": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","colour","initzoom"], "optionstype":["feedid","colour_picker","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Default visible window interval")], "optionsdata": [ , , [["1", "1 "+_Tr("minute")],["5", "5 "+_Tr("minutes")],["15", "15 "+_Tr("minutes")],["30", "30 "+_Tr("minutes")],["60", "1 "+ _Tr("hour")]] ], "html":"" }, "rawdata": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","colour","units","dp","scale","fill","initzoom"], "optionstype":["feedid","colour_picker","value","value","value","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("Fill"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Fill value"),_Tr("Default visible window interval")], "optionsdata": [ , , , , , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ], "html":"" }, "bargraph": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","colour","interval","units","dp","scale","delta"], "optionstype":["feedid","colour_picker","value","value","value","value","boolean"], "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("Interval"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("delta")], "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Interval (seconds)-you can set \"d\" for day, \"m\" for month, or \"y\" for year"),_Tr("Units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Show difference between each bar")], "html":"" }, "timestoredaily": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","units","initzoom"], "optionstype":["feedid","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Units"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Units to show"),_Tr("Default visible window interval")], "optionsdata": [ , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ], "html":"" }, "zoom": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["power","kwhd","currency","currency_after_val","pricekwh","delta"], "optionstype":["feedid","feedid","value","value","value","boolean"], "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("Currency"),_Tr("Currency position"),_Tr("Kwh price"),_Tr("delta")], "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Currency to show"),_Tr("0 = before value, 1 = after value"),_Tr("Set kwh price"),_Tr("Show difference between each bar")], "html":"" }, "simplezoom": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["power","kwhd","delta"], "optionstype":["feedid","feedid","boolean"], "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("delta")], "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Show difference between each bar")], "html":"" }, "histgraph": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid"], "optionstype":["feedid"], "optionsname":[_Tr("Feed")], "optionshint":[_Tr("Feed source")], "html":"" }, "threshold": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","thresholdA","thresholdB","initzoom"], "optionstype":["feedid","value","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Threshold A"),_Tr("Threshold B"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Threshold A used"),_Tr("Threshold B used"),_Tr("Default visible window interval")], "optionsdata": [ , , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ], "html":"" }, "orderthreshold": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","power","thresholdA","thresholdB"], "optionstype":["feedid","feedid","value","value"], "optionsname":[_Tr("Feed"),_Tr("Power"),_Tr("Threshold A"),_Tr("Threshold B")], "optionshint":[_Tr("Feed source"),_Tr("Power"),_Tr("Threshold A used"),_Tr("Threshold B used")], "html":"" }, "orderbars": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","delta"], "optionstype":["feedid","boolean"], "optionsname":[_Tr("Feed"),_Tr("delta")], "optionshint":[_Tr("Feed source"),_Tr("Show difference between each bar")], "html":"" }, "stacked": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["bottom","top","colourt","colourb","delta"], "optionstype":["feedid","feedid","colour_picker","colour_picker","boolean"], "optionsname":[_Tr("Bottom"),_Tr("Top"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("delta")], "optionshint":[_Tr("Bottom feed value"),_Tr("Top feed value"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("Show difference between each bar")], "html":"" }, "stackedsolar": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["solar","consumption","delta"], "optionstype":["feedid","feedid","boolean"], "optionsname":[_Tr("Solar"),_Tr("Consumption"),_Tr("delta")], "optionshint":[_Tr("Solar feed value"),_Tr("Consumption feed value"),_Tr("Show difference between each bar")], "html":"" }, "smoothie": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","ufac"], "optionstype":["feedid","value"], "optionsname":[_Tr("Feed"),_Tr("Ufac")], "optionshint":[_Tr("Feed source"),_Tr("Ufac value")], "html":"" }, "multigraph": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["mid"], "optionstype":["dropbox"], "optionsname":[_Tr("Multigraph")], "optionshint":[_Tr("Managed on Visualization module")], "optionsdata":[multigraphsDropBoxOptions], // Gets multigraphs from vis_widget.php multigraphsDropBoxOptions variable "html":"" }, "timecompare": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","fill","depth","npoints","initzoom"], "optionstype":["feedid","value","value","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Fill"),_Tr("Depth"),_Tr("Data points"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Fill under line"),_Tr("Number of lines"),_Tr("Default: 800"),_Tr("Default visible window interval")], "optionsdata": [ , , , , [["8", "8 " + _Tr("Hours")],["24", _Tr("Day")],["168", _Tr("Week")],["672", _Tr("Month")],["8760", _Tr("Year")]] ], "html":"" } } return widgets; } function vis_init(){ vis_draw(); } function vis_draw(){ var vislist = vis_widgetlist(); var visclasslist = ''; for (z in vislist) { visclasslist += '.'+z+','; } visclasslist = visclasslist.slice(0, -1); $(visclasslist).each(function(){ var id = $(this).attr("id"); var feed = $(this).attr("feed") || 0; var width = $(this).width(); var height = $(this).height(); var apikey_string = ""; if (apikey) apikey_string = "&apikey="+apikey; if (!$(this).html() || reloadiframe==id || reloadiframe==-1 || apikey){ var attrstring = ""; var target = $(this).get(0); var l = target.attributes.length; for (var i=0; i<l; i++){ var attr = target.attributes[i].name; if (attr!="id" && attr!="class" && attr!="style"){ attrstring += "&"+attr+"="+target.attributes[i].value; } } pathfix=path.substr(path.indexOf('://')+3); // remove protocol pathfix=pathfix.substr(pathfix.indexOf('/')); // remove hostname $(this).html('<iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string+'"></iframe>'); console.log('--> new relative url for iframe of '+ $(this).attr("class") + ': '+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string); } var iframe = $(this).children('iframe'); iframe.width(width); iframe.height(height); }); reloadiframe = 0; } function vis_slowupdate() {} function vis_fastupdate() {}
thaipowertech/emoncms
Modules/vis/widget/vis_render.js
JavaScript
agpl-3.0
9,506
const passport = require('../helpers/auth/passport_factory'); const logger = require('../../lib/logger'); const adminChecker = require('../helpers/auth/request_admin_checker'); const oauthConfig = require('../../config/oauth/oauth_config.js'); module.exports.logout = function(req, res) { req.logout(); res.status(200).json({}); }; module.exports.loginTwitter = function(req, res, next) { passport.authenticate('twitter')(req, res, next); }; module.exports.loginInstagram = function(req, res, next) { passport.authenticate('instagram', {scope: 'basic', failWithError: true})(req, res, next); }; module.exports.loginFacebook = function(req, res, next) { passport.authenticate('facebook', {scope: 'email', session:false})(req, res, next); }; module.exports.loginGoogle = function(req, res, next) { passport.authenticate('google', { scope: ['email'] })(req, res, next); }; module.exports.loginCallbackTwitter = function(req, res) { passport.authenticate('twitter')(req, res, function(err) { if (err) { logger.error('Error logging in with twitter:' + err); res.status(403).json({'message': err}); return; } res.redirect(oauthConfig.get('redirectURLOnSuccessfulLogin')); }); }; module.exports.loginCallbackFacebook = function(req, res) { passport.authenticate('facebook')(req, res, function(err){ if (err) { logger.error('Error logging in with facebook:' + err); res.status(403).json({'message': err}); return; } res.redirect(oauthConfig.get('redirectURLOnSuccessfulLogin')); }); }; module.exports.loginCallbackGoogle = function(req, res) { passport.authenticate('google')(req, res, function(err){ if (err) { logger.error('Error logging in with google:' + err); res.status(403).json({'message': err}); return; } res.redirect(oauthConfig.get('redirectURLOnSuccessfulLogin')); }); }; module.exports.getAccountPermissions = function(req, res) { if (!adminChecker.isLoggedIn(req)) { res.status(403).json({'message': 'Not logged in'}); return; } if (adminChecker.isRequestDirectoryAdmin(req)) { res.status(200).json({'directoryAdmin': true}); return; } let enterprisePermissions = adminChecker.getAuthenticatedEnterprisesByRequest(req); res.status(200).json( { 'directoryAdmin': false, 'authenticatedEnterprises': enterprisePermissions } ); };
cised-ca/social-enterprise-directory
api/controllers/account_controller.js
JavaScript
agpl-3.0
2,409
import { combineReducers } from 'redux' const FETCH_ENTRIES = 'FETCH_ENTRIES' const RECEIVE_ENTRIES = 'RECEIVE_ENTRIES' const RECEIVE_MORE_ENTRIES = 'RECEIVE_MORE_ENTRIES' const RECEIVE_ERROR = 'RECEIVE_ERROR' const INSERT_ENTRIES = 'INSERT_ENTRIES' const UPDATE_ENTRIES = 'UPDATE_ENTRIES' const DELETE_ENTRY = 'DELETE_ENTRY' const EMIT_ERROR = 'EMIT_ERROR' const entries = (state = [], action) => { switch (action.type) { case RECEIVE_MORE_ENTRIES: return [...state, ...action.entries] case RECEIVE_ENTRIES: return action.entries case INSERT_ENTRIES: return [...action.entries, ...state] case UPDATE_ENTRIES: return state.map(entry => { let updatedEntry = action.entries.find( actionEntry => actionEntry._id === entry._id ) return updatedEntry || entry }) case DELETE_ENTRY: // TODO: quick and dirty fix for removeFromAlbum (we got IDs instead of photos) const id = typeof action.entity === 'object' ? action.entity.id || action.entity._id : action.entity // TODO: why is the back sending an id prop instead of a _id prop here??? const idx = state.findIndex(e => e._id === id) if (idx === -1) return state return [...state.slice(0, idx), ...state.slice(idx + 1)] default: return state } } const fetchStatus = (state = 'pending', action) => { switch (action.type) { case FETCH_ENTRIES: return 'loading' case RECEIVE_ENTRIES: return 'loaded' case RECEIVE_ERROR: return 'failed' default: return state } } const lastFetch = (state = null, action) => { switch (action.type) { case RECEIVE_ENTRIES: case RECEIVE_MORE_ENTRIES: return Date.now() default: return state } } const hasMore = (state = false, action) => { switch (action.type) { case RECEIVE_ENTRIES: case RECEIVE_MORE_ENTRIES: return action.next !== undefined ? action.next : state default: return state } } const index = (state = null, action) => { switch (action.type) { case RECEIVE_ENTRIES: return action.index !== undefined ? action.index : state default: return state } } const listReducer = combineReducers({ entries, fetchStatus, lastFetch, hasMore, index }) const listsReducer = (state = {}, action) => { switch (action.type) { case FETCH_ENTRIES: case RECEIVE_ENTRIES: case RECEIVE_MORE_ENTRIES: case RECEIVE_ERROR: case INSERT_ENTRIES: case UPDATE_ENTRIES: case DELETE_ENTRY: return Object.assign({}, state, { [action.name]: listReducer(state[action.name] || {}, action) }) default: return state } } export default listsReducer export const createFetchAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { let fetchingMoreEntries = false const existingList = getList(getState(), listName) if (existingList) { const { fetchStatus, hasMore } = existingList fetchingMoreEntries = fetchStatus === 'loaded' && hasMore === true } if (!fetchingMoreEntries) { dispatch({ type: FETCH_ENTRIES, name: listName }) } return saga(...args) .then(resp => { return fetchingMoreEntries && resp.skip !== 0 ? dispatch({ type: RECEIVE_MORE_ENTRIES, name: listName, ...resp }) : dispatch({ type: RECEIVE_ENTRIES, name: listName, ...resp }) }) .catch(error => dispatch({ type: RECEIVE_ERROR, name: listName, error }) ) } } } const shouldRefetch = list => { if (!list) { return true } // here we could add conditions so that we don't refetch a list fetched 30s ago return true } export const createFetchIfNeededAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) if (existingList && !shouldRefetch(existingList)) { return Promise.resolve(existingList) } return dispatch(createFetchAction(listName, saga)(...args)) } } } export const createInsertAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) return saga(...args).then(resp => { if (existingList) { return dispatch(insertAction(listName, resp)) } else { return resp } }) } } } export const createUpdateAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) return saga(...args).then(resp => { if (existingList) { return dispatch(updateAction(listName, resp)) } else { return resp } }) } } } export const createDeleteAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) return saga(...args).then(resp => { if (existingList) { resp.entries.forEach(e => dispatch(deleteAction(listName, e))) } return resp }) } } } export const errorAction = (listName, error) => ({ type: EMIT_ERROR, name: listName, error, alert: { message: error.message || error } }) // TODO: remove the discrepancy between insert and deleteAction inputs (full response with entries vs single entry) export const insertAction = (listName, resp) => ({ type: INSERT_ENTRIES, name: listName, ...resp }) export const updateAction = (listName, resp) => ({ type: UPDATE_ENTRIES, name: listName, ...resp }) export const deleteAction = (listName, entity) => ({ type: DELETE_ENTRY, name: listName, entity }) export const getList = (state, name) => state.lists[name]
enguerran/cozy-files-v3
src/photos/ducks/lists/index.js
JavaScript
agpl-3.0
5,918
(function () { 'use strict'; var WindowSize = Class.create({ width: function() { var myWidth = 0; if (typeof(window.innerWidth) == 'number') { //Non-IE myWidth = window.innerWidth; } else if (document.documentElement && document.documentElement.clientWidth) { //IE 6+ in 'standards compliant mode' myWidth = document.documentElement.clientWidth; } else if (document.body && document.body.clientWidth) { //IE 4 compatible myWidth = document.body.clientWidth; } return myWidth; }, height: function() { var myHeight = 0; if (typeof(window.innerHeight) == 'number') { //Non-IE myHeight = window.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { //IE 6+ in 'standards compliant mode' myHeight = document.documentElement.clientHeight; } else if (document.body && document.body.clientHeight) { //IE 4 compatible myHeight = document.body.clientHeight; } return myHeight; }, scrollTop: function (){ return document.viewport.getScrollOffsets()['top']; } }); var dateTimePicker = function (element, options){ var picker = {}, date, viewDate, unset = true, input, component = false, widget = false, use24Hours, minViewModeNumber = 0, actualFormat, parseFormats, currentViewMode, datePickerModes = [ { clsName: 'days', navFnc: 'M', navStep: 1 }, { clsName: 'months', navFnc: 'y', navStep: 1 }, { clsName: 'years', navFnc: 'y', navStep: 10 }, { clsName: 'decades', navFnc: 'y', navStep: 100 } ], viewModes = ['days', 'months', 'years', 'decades'], verticalModes = ['top', 'bottom', 'auto'], horizontalModes = ['left', 'right', 'auto'], toolbarPlacements = ['default', 'top', 'bottom'], keyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, keyState = {}, /******************************************************************************** * * Private functions * ********************************************************************************/ hasTimeZone = function () { return moment.tz !== undefined && options.timeZone !== undefined && options.timeZone !== null && options.timeZone !== ''; }, getMoment = function (d) { var returnMoment; if (d === undefined || d === null) { returnMoment = moment(); //TODO should this use format? and locale? } else if (moment.isDate(d) || moment.isMoment(d)) { // If the date that is passed in is already a Date() or moment() object, // pass it directly to moment. returnMoment = moment(d); } else if (hasTimeZone()) { // There is a string to parse and a default time zone // parse with the tz function which takes a default time zone if it is not in the format string returnMoment = moment.tz(d, parseFormats, options.useStrict, options.timeZone); } else { returnMoment = moment(d, parseFormats, options.useStrict); } if (hasTimeZone()) { returnMoment.tz(options.timeZone); } return returnMoment; }, isEnabled = function (granularity) { if (typeof granularity !== 'string' || granularity.length > 1) { throw new TypeError('isEnabled expects a single character string parameter'); } switch (granularity) { case 'y': return actualFormat.indexOf('Y') !== -1; case 'M': return actualFormat.indexOf('M') !== -1; case 'd': return actualFormat.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return actualFormat.toLowerCase().indexOf('h') !== -1; case 'm': return actualFormat.indexOf('m') !== -1; case 's': return actualFormat.indexOf('s') !== -1; default: return false; } }, hasTime = function () { return (isEnabled('h') || isEnabled('m') || isEnabled('s')); }, hasDate = function () { return (isEnabled('y') || isEnabled('M') || isEnabled('d')); }, getDatePickerTemplate = function () { var headTemplate = [ '<thead>', '<tr>', '<th class="prev" data-action="previous">', '<span class="'+options.icons.previous+'"/>', '</th>', '<th class="picker-switch" data-action="pickerSwitch" colspan="'+(options.calendarWeeks?'6':'5')+'"></th>', '<th class="next" data-action="next">', '<span class="'+options.icons.next+'"/>', '</th>', '</tr>', '</thead>' ].join(''), contTemplate = [ '<tbody>', '<tr>', '<td colspan="'+(options.calendarWeeks?'8':'7')+'"/>', '</tr>', '<tbody>' ].join(''); return [ new Element('div', {className:'datepicker-days'}).update([ '<table class="table-condensed">', headTemplate, '<tbody/>', '</table>' ].join('')), new Element('div', {className:'datepicker-months'}).update([ '<table class="table-condensed">', headTemplate, contTemplate, '</table>' ].join('')), new Element('div', {className:'datepicker-years'}).update([ '<table class="table-condensed">', headTemplate, contTemplate, '</table>' ].join('')), new Element('div', {className:'datepicker-decades'}).update([ '<table class="table-condensed">', headTemplate, contTemplate, '</table>' ].join('')) ]; }, getTimePickerMainTemplate = function (){ var topRow = ['<tr>'], middleRow = ['<tr>'], bottomRow = ['<tr>']; if (isEnabled('h')) { topRow.splice(topRow.length, 0, '<td>', '<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementHour+'" data-action="incrementHours">', '<span class="'+options.icons.up+'"/>', '</a>', '</td>'); middleRow.splice(middleRow.length, 0, '<td>', '<span class="timepicker-hour" data-time-component="hours" title="'+options.tooltips.pickHour+'" data-action="showHours"/>', '</td>'); bottomRow.splice(bottomRow.length, 0, '<td>', '<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementHour+'" data-action="decrementHours"/>', '<span class="'+options.icons.down+'"/>', '</a>', '</td>'); } if (isEnabled('m')) { if (isEnabled('h')) { topRow.push('<td class="separator"></td>'); middleRow.push('<td class="separator">:</td>'); bottomRow.push('<td class="separator"></td>'); } topRow.splice(topRow.length, 0, '<td>', '<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementMinute+'" data-action="incrementMinutes">', '<span class="'+options.icons.up+'"/>', '</a>', '</td>'); middleRow.splice(middleRow.length, 0, '<td>', '<span class="timepicker-minute" data-time-component="minute" title="'+options.tooltips.pickMinute+'" data-action="showMinutes"/>', '</td>'); bottomRow.splice(bottomRow.length, 0, '<td>', '<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementMinute+'" data-action="decrementMinutes"/>', '<span class="'+options.icons.down+'"/>', '</a>', '</td>'); } if (isEnabled('s')) { if (isEnabled('m')) { topRow.push('<td class="separator"></td>'); middleRow.push('<td class="separator">:</td>'); bottomRow.push('<td class="separator"></td>'); } topRow.splice(topRow.length, 0, '<td>', '<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementSecond+'" data-action="incrementSeconds">', '<span class="'+options.icons.up+'"/>', '</a>', '</td>'); middleRow.splice(middleRow.length, 0, '<td>', '<span class="timepicker-second" data-time-component="seconds" title="'+options.tooltips.pickSecond+'" data-action="showSeconds"/>', '</td>'); bottomRow.splice(bottomRow.length, 0, '<td>', '<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementSecond+'" data-action="decrementSeconds"/>', '<span class="'+options.icons.down+'"/>', '</a>', '</td>'); } if (!use24Hours){ topRow.push('<td class="separator"/>'); middleRow.splice(middleRow.length, 0, '<td>', '<button class="btn btn-primary" data-action="togglePeriod" tabindex="-1"', ' title="'+options.tooltips.togglePeriod+'"/>', '</td>'); bottomRow.push('<td class="separator"/>'); } topRow.push('</tr>') middleRow.push('</tr>') bottomRow.push('</tr>') var content = [ '<table class="table-condensed">', topRow.join(''), middleRow.join(''), bottomRow.join(''), '</table>' ].join(''); return new Element('div', {className:'timepicker-picker'}).update(content); }, getTimePickerTemplate = function () { var hoursView = new Element('div', {className:'timepicker-hours'}).update('<table class="table-condensed"></table>'), minutesView = new Element('div', {className:'timepicker-minutes'}).update('<table class="table-condensed"></table>'), secondsView = new Element('div', {className:'timepicker-seconds'}).update('<table class="table-condensed"></table>'), ret = [getTimePickerMainTemplate()]; if (isEnabled('h')) { ret.push(hoursView); } if (isEnabled('m')) { ret.push(minutesView); } if (isEnabled('s')) { ret.push(secondsView); } return ret; }, getToolbar = function () { var row = ['<tbody><tr>']; if (options.showTodayButton) { row.splice(row.length, 0, '<td>', '<a data-action="today" title="'+options.tooltips.today+'">', '<span class="'+options.icons.today+'"/>', '</a>', '</td>' ); } if (!options.sideBySide && hasDate() && hasTime()){ row.splice(row.length, 0, '<td>', '<a data-action="togglePicker" title="'+options.tooltips.selectTime+'">', '<span class="'+options.icons.time+'"/>', '</a>', '</td>' ); } if (options.showClear) { row.splice(row.length, 0, '<td>', '<a data-action="clear" title="'+options.tooltips.clear+'">', '<span class="'+options.icons.clear+'"/>', '</a>', '</td>' ); } if (options.showClose) { row.splice(row.length, 0, '<td>', '<a data-action="close" title="'+options.tooltips.close+'">', '<span class="'+options.icons.close+'"/>', '</a>', '</td>' ); } row.push('</tr></tbody>') return new Element('table', { className: 'table-condensed' }).update(row.join('')); }, getTemplate = function () { var template = new Element('div', {className: 'bootstrap-datetimepicker-widget dropdown-menu'}), dateView = new Element('div', {className: 'datepicker'}), timeView = new Element('div', {className: 'timepicker'}), content = new Element('ul', {className: 'list-unstyled'}), toolbar = new Element('li', {className: 'picker-switch' + (options.collapse ? ' accordion-toggle' : '')}).update(getToolbar()); $A(getDatePickerTemplate()).each(function(el){ dateView.insert(el); }); $A(getTimePickerTemplate()).each(function(el){ timeView.insert(el); }); if (options.inline) { template.removeClassName('dropdown-menu'); } if (use24Hours) { template.addClassName('usetwentyfour'); } if (isEnabled('s') && !use24Hours) { template.addClassName('wider'); } if (options.sideBySide && hasDate() && hasTime()){ template.addClassName('timepicker-sbs'); if (options.toolbarPlacement === 'top') { template.insert(toolbar); } template.insert( new Element('div', {className:'row'}) .insert(dateView.addClassName('col-md-6')) .insert(timeView.addClassName('col-md-6')) ); if (options.toolbarPlacement === 'bottom'){ template.insert(toolbar); } return template; } if (options.toolbarPlacement === 'top'){ content.insert(toolbar); } if (hasDate()){ content.insert(new Element('li', {className: (options.collapse && hasTime() ? 'collapse in' : '')}).update(dateView)); } if (options.toolbarPlacement === 'default'){ content.insert(toolbar); } if (hasTime()){ content.insert(new Element('li', {className: (options.collapse && hasDate() ? 'collapse' : '')}).update(timeView)); } if (options.toolbarPlacement === 'bottom'){ content.insert(toolbar); } return template.insert(content); }, dataToOptions = function(){ var dateOptions, dataOptions = {}; if (element.match('input') || options.inline) { dateOptions = element.retrieve('dateoptions'); } else { dateOptions = element.select('input').first().retrieve('dateoptions'); } if (dateOptions && dateOptions instanceof Object) { dataOptions = Object.extend(dataOptions, dateOptions); } $A(options).each(function (key){ var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); if (dateOptions[attributeName] !== undefined) { dataOptions[key] = dateOptions[attributeName]; } }); return dataOptions; }, hasFocus = function (elem){ return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, falseFn = function (e){ e.stop(); return false; }, place = function () { var eLayout = (component || element).getLayout(true), position = { top: eLayout.get('top'), left: eLayout.get('left') }, offset = (component || element).cumulativeOffset(), vertical = options.widgetPositioning.vertical, horizontal = options.widgetPositioning.horizontal, parent; /*if (options.widgetParent) { parent = options.widgetParent.insert(widget); } else if (element.match('input')) { parent = element.insert({after: widget}).up(); } else if (options.inline) { parent = element.insert(widget); return; } else { parent = element; element.childElements().first().insert({after: widget}); }*/ component.insert(widget); parent = component; var windowSize = new WindowSize(); var wLayout = widget.getLayout(true); var eOuterHeight = eLayout.get('height') + eLayout.get('border-box-height'); var eOuterWidth = eLayout.get('width') + eLayout.get('border-box-width'); // Top and bottom logic if (vertical === 'auto'){ if (offset.top + wLayout.get('height') * 1.5 >= windowSize.height() + windowSize.scrollTop() && wLayout.get('height') + eOuterHeight < offset.top){ vertical = 'top'; } else { vertical = 'bottom'; } } var pLayout = parent.getLayout(true); var pOuterHeight = pLayout.get('height') + pLayout.get('border-box-height'); var pOuterWidth = pLayout.get('width') + pLayout.get('border-box-width'); // Left and right logic if (horizontal === 'auto'){ var outerWidth = wLayout.get('width') + wLayout.get('border-box-width'); if (pLayout.get('width') < offset.left + outerWidth / 2 && offset.left + outerWidth > windowSize.width()){ horizontal = 'right'; } else { horizontal = 'left'; } } widget.addClassName('bottom'); /*if (vertical === 'top') { widget.addClassName('top').removeClassName('bottom'); } else { widget.addClassName('bottom').removeClassName('top'); }*/ widget.removeClassName('pull-right'); /* if (horizontal === 'right') { widget.addClassName('pull-right'); } else { widget.removeClassName('pull-right'); }*/ // find the first parent element that has a non-static css positioning if (parent.getStyle('position') === 'static'){ parent = parent.ancestors().filter(function (it) { return $(it).getStyle('position') !== 'static'; }).first(); } if (!parent) { throw new Error('datetimepicker component should be placed within a non-static positioned container'); } var parentsZindex = [0]; widget.ancestors().each(function(a){ var itemZIndex = $(a).getStyle('z-index'); if (itemZIndex !== 'auto' && Number(itemZIndex) !== 0) parentsZindex.push(Number(itemZIndex)); }); var zIndex = Math.max.apply(Math, parentsZindex) + 10; //console.log([vertical, horizontal, position, eOuterHeight, pOuterHeight, pOuterWidth]); /*ToDo: Correct this to properly calculate positioning var style = { top: vertical === 'top' ? 'auto' : (position.top + eOuterHeight)+'px', bottom: vertical === 'top' ? (pOuterHeight - (parent === element ? 0 : position.top))+'px' : 'auto', left: horizontal === 'left' ? (parent === element ? 0 : position.left)+'px' : 'auto', right: horizontal === 'left' ? 'auto' : (pOuterWidth - eOuterWidth - (parent === element ? 0 : position.left))+'px', zIndex: zIndex };*/ var style = { top: '26px', left: 0, right: 'auto', bottom: 'auto', zIndex: zIndex }; //console.log(style); widget.setStyle(style); }, notifyEvent = function (e) { if (e.type === 'dp:change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) { return; } element.fire(e.type, e); }, viewUpdate = function (e) { if (e === 'y') { e = 'YYYY'; } notifyEvent({ type: 'dp:update', change: e, viewDate: viewDate.clone() }); }, showMode = function (dir) { if (!widget) { return; } if (dir){ currentViewMode = Math.max(minViewModeNumber, Math.min(3, currentViewMode + dir)); } widget.select('.datepicker > div').each(function(el){ el.hide(); if (el.match('.datepicker-' + datePickerModes[currentViewMode].clsName)){ el.setStyle({display: 'block'}); } }); }, fillDow = function () { var row = new Element('tr'), currentDate = viewDate.clone().startOf('w').startOf('d'); if (options.calendarWeeks === true) { row.insert(new Element('th', {className: 'cw'}).update('#')); } while (currentDate.isBefore(viewDate.clone().endOf('w'))) { row.insert(new Element('th', {className: 'dow'}).update(currentDate.format('dd'))); currentDate.add(1, 'd'); } widget.select('.datepicker-days thead').first().insert(row); }, isInDisabledDates = function (testDate) { return options.disabledDates[testDate.format('YYYY-MM-DD')] === true; }, isInEnabledDates = function (testDate) { return options.enabledDates[testDate.format('YYYY-MM-DD')] === true; }, isInDisabledHours = function (testDate) { return options.disabledHours[testDate.format('H')] === true; }, isInEnabledHours = function (testDate) { return options.enabledHours[testDate.format('H')] === true; }, isValid = function (targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (options.disabledDates && granularity === 'd' && isInDisabledDates(targetMoment)) { return false; } if (options.enabledDates && granularity === 'd' && !isInEnabledDates(targetMoment)) { return false; } if (options.minDate && targetMoment.isBefore(options.minDate, granularity)) { return false; } if (options.maxDate && targetMoment.isAfter(options.maxDate, granularity)) { return false; } if (options.daysOfWeekDisabled && granularity === 'd' && options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && isInDisabledHours(targetMoment)) { return false; } if (options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !isInEnabledHours(targetMoment)) { return false; } if (options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $A(options.disabledTimeIntervals).each(function (it) { if (targetMoment.isBetween(it[0], it[1])) { found = true; return false; } }); if (found) { return false; } } return true; }, fillMonths = function () { var spans = [], monthsShort = viewDate.clone().startOf('y').startOf('d'), tdMonths = widget.select('.datepicker-months td').first(); tdMonths.update(''); while (monthsShort.isSame(viewDate, 'y')) { //spans.push($('<span>').attr('data-action', 'selectMonth').addClassName('month').text(monthsShort.format('MMM'))); tdMonths.insert(new Element('span', {'data-action':'selectMonth', className: 'month'}).update(monthsShort.format('MMM'))); monthsShort.add(1, 'M'); } //widget.find('.datepicker-months td').empty().append(spans); }, updateMonths = function () { var monthsView = widget.select('.datepicker-months').first(), monthsViewHeader = monthsView.select('th'), months = monthsView.select('tbody').first().select('span'); var mvh0 = Prototype.Selector.find(monthsViewHeader, 'th', 0); if (mvh0 && mvh0.down('span')) mvh0.down('span').writeAttribute('title', options.tooltips.prevYear); var mvh1 = Prototype.Selector.find(monthsViewHeader, 'th', 1); if (mvh1 && mvh1.down('span')) mvh1.down('span').writeAttribute('title', options.tooltips.selectYear); var mvh2 = Prototype.Selector.find(monthsViewHeader, 'th', 2); if (mvh2 && mvh2.down('span')) mvh2.down('span').writeAttribute('title', options.tooltips.nextYear); monthsView.select('.disabled').each(function(el){el.removeClassName('disabled');}); if (!isValid(viewDate.clone().subtract(1, 'y'), 'y')) { mvh0.addClassName('disabled'); } mvh1.update(viewDate.year()); if (!isValid(viewDate.clone().add(1, 'y'), 'y')) { mvh2.addClassName('disabled'); } months.each(function (el){el.removeClassName('active');}); if (date.isSame(viewDate, 'y') && !unset) { Prototype.Selector.find(months, 'span', date.month()).addClassName('active'); } months.each(function (month, index) { if (!isValid(viewDate.clone().month(index), 'M')) { month.addClassName('disabled'); } }); }, updateYears = function () { var yearsView = widget.select('.datepicker-years').first(), yearsViewHeader = yearsView.select('th'), startYear = viewDate.clone().subtract(5, 'y'), endYear = viewDate.clone().add(6, 'y'), html = ''; var yvh0 = Prototype.Selector.find(yearsViewHeader, 'th', 0); if (yvh0 && yvh0.down('span')) yvh0.down('span').writeAttribute('title', options.tooltips.prevDecade); var yvh1 = Prototype.Selector.find(yearsViewHeader, 'th', 1); if (yvh1 && yvh1.down('span')) yvh1.down('span').writeAttribute('title', options.tooltips.selectDecade); var yvh2 = Prototype.Selector.find(yearsViewHeader, 'th', 2); if (yvh1 && yvh2.down('span')) yvh2.down('span').writeAttribute('title', options.tooltips.nextDecade); yearsView.select('.disabled').each(function(el){el.removeClassName('disabled');}); if (options.minDate && options.minDate.isAfter(startYear, 'y')) { yvh0.addClassName('disabled'); } yvh1.update(startYear.year() + '-' + endYear.year()); if (options.maxDate && options.maxDate.isBefore(endYear, 'y')) { yvh2.addClassName('disabled'); } while (!startYear.isAfter(endYear, 'y')) { html += '<span data-action="selectYear" class="year' + (startYear.isSame(date, 'y') && !unset ? ' active' : '') + (!isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } yearsView.select('td').each(function(td){ td.update(html);}); }, updateDecades = function () { var decadesView = widget.select('.datepicker-decades').first(), decadesViewHeader = decadesView.select('th'), startDecade = moment({ y: viewDate.year() - (viewDate.year() % 100) - 1 }), endDecade = startDecade.clone().add(100, 'y'), startedAt = startDecade.clone(), minDateDecade = false, maxDateDecade = false, endDecadeYear, html = ''; var dvh0 = Prototype.Selector.find(decadesViewHeader, 'th', 0); if (dvh0 && dvh0.down('span')) dvh0.down('span').writeAttribute('title', options.tooltips.prevCentury); var dvh1 = Prototype.Selector.find(decadesViewHeader, 'th', 1); var dvh2 = Prototype.Selector.find(decadesViewHeader, 'th', 2); if (dvh2 && dvh2.down('span')) dvh2.down('span').writeAttribute('title', options.tooltips.nextCentury); decadesView.select('.disabled').each(function(el){el.removeClassName('disabled');}); if (startDecade.isSame(moment({ y: 1900 })) || (options.minDate && options.minDate.isAfter(startDecade, 'y'))) { dvh0.addClassName('disabled'); } dvh1.update(startDecade.year() + '-' + endDecade.year()); if (startDecade.isSame(moment({ y: 2000 })) || (options.maxDate && options.maxDate.isBefore(endDecade, 'y'))) { dvh2.addClassName('disabled'); } while (!startDecade.isAfter(endDecade, 'y')) { endDecadeYear = startDecade.year() + 12; minDateDecade = options.minDate && options.minDate.isAfter(startDecade, 'y') && options.minDate.year() <= endDecadeYear; maxDateDecade = options.maxDate && options.maxDate.isAfter(startDecade, 'y') && options.maxDate.year() <= endDecadeYear; html += '<span data-action="selectDecade" class="decade' + (date.isAfter(startDecade) && date.year() <= endDecadeYear ? ' active' : '') + (!isValid(startDecade, 'y') && !minDateDecade && !maxDateDecade ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + '</span>'; startDecade.add(12, 'y'); } html += '<span></span><span></span><span></span>'; //push the dangling block over, at least this way it's even decadesView.select('td').each(function(td){td.update(html);}); dvh1.update((startedAt.year() + 1) + '-' + (startDecade.year())); }, fillDate = function () { var daysView = widget.select('.datepicker-days').first(), daysViewHeader = daysView.select('th'), currentDate, html = [], row, clsNames = [], i; if (!hasDate()) { return; } var dvh0 = Prototype.Selector.find(daysViewHeader, 'th', 0); if (dvh0 && dvh0.down('span')) dvh0.down('span').writeAttribute('title', options.tooltips.prevMonth); var dvh1 = Prototype.Selector.find(daysViewHeader, 'th', 1); if (dvh1 && dvh1.down('span')) dvh1.down('span').writeAttribute('title', options.tooltips.selectMonth); var dvh2 = Prototype.Selector.find(daysViewHeader, 'th', 2); if (dvh2 && dvh2.down('span')) dvh2.down('span').writeAttribute('title', options.tooltips.nextMonth); daysView.select('.disabled').each(function(el) { el.removeClassName('disabled');}); dvh1.update(viewDate.format(options.dayViewHeaderFormat)); if (!isValid(viewDate.clone().subtract(1, 'M'), 'M')) { dvh0.addClassName('disabled'); } if (!isValid(viewDate.clone().add(1, 'M'), 'M')) { dvh2.addClassName('disabled'); } currentDate = viewDate.clone().startOf('M').startOf('w').startOf('d'); for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) if (currentDate.weekday() === 0) { row = new Element('tr'); if (options.calendarWeeks) { row.insert('<td class="cw">' + currentDate.week() + '</td>'); } html.push(row); } clsNames = ['day']; if (currentDate.isBefore(viewDate, 'M')) { clsNames.push('old'); } if (currentDate.isAfter(viewDate, 'M')) { clsNames.push('new'); } if (currentDate.isSame(date, 'd') && !unset) { clsNames.push('active'); } if (!isValid(currentDate, 'd')) { clsNames.push('disabled'); } if (currentDate.isSame(getMoment(), 'd')) { clsNames.push('today'); } if (currentDate.day() === 0 || currentDate.day() === 6) { clsNames.push('weekend'); } notifyEvent({ type: 'dp:classify', date: currentDate, classNames: clsNames }); row.insert('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="' + clsNames.join(' ') + '">' + currentDate.date() + '</td>'); currentDate.add(1, 'd'); } var tbody = daysView.select('tbody').first().update(''); $A(html).each(function (it){ tbody.insert(it); }) updateMonths(); updateYears(); updateDecades(); }, fillHours = function () { var table = widget.select('.timepicker-hours table').first(), currentHour = viewDate.clone().startOf('d'), html = [], row = new Element('tr'); if (viewDate.hour() > 11 && !use24Hours) { currentHour.hour(12); } while (currentHour.isSame(viewDate, 'd') && (use24Hours || (viewDate.hour() < 12 && currentHour.hour() < 12) || viewDate.hour() > 11)) { if (currentHour.hour() % 4 === 0) { row = new Element('tr'); html.push(row); } row.insert('<td data-action="selectHour" class="hour' + (!isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(use24Hours ? 'HH' : 'hh') + '</td>'); currentHour.add(1, 'h'); } table.update(''); $A(html).each(function (r){table.insert(r);}); }, fillMinutes = function () { var table = widget.select('.timepicker-minutes table').first(), currentMinute = viewDate.clone().startOf('h'), html = [], row = new Element('tr'), step = options.stepping === 1 ? 5 : options.stepping; while (viewDate.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { row = new Element('tr'); html.push(row); } row.insert('<td data-action="selectMinute" class="minute' + (!isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'); currentMinute.add(step, 'm'); } table.update(''); $A(html).each(function(r){table.insert(r);}); }, fillSeconds = function () { var table = widget.select('.timepicker-seconds table').first(), currentSecond = viewDate.clone().startOf('m'), html = [], row = new Element('tr'); if (!table) return; while (viewDate.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { row = new Element('tr'); html.push(row); } row.insert('<td data-action="selectSecond" class="second' + (!isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'); currentSecond.add(5, 's'); } table.update(''); $A(html).each(function(r){table.insert(r);}); }, fillTime = function () { var toggle, newDate, timeComponents = widget.select('.timepicker span[data-time-component]'); if (!use24Hours) { toggle = widget.select('.timepicker [data-action=togglePeriod]').first(); newDate = date.clone().add((date.hours() >= 12) ? -12 : 12, 'h'); toggle.update(date.format('A')); if (isValid(newDate, 'h')) { toggle.removeClassName('disabled'); } else { toggle.addClassName('disabled'); } } timeComponents.each(function(tc){ if (tc.match('[data-time-component=hours]')){ tc.update(date.format(use24Hours ? 'HH' : 'hh')); } if (tc.match('[data-time-component=minute]')){ tc.update(date.format('mm')); } if (tc.match('[data-time-component=seconds]')){ tc.update(date.format(date.format('ss'))); } }) if (isEnabled('h')) fillHours(); if (isEnabled('m')) fillMinutes(); if (isEnabled('s')) fillSeconds(); }, update = function () { if (!widget) { return; } fillDate(); fillTime(); }, setValue = function (targetMoment) { var oldDate = unset ? null : date; // case of calling setValue(null or false) if (!targetMoment) { unset = true; input.setValue(''); input.store(date, ''); element.store('date', ''); notifyEvent({ type: 'dp:change', date: false, oldDate: oldDate }); update(); return; } targetMoment = targetMoment.clone().locale(options.locale); if (hasTimeZone()) { targetMoment.tz(options.timeZone); } if (options.stepping !== 1) { targetMoment.minutes((Math.round(targetMoment.minutes() / options.stepping) * options.stepping)).seconds(0); while (options.minDate && targetMoment.isBefore(options.minDate)) { targetMoment.add(options.stepping, 'minutes'); } } if (isValid(targetMoment)) { date = targetMoment; viewDate = date.clone(); input.setValue(date.format(actualFormat)); element.store('date', date.format(actualFormat)); input.store('date', date.toISOString()); unset = false; update(); notifyEvent({ type: 'dp:change', date: date.clone(), oldDate: oldDate }); } else { if (!options.keepInvalid) { Form.Element.setValue(input, unset ? '' : date.format(actualFormat)); } else { notifyEvent({ type: 'dp:change', date: targetMoment, oldDate: oldDate }); } notifyEvent({ type: 'dp:error', date: targetMoment, oldDate: oldDate }); } }, /// // Hides the widget. Possibly will emit dp:hide // hide = function () { var transitioning = false; if (!widget) { return picker; } // Ignore event if in the middle of a picker transition widget.select('.collapse').each(function (it) { var collapseData = it.retrieve('collapse'); if (collapseData && collapseData.transitioning) { transitioning = true; return false; } return true; }); if (transitioning) { return picker; } if (component && component.hasClassName('btn')) { component.toggleClassName('active'); } widget.hide(); Event.stopObserving(window, 'resize', place); widget.stopObserving('click', doAction); widget.stopObserving('mousedown', falseFn); widget.remove(); widget = false; notifyEvent({ type: 'dp:hide', date: date.clone() }); input.blur(); viewDate = date.clone(); return picker; }, clear = function () { setValue(null); }, parseInputDate = function (inputDate) { if (options.parseInputDate === undefined) { if (!moment.isMoment(inputDate) || inputDate instanceof Date) { inputDate = getMoment(inputDate); } } else { inputDate = options.parseInputDate(inputDate); } //inputDate.locale(options.locale); return inputDate; }, /******************************************************************************** * * Widget UI interaction functions * ********************************************************************************/ actions = { next: function () { var navFnc = datePickerModes[currentViewMode].navFnc; viewDate.add(datePickerModes[currentViewMode].navStep, navFnc); fillDate(); viewUpdate(navFnc); }, previous: function () { var navFnc = datePickerModes[currentViewMode].navFnc; viewDate.subtract(datePickerModes[currentViewMode].navStep, navFnc); fillDate(); viewUpdate(navFnc); }, pickerSwitch: function () { showMode(1); }, selectMonth: function (e) { //var month = $(e.target).closest('tbody').find('span').index($(e.target)); var month = $(e.target).previousSiblings().size(); viewDate.month(month); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year()).month(viewDate.month())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('M'); }, selectYear: function (e) { var year = parseInt($(e.target).innerText, 10) || 0; viewDate.year(year); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('YYYY'); }, selectDecade: function (e) { var year = parseInt($(e.target).readAttribute('data-selection'), 10) || 0; viewDate.year(year); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('YYYY'); }, selectDay: function (e) { var day = viewDate.clone(); if ($(e.target).match('.old')) { day.subtract(1, 'M'); } if ($(e.target).match('.new')) { day.add(1, 'M'); } setValue(day.date(parseInt($(e.target).innerText, 10))); if (!hasTime() && !options.keepOpen && !options.inline) { hide(); } }, incrementHours: function () { var newDate = date.clone().add(1, 'h'); if (isValid(newDate, 'h')) { setValue(newDate); } }, incrementMinutes: function () { var newDate = date.clone().add(options.stepping, 'm'); if (isValid(newDate, 'm')) { setValue(newDate); } }, incrementSeconds: function () { var newDate = date.clone().add(1, 's'); if (isValid(newDate, 's')) { setValue(newDate); } }, decrementHours: function () { var newDate = date.clone().subtract(1, 'h'); if (isValid(newDate, 'h')) { setValue(newDate); } }, decrementMinutes: function () { var newDate = date.clone().subtract(options.stepping, 'm'); if (isValid(newDate, 'm')) { setValue(newDate); } }, decrementSeconds: function () { var newDate = date.clone().subtract(1, 's'); if (isValid(newDate, 's')) { setValue(newDate); } }, togglePeriod: function () { setValue(date.clone().add((date.hours() >= 12) ? -12 : 12, 'h')); }, togglePicker: function (e) { var $this = $(e.target), $parent = $this.up('ul'), expanded = $parent.select('.in').first(), closed = $parent.select('.collapse:not(.in)').first(), collapseData; if (expanded) { collapseData = expanded.retrieve('collapse'); if (collapseData && collapseData.transitioning) { return; } expanded.removeClassName('in'); closed.addClassName('in'); if ($this.match('span')) { $this.toggleClassName(options.icons.time + ' ' + options.icons.date); } else { $this.down('span').toggleClassName(options.icons.time + ' ' + options.icons.date); } // NOTE: uncomment if toggled state will be restored in show() //if (component) { // component.find('span').toggleClass(options.icons.time + ' ' + options.icons.date); //} } }, showPicker: function () { widget.select('.timepicker > div:not(.timepicker-picker)').each(function(el){el.hide();}); widget.down('.timepicker .timepicker-picker').show(); }, showHours: function () { widget.down('.timepicker .timepicker-picker').hide(); widget.down('.timepicker .timepicker-hours').show(); }, showMinutes: function () { widget.down('.timepicker .timepicker-picker').hide(); widget.down('.timepicker .timepicker-minutes').show(); }, showSeconds: function () { widget.down('.timepicker .timepicker-picker').hide(); widget.down('.timepicker .timepicker-seconds').show(); }, selectHour: function (e) { var hour = parseInt($(e.target).innerText, 10); if (!use24Hours) { if (date.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } setValue(date.clone().hours(hour)); actions.showPicker.call(picker); }, selectMinute: function (e) { setValue(date.clone().minutes(parseInt($(e.target).innerText, 10))); actions.showPicker.call(picker); }, selectSecond: function (e) { setValue(date.clone().seconds(parseInt($(e.target).innerText, 10))); actions.showPicker.call(picker); }, clear: clear, today: function () { var todaysDate = getMoment(); if (isValid(todaysDate, 'd')) { setValue(todaysDate); } }, close: hide }, doAction = function (e) { Event.stop(e); var actionEl = e.findElement('[data-action]'); if (!actionEl) return false; if ($(e.target).match('.disabled')){ return false; } actions[actionEl.readAttribute('data-action')].apply(picker, arguments); return false; }, /// // Shows the widget. Possibly will emit dp:show and dp:change /// show = function () { var currentMoment, useCurrentGranularity = { 'year': function (m) { return m.month(0).date(1).hours(0).seconds(0).minutes(0); }, 'month': function (m) { return m.date(1).hours(0).seconds(0).minutes(0); }, 'day': function (m) { return m.hours(0).seconds(0).minutes(0); }, 'hour': function (m) { return m.seconds(0).minutes(0); }, 'minute': function (m) { return m.seconds(0); } }; if (input.readAttribute('disabled') || (!options.ignoreReadonly && input.readAttribute('readonly')) || widget) { return picker; } var val = input.retrieve('date'); if (!val){ val = $F(input); val = moment(val.trim(), actualFormat); } else { val = moment(val.trim()); } if (val !== undefined) { //} && val.trim().length !== 0) { setValue(parseInputDate(val)); } else if (unset && options.useCurrent && (options.inline || (input.match('input') && val.trim().length === 0))) { currentMoment = getMoment(); if (typeof options.useCurrent === 'string') { currentMoment = useCurrentGranularity[options.useCurrent](currentMoment); } setValue(currentMoment); } widget = getTemplate(); fillDow(); fillMonths(); widget.down('.timepicker-hours') && widget.down('.timepicker-hours').hide(); widget.down('.timepicker-minutes') && widget.down('.timepicker-minutes').hide(); widget.down('.timepicker-seconds') && widget.down('.timepicker-seconds').hide(); //ToDo: Enable this when safe update(); showMode(); Event.observe(window, 'resize', place); widget.observe('click', doAction); // this handles clicks on the widget widget.observe('mousedown', falseFn); if (component && component.hasClassName('btn')) { component.toggleClassName('active'); } place(); if (options.focusOnShow && !hasFocus(input)) { //return elem === document.activeElement && ( elem.type || elem.href ); input.focus(); } notifyEvent({ type: 'dp:show' }); return picker; }, /// // Shows or hides the widget /// toggle = function () { if (input.match('[disabled]')) return; return (widget ? hide() : show()); }, keydown = function (e) { var handler = null, index, index2, pressedKeys = [], pressedModifiers = {}, currentKey = e.which, keyBindKeys, allModifiersPressed, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in options.keyBinds) { if (options.keyBinds.hasOwnProperty(index) && typeof (options.keyBinds[index]) === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = options.keyBinds[index]; break; } } } } if (handler) { handler.call(picker, widget); e.stopPropagation(); e.preventDefault(); } }, keyup = function (e) { keyState[e.which] = 'r'; e.stopPropagation(); e.preventDefault(); }, change = function (e) { var val = $F($(e.target)).trim(), parsedDate = val ? parseInputDate(val) : null; setValue(parsedDate); e.stopImmediatePropagation(); return false; }, attachDatePickerElementEvents = function () { input.observe('change', change); input.observe('blur', options.debug ? Prototype.emptyFunction : hide); input.observe('keydown', keydown); input.observe('keyup', keyup); input.observe('focus', options.allowInputToggle ? show : Prototype.emptyFunction); if (element.match('input')) { input.observe('focus', show); } else if (component) { component.observe('click', toggle); component.observe('mousedown', falseFn); } },/* detachDatePickerElementEvents = function () { input.off({ 'change': change, 'blur': blur, 'keydown': keydown, 'keyup': keyup, 'focus': options.allowInputToggle ? hide : '' }); if (element.is('input')) { input.off({ 'focus': show }); } else if (component) { component.off('click', toggle); component.off('mousedown', false); } }, indexGivenDates = function (givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}; $.each(givenDatesArray, function () { var dDate = parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false; }, indexGivenHours = function (givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false; },*/ initFormatting = function () { var format = options.format || 'L LT'; actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { var newinput = date.localeData().longDateFormat(formatInput) || formatInput; return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740 return date.localeData().longDateFormat(formatInput2) || formatInput2; }); }); parseFormats = options.extraFormats ? options.extraFormats.slice() : []; if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(actualFormat) < 0){ parseFormats.push(actualFormat); } use24Hours = (actualFormat.toLowerCase().indexOf('a') < 1 && actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1); if (isEnabled('y')){ minViewModeNumber = 2; } if (isEnabled('M')){ minViewModeNumber = 1; } if (isEnabled('d')){ minViewModeNumber = 0; } currentViewMode = Math.max(minViewModeNumber, currentViewMode); if (!unset) { setValue(date); } }; /******************************************************************************** * * Public API functions * ===================== * * Important: Do not expose direct references to private objects or the options * object to the outer world. Always return a clone when returning values or make * a clone when setting a private variable. * ********************************************************************************/ picker.destroy = function () { ///<summary>Destroys the widget and removes all attached event listeners</summary> hide(); detachDatePickerElementEvents(); //element.removeData('DateTimePicker'); //element.removeData('date'); }; picker.toggle = toggle; picker.show = show; picker.hide = hide; picker.disable = function () { ///<summary>Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. ///If the widget was visible before that call it is hidden. Possibly emits dp:hide</summary> hide(); if (component && component.hasClassName('btn')) { component.addClassName('disabled'); } input.prop('disabled', true); return picker; }; picker.enable = function () { ///<summary>Enables the input element, the component is attached to, by removing disabled attribute from it.</summary> if (component && component.hasClassName('btn')) { component.removeClassName('disabled'); } input.prop('disabled', false); return picker; }; picker.ignoreReadonly = function (ignoreReadonly) { if (arguments.length === 0) { return options.ignoreReadonly; } if (typeof ignoreReadonly !== 'boolean') { throw new TypeError('ignoreReadonly () expects a boolean parameter'); } options.ignoreReadonly = ignoreReadonly; return picker; }; picker.options = function (newOptions) { if (arguments.length === 0) { return Object.extend({}, options); } if (!(newOptions instanceof Object)) { throw new TypeError('options() options parameter should be an object'); } Object.extend(options, newOptions); $H(options).each(function (pair) { if (picker[pair.key] !== undefined) { picker[pair.key](pair.value); } else { throw new TypeError('option ' + key + ' is not recognized!'); } }); return picker; }; picker.date = function (newDate) { ///<signature helpKeyword="$.fn.datetimepicker.date"> ///<summary>Returns the component's model current date, a moment object or null if not set.</summary> ///<returns type="Moment">date.clone()</returns> ///</signature> ///<signature> ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary> ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param> ///</signature> if (arguments.length === 0) { if (unset) { return null; } return date.clone(); } if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); } setValue(newDate === null ? null : parseInputDate(newDate)); return picker; }; picker.format = function (newFormat) { ///<summary>test su</summary> ///<param name="newFormat">info about para</param> ///<returns type="string|boolean">returns foo</returns> if (arguments.length === 0) { return options.format; } if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) { throw new TypeError('format() expects a string or boolean:false parameter ' + newFormat); } options.format = newFormat; if (actualFormat) { initFormatting(); // reinit formatting } return picker; }; picker.timeZone = function (newZone) { if (arguments.length === 0) { return options.timeZone; } if (typeof newZone !== 'string') { throw new TypeError('newZone() expects a string parameter'); } options.timeZone = newZone; return picker; }; picker.dayViewHeaderFormat = function (newFormat) { if (arguments.length === 0) { return options.dayViewHeaderFormat; } if (typeof newFormat !== 'string') { throw new TypeError('dayViewHeaderFormat() expects a string parameter'); } options.dayViewHeaderFormat = newFormat; return picker; }; picker.extraFormats = function (formats) { if (arguments.length === 0) { return options.extraFormats; } if (formats !== false && !(formats instanceof Array)) { throw new TypeError('extraFormats() expects an array or false parameter'); } options.extraFormats = formats; if (parseFormats) { initFormatting(); // reinit formatting } return picker; }; picker.disabledDates = function (dates) { ///<signature helpKeyword="$.fn.datetimepicker.disabledDates"> ///<summary>Returns an array with the currently set disabled dates on the component.</summary> ///<returns type="array">options.disabledDates</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledDates if such exist.</summary> ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> ///</signature> if (arguments.length === 0) { return (options.disabledDates ? Object.extend({}, options.disabledDates) : options.disabledDates); } if (!dates) { options.disabledDates = false; update(); return picker; } if (!(dates instanceof Array)) { throw new TypeError('disabledDates() expects an array parameter'); } options.disabledDates = indexGivenDates(dates); options.enabledDates = false; update(); return picker; }; picker.enabledDates = function (dates) { ///<signature helpKeyword="$.fn.datetimepicker.enabledDates"> ///<summary>Returns an array with the currently set enabled dates on the component.</summary> ///<returns type="array">options.enabledDates</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary> ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> ///</signature> if (arguments.length === 0) { return (options.enabledDates ? Object.extend({}, options.enabledDates) : options.enabledDates); } if (!dates) { options.enabledDates = false; update(); return picker; } if (!(dates instanceof Array)) { throw new TypeError('enabledDates() expects an array parameter'); } options.enabledDates = indexGivenDates(dates); options.disabledDates = false; update(); return picker; }; picker.daysOfWeekDisabled = function (daysOfWeekDisabled) { if (arguments.length === 0) { return options.daysOfWeekDisabled.splice(0); } if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) { options.daysOfWeekDisabled = false; update(); return picker; } if (!(daysOfWeekDisabled instanceof Array)) { throw new TypeError('daysOfWeekDisabled() expects an array parameter'); } options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) { currentValue = parseInt(currentValue, 10); if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { return previousValue; } if (previousValue.indexOf(currentValue) === -1) { previousValue.push(currentValue); } return previousValue; }, []).sort(); if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'd')) { date.add(1, 'd'); if (tries === 31) { throw 'Tried 31 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; picker.maxDate = function (maxDate) { if (arguments.length === 0) { return options.maxDate ? options.maxDate.clone() : options.maxDate; } if ((typeof maxDate === 'boolean') && maxDate === false) { options.maxDate = false; update(); return picker; } if (typeof maxDate === 'string') { if (maxDate === 'now' || maxDate === 'moment') { maxDate = getMoment(); } } var parsedDate = parseInputDate(maxDate); if (!parsedDate.isValid()) { throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate); } if (options.minDate && parsedDate.isBefore(options.minDate)) { throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat)); } options.maxDate = parsedDate; if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) { setValue(options.maxDate); } if (viewDate.isAfter(parsedDate)) { viewDate = parsedDate.clone().subtract(options.stepping, 'm'); } update(); return picker; }; picker.minDate = function (minDate) { if (arguments.length === 0) { return options.minDate ? options.minDate.clone() : options.minDate; } if ((typeof minDate === 'boolean') && minDate === false) { options.minDate = false; update(); return picker; } if (typeof minDate === 'string') { if (minDate === 'now' || minDate === 'moment') { minDate = getMoment(); } } var parsedDate = parseInputDate(minDate); if (!parsedDate.isValid()) { throw new TypeError('minDate() Could not parse date parameter: ' + minDate); } if (options.maxDate && parsedDate.isAfter(options.maxDate)) { throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat)); } options.minDate = parsedDate; if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) { setValue(options.minDate); } if (viewDate.isBefore(parsedDate)) { viewDate = parsedDate.clone().add(options.stepping, 'm'); } update(); return picker; }; picker.defaultDate = function (defaultDate) { ///<signature helpKeyword="$.fn.datetimepicker.defaultDate"> ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary> ///<returns type="Moment">date.clone()</returns> ///</signature> ///<signature> ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary> ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param> ///</signature> if (arguments.length === 0) { return options.defaultDate ? options.defaultDate.clone() : options.defaultDate; } if (!defaultDate) { options.defaultDate = false; return picker; } if (typeof defaultDate === 'string') { if (defaultDate === 'now' || defaultDate === 'moment') { defaultDate = getMoment(); } else { defaultDate = getMoment(defaultDate); } } var parsedDate = parseInputDate(defaultDate); if (!parsedDate.isValid()) { throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate); } if (!isValid(parsedDate)) { throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); } options.defaultDate = parsedDate; if ((options.defaultDate && options.inline) || input.val().trim() === '') { setValue(options.defaultDate); } return picker; }; picker.locale = function (locale) { if (arguments.length === 0) { return options.locale; } if (!moment.localeData(locale)) { throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!'); } options.locale = locale; options.tooltips = localeTooltips[locale] || options.locale; date.locale(options.locale); viewDate.locale(options.locale); if (actualFormat) { initFormatting(); // reinit formatting } if (widget) { hide(); show(); } return picker; }; picker.stepping = function (stepping) { if (arguments.length === 0) { return options.stepping; } stepping = parseInt(stepping, 10); if (isNaN(stepping) || stepping < 1) { stepping = 1; } options.stepping = stepping; return picker; }; picker.useCurrent = function (useCurrent) { var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; if (arguments.length === 0) { return options.useCurrent; } if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) { throw new TypeError('useCurrent() expects a boolean or string parameter'); } if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) { throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); } options.useCurrent = useCurrent; return picker; }; picker.collapse = function (collapse) { if (arguments.length === 0) { return options.collapse; } if (typeof collapse !== 'boolean') { throw new TypeError('collapse() expects a boolean parameter'); } if (options.collapse === collapse) { return picker; } options.collapse = collapse; if (widget) { hide(); show(); } return picker; }; picker.icons = function (icons) { if (arguments.length === 0) { return Object.extend({}, options.icons); } if (!(icons instanceof Object)) { throw new TypeError('icons() expects parameter to be an Object'); } Object.extend(options.icons, icons); if (widget) { hide(); show(); } return picker; }; picker.tooltips = function (tooltips) { if (arguments.length === 0) { return Object.extend({}, options.tooltips); } if (!(tooltips instanceof Object)) { throw new TypeError('tooltips() expects parameter to be an Object'); } Object.extend(options.tooltips, tooltips); if (widget) { hide(); show(); } return picker; }; picker.useStrict = function (useStrict) { if (arguments.length === 0) { return options.useStrict; } if (typeof useStrict !== 'boolean') { throw new TypeError('useStrict() expects a boolean parameter'); } options.useStrict = useStrict; return picker; }; picker.sideBySide = function (sideBySide) { if (arguments.length === 0) { return options.sideBySide; } if (typeof sideBySide !== 'boolean') { throw new TypeError('sideBySide() expects a boolean parameter'); } options.sideBySide = sideBySide; if (widget) { hide(); show(); } return picker; }; picker.viewMode = function (viewMode) { if (arguments.length === 0) { return options.viewMode; } if (typeof viewMode !== 'string') { throw new TypeError('viewMode() expects a string parameter'); } if (viewModes.indexOf(viewMode) === -1) { throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value'); } options.viewMode = viewMode; currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber); showMode(); return picker; }; picker.toolbarPlacement = function (toolbarPlacement) { if (arguments.length === 0) { return options.toolbarPlacement; } if (typeof toolbarPlacement !== 'string') { throw new TypeError('toolbarPlacement() expects a string parameter'); } if (toolbarPlacements.indexOf(toolbarPlacement) === -1) { throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); } options.toolbarPlacement = toolbarPlacement; if (widget) { hide(); show(); } return picker; }; picker.widgetPositioning = function (widgetPositioning) { if (arguments.length === 0) { return Object.extend({}, options.widgetPositioning); } if (({}).toString.call(widgetPositioning) !== '[object Object]') { throw new TypeError('widgetPositioning() expects an object variable'); } if (widgetPositioning.horizontal) { if (typeof widgetPositioning.horizontal !== 'string') { throw new TypeError('widgetPositioning() horizontal variable must be a string'); } widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase(); if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) { throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); } options.widgetPositioning.horizontal = widgetPositioning.horizontal; } if (widgetPositioning.vertical) { if (typeof widgetPositioning.vertical !== 'string') { throw new TypeError('widgetPositioning() vertical variable must be a string'); } widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase(); if (verticalModes.indexOf(widgetPositioning.vertical) === -1) { throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); } options.widgetPositioning.vertical = widgetPositioning.vertical; } update(); return picker; }; picker.calendarWeeks = function (calendarWeeks) { if (arguments.length === 0) { return options.calendarWeeks; } if (typeof calendarWeeks !== 'boolean') { throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); } options.calendarWeeks = calendarWeeks; update(); return picker; }; picker.showTodayButton = function (showTodayButton) { if (arguments.length === 0) { return options.showTodayButton; } if (typeof showTodayButton !== 'boolean') { throw new TypeError('showTodayButton() expects a boolean parameter'); } options.showTodayButton = showTodayButton; if (widget) { hide(); show(); } return picker; }; picker.showClear = function (showClear) { if (arguments.length === 0) { return options.showClear; } if (typeof showClear !== 'boolean') { throw new TypeError('showClear() expects a boolean parameter'); } options.showClear = showClear; if (widget) { hide(); show(); } return picker; }; picker.widgetParent = function (widgetParent) { if (arguments.length === 0) { return options.widgetParent; } if (typeof widgetParent === 'string') { widgetParent = $(widgetParent); } if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof Element))) { throw new TypeError('widgetParent() expects a string or a Element object parameter'); } options.widgetParent = widgetParent; if (widget) { hide(); show(); } return picker; }; picker.keepOpen = function (keepOpen) { if (arguments.length === 0) { return options.keepOpen; } if (typeof keepOpen !== 'boolean') { throw new TypeError('keepOpen() expects a boolean parameter'); } options.keepOpen = keepOpen; return picker; }; picker.focusOnShow = function (focusOnShow) { if (arguments.length === 0) { return options.focusOnShow; } if (typeof focusOnShow !== 'boolean') { throw new TypeError('focusOnShow() expects a boolean parameter'); } options.focusOnShow = focusOnShow; return picker; }; picker.inline = function (inline) { if (arguments.length === 0) { return options.inline; } if (typeof inline !== 'boolean') { throw new TypeError('inline() expects a boolean parameter'); } options.inline = inline; return picker; }; picker.clear = function () { clear(); return picker; }; picker.keyBinds = function (keyBinds) { if (arguments.length === 0) { return options.keyBinds; } options.keyBinds = keyBinds; return picker; }; picker.getMoment = function (d) { return getMoment(d); }; picker.debug = function (debug) { if (typeof debug !== 'boolean') { throw new TypeError('debug() expects a boolean parameter'); } options.debug = debug; return picker; }; picker.allowInputToggle = function (allowInputToggle) { if (arguments.length === 0) { return options.allowInputToggle; } if (typeof allowInputToggle !== 'boolean') { throw new TypeError('allowInputToggle() expects a boolean parameter'); } options.allowInputToggle = allowInputToggle; return picker; }; picker.showClose = function (showClose) { if (arguments.length === 0) { return options.showClose; } if (typeof showClose !== 'boolean') { throw new TypeError('showClose() expects a boolean parameter'); } options.showClose = showClose; return picker; }; picker.keepInvalid = function (keepInvalid) { if (arguments.length === 0) { return options.keepInvalid; } if (typeof keepInvalid !== 'boolean') { throw new TypeError('keepInvalid() expects a boolean parameter'); } options.keepInvalid = keepInvalid; return picker; }; picker.datepickerInput = function (datepickerInput) { if (arguments.length === 0) { return options.datepickerInput; } if (typeof datepickerInput !== 'string') { throw new TypeError('datepickerInput() expects a string parameter'); } options.datepickerInput = datepickerInput; return picker; }; picker.parseInputDate = function (parseInputDate) { if (arguments.length === 0) { return options.parseInputDate; } if (typeof parseInputDate !== 'function') { throw new TypeError('parseInputDate() sholud be as function'); } options.parseInputDate = parseInputDate; return picker; }; picker.disabledTimeIntervals = function (disabledTimeIntervals) { ///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals"> ///<summary>Returns an array with the currently set disabled dates on the component.</summary> ///<returns type="array">options.disabledTimeIntervals</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledDates if such exist.</summary> ///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> ///</signature> if (arguments.length === 0) { return (options.disabledTimeIntervals ? Object.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals); } if (!disabledTimeIntervals) { options.disabledTimeIntervals = false; update(); return picker; } if (!(disabledTimeIntervals instanceof Array)) { throw new TypeError('disabledTimeIntervals() expects an array parameter'); } options.disabledTimeIntervals = disabledTimeIntervals; update(); return picker; }; picker.disabledHours = function (hours) { ///<signature helpKeyword="$.fn.datetimepicker.disabledHours"> ///<summary>Returns an array with the currently set disabled hours on the component.</summary> ///<returns type="array">options.disabledHours</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledHours if such exist.</summary> ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param> ///</signature> if (arguments.length === 0) { return (options.disabledHours ? Object.extend({}, options.disabledHours) : options.disabledHours); } if (!hours) { options.disabledHours = false; update(); return picker; } if (!(hours instanceof Array)) { throw new TypeError('disabledHours() expects an array parameter'); } options.disabledHours = indexGivenHours(hours); options.enabledHours = false; if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'h')) { date.add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; picker.enabledHours = function (hours) { ///<signature helpKeyword="$.fn.datetimepicker.enabledHours"> ///<summary>Returns an array with the currently set enabled hours on the component.</summary> ///<returns type="array">options.enabledHours</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary> ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param> ///</signature> if (arguments.length === 0) { return (options.enabledHours ? Object.extend({}, options.enabledHours) : options.enabledHours); } if (!hours) { options.enabledHours = false; update(); return picker; } if (!(hours instanceof Array)) { throw new TypeError('enabledHours() expects an array parameter'); } options.enabledHours = indexGivenHours(hours); options.disabledHours = false; if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'h')) { date.add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; /** * Returns the component's model current viewDate, a moment object or null if not set. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. * @param {Takes string, viewDate, moment, null parameter.} newDate * @returns {viewDate.clone()} */ picker.viewDate = function (newDate) { if (arguments.length === 0) { return viewDate.clone(); } if (!newDate) { viewDate = date.clone(); return picker; } if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); } viewDate = parseInputDate(newDate); viewUpdate(); return picker; }; // initializing element and component attributes if (element.match('input')) { input = element; } else { input = element.select(options.datepickerInput); if (input.length === 0) { input = element.select('input').first(); } else if (!input.match('input')) { throw new Error('CSS class "' + options.datepickerInput + '" cannot be applied to non input element'); } } if (element.hasClassName('input-group')) { // in case there is more then one 'input-group-addon' Issue #48 if (element.select('.datepickerbutton').length === 0) { component = element.select('.input-group-addon').first(); } else { component = element.select('.datepickerbutton').first(); } } if (!options.inline && !input.match('input')) { throw new Error('Could not initialize DateTimePicker without an input element'); } // Set defaults for date here now instead of in var declaration date = getMoment(); viewDate = date.clone(); Object.extend(options, dataToOptions()); picker.options(options); initFormatting(); attachDatePickerElementEvents(); if (input.readAttribute('disabled')) { picker.disable(); } var val = input.retrieve('date'); if (!val) val = $F(input).trim(); else val = moment(val); if (input.match('input') && val.length !== 0) { setValue(parseInputDate(val)); } else if (options.defaultDate && (input.readAttribute('placeholder') === undefined || input.readAttribute('placeholder') === null)) { setValue(options.defaultDate); } if (options.inline) { show(); } return picker; }; /******************************************************************************** * * jQuery plugin constructor and defaults object * ********************************************************************************/ /** * See (http://jquery.com/). * @name jQuery * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. */ /** * See (http://jquery.com/) * @name fn * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. * @memberOf jQuery */ /** * Show comments * @class datetimepicker * @memberOf jQuery.fn */ var dpDefaults = { timeZone: '', format: false, dayViewHeaderFormat: 'MMMM YYYY', extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, collapse: true, locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'glyphicon glyphicon-time', date: 'glyphicon glyphicon-calendar', up: 'glyphicon glyphicon-chevron-up', down: 'glyphicon glyphicon-chevron-down', previous: 'glyphicon glyphicon-chevron-left', next: 'glyphicon glyphicon-chevron-right', today: 'glyphicon glyphicon-screenshot', clear: 'glyphicon glyphicon-trash', close: 'glyphicon glyphicon-remove' }, tooltips: { today: 'Go to today', clear: 'Clear selection', close: 'Close the picker', selectMonth: 'Select Month', prevMonth: 'Previous Month', nextMonth: 'Next Month', selectYear: 'Select Year', prevYear: 'Previous Year', nextYear: 'Next Year', selectDecade: 'Select Decade', prevDecade: 'Previous Decade', nextDecade: 'Next Decade', prevCentury: 'Previous Century', nextCentury: 'Next Century', pickHour: 'Pick Hour', incrementHour: 'Increment Hour', decrementHour: 'Decrement Hour', pickMinute: 'Pick Minute', incrementMinute: 'Increment Minute', decrementMinute: 'Decrement Minute', pickSecond: 'Pick Second', incrementSecond: 'Increment Second', decrementSecond: 'Decrement Second', togglePeriod: 'Toggle Period', selectTime: 'Select Time' }, useStrict: false, sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', toolbarPlacement: 'default', showTodayButton: true, showClear: false, showClose: false, widgetPositioning: { horizontal: 'auto', vertical: 'auto' }, widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, datepickerInput: '.datepickerinput', keyBinds: { up: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } }, down: function (widget) { if (!widget) { this.show(); return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } }, 'control up': function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } }, 'control down': function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } }, left: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(1, 'd')); } }, right: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(1, 'd')); } }, pageUp: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(1, 'M')); } }, pageDown: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(1, 'M')); } }, enter: function () { this.hide(); }, escape: function () { this.hide(); }, //tab: function (widget) { //this break the flow of the form. disabling for now // var toggle = widget.find('.picker-switch a[data-action="togglePicker"]'); // if(toggle.length > 0) toggle.click(); //}, 'control space': function (widget) { if (!widget) { return; } if (widget.down('.timepicker').visible()) { widget.down('.btn[data-action="togglePeriod"]').click(); } }, t: function () { this.date(this.getMoment()); }, 'delete': function () { this.clear(); } }, debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, viewDate: false }; var localeTooltips = { es: { today: 'Hoy', clear: 'Limpiar selección', close: 'Cerrar', selectMonth: 'Seleccionar mes', prevMonth: 'Mes anterior', nextMonth: 'Mes siguiente', selectYear: 'Seleccionar año', prevYear: 'Año anterior', nextYear: 'Año siguiente', selectDecade: 'Seleccionar década', prevDecade: 'Década anterior', nextDecade: 'Década siguiente', prevCentury: 'Siglo siguiente', nextCentury: 'Siglo anterior', pickHour: 'Seleccionar hora', incrementHour: 'Aumentar hora', decrementHour: 'Disminuir hora', pickMinute: 'Seleccionar minuto', incrementMinute: 'Aumentar minuto', decrementMinute: 'Disminuir minuto', pickSecond: 'Seleccionar segundo', incrementSecond: 'Aumentar segundo', decrementSecond: 'Disminuir segundo', togglePeriod: 'Toggle Period', selectTime: 'Select Time' } }; Class.create('DateTimePicker', { picker: null, initialize: function (element, options) { var thisOptions = Object.extend({}, dpDefaults); thisOptions = Object.extend(thisOptions, options || {}); thisOptions.tooltips = localeTooltips[thisOptions.locale] || thisOptions.tooltips; this.picker = dateTimePicker(element, thisOptions); } }); })();
boa-project/boa
src/boa/plugins/gui.ajax/res/js/core/DateTimePicker.class.js
JavaScript
agpl-3.0
113,199
importPackage(Packages.tools); var returnTo = new Array(103000100, 103000310); var rideTo = new Array(103000310, 103000100); var trainRide = new Array(103000301, 103000302); var myRide; var returnMap; var exitMap; var map; var onRide; //Time Setting is in millisecond var rideTime = 10 * 1000; function init() { rideTime = em.getTransportationTime(rideTime); } function setup(level, lobbyid) { var eim = em.newInstance("KerningTrain_" + lobbyid); return eim; } function afterSetup(eim) {} function playerEntry(eim, player) { if (player.getMapId() == returnTo[0]) { myRide = 0; } else { myRide = 1; } exitMap = eim.getEm().getChannelServer().getMapFactory().getMap(rideTo[myRide]); returnMap = eim.getMapFactory().getMap(returnTo[myRide]); onRide = eim.getMapFactory().getMap(trainRide[myRide]); player.changeMap(onRide, onRide.getPortal(0)); player.getClient().announce(MaplePacketCreator.getClock(rideTime / 1000)); player.getClient().announce(MaplePacketCreator.earnTitleMessage("The next stop is at Kerning " + (myRide == 0 ? "Square" : "Subway") + " Station. The exit is to your left.")); eim.schedule("timeOut", rideTime); } function timeOut(eim) { end(eim); } function playerUnregistered(eim, player) {} function playerExit(eim, player, success) { eim.unregisterPlayer(player); player.changeMap(success ? exitMap.getId() : returnMap.getId(), 0); } function end(eim) { var party = eim.getPlayers(); for (var i = 0; i < party.size(); i++) { playerExit(eim, party.get(i), true); } eim.dispose(); } function playerDisconnected(eim, player) { playerExit(eim, player, false); } function cancelSchedule() {} function dispose(eim) {} // ---------- FILLER FUNCTIONS ---------- function monsterValue(eim, mobid) {return 0;} function disbandParty(eim, player) {} function monsterKilled(mob, eim) {} function scheduledTimeout(eim) {} function changedLeader(eim, leader) {} function leftParty(eim, player) {} function clearPQ(eim) {} function allMonstersDead(eim) {}
ronancpl/MapleSolaxiaV2
scripts/event/KerningTrain.js
JavaScript
agpl-3.0
2,133
// TriangleCanvas.js import React from 'react'; import Trianglify from 'trianglify'; import './TriangleCanvas.scss'; /** Canvas with Trianglify styling applied, equal in size to current window, can be used as a sweet background. Will automatically size to window's width and height. @prop cellSize: cell_size option for Trianglify @prop xColors: x_colors option for Trianglify @prop yColors: y_colors option for Trianglify note: more Trianglify options available https://github.com/qrohlf/trianglify */ const TriangleCanvas = React.createClass({ getDefaultProps() { return { cellSize: Trianglify.defaults.cell_size, xColors: Trianglify.defaults.x_colors, yColors: Trianglify.defaults.cell_size, }; }, componentDidMount() { this.renderCanvas(); }, renderCanvas() { const canvas = document.getElementById('daCanvas'); const pattern = Trianglify({ width: window.innerWidth, height: window.innerHeight, cell_size: this.props.cellSize, x_colors: this.props.xColors, }); pattern.canvas(canvas); }, render() { return ( <div className="triangleCanvas"> <canvas className="canvasCanvas" id="daCanvas" /> <div className="canvasContent">{this.props.children}</div> </div> ); }, }); export default TriangleCanvas;
uclaradio/uclaradio
client/react/frontpage/components/TriangleCanvas.js
JavaScript
agpl-3.0
1,331
OC.L10N.register( "workflowengine", { "Saved" : "Bewaard", "Saving failed:" : "Opslaan mislukt:", "File MIME type" : "Mimetype bestand", "is" : "is", "is not" : "is niet", "matches" : "komt overeen", "does not match" : "komt niet overeen", "Example: {placeholder}" : "Bijvoorbeeld: {placeholder}", "File size (upload)" : "Bestandsgrootte (upload)", "less" : "minder", "less or equals" : "minder of gelijk", "greater or equals" : "groter of gelijk", "greater" : "groter", "File system tag" : "Bestandssysteem markering", "is tagged with" : "is gemarkeerd met", "is not tagged with" : "is niet gemarkeerd met", "Select tag…" : "Selecteer markering...", "Request remote address" : "Vraag extern adres aan", "matches IPv4" : "komt overeen met IPv4", "does not match IPv4" : "komt niet overeen met IPv4", "matches IPv6" : "komt overeen met IPv6", "does not match IPv6" : "komt niet overeen met IPv6", "Request time" : "Vraag tijd aan", "between" : "tussen", "not between" : "niet tussen", "Start" : "Begin", "End" : "Einde", "Select timezone…" : "Selecteer tijdzone...", "Request URL" : "Vraag URL aan", "Predefined URLs" : "Voorgedefinieerde URL's", "Files WebDAV" : "Bestanden WebDAV", "Request user agent" : "Vraag gebruikersagent aan", "Sync clients" : "Synchroniseer clients", "Android client" : "Android client", "iOS client" : "iOS client", "Desktop client" : "Desktop client", "User group membership" : "Gebruikersgroep lidmaatschap", "is member of" : "is lid van", "is not member of" : "is geen lid van", "The given operator is invalid" : "De opgegeven operator is ongeldig", "The given regular expression is invalid" : "De opgegeven reguliere expressie is ongeldig", "The given file size is invalid" : "De opgegeven bestandsgrootte is ongeldig", "The given tag id is invalid" : "De opgegeven markerings-id is ongeldig", "The given IP range is invalid" : "De opgegeven IP-range is ongeldig", "The given IP range is not valid for IPv4" : "De opgegeven IP-range is niet geldig voor IPv4", "The given IP range is not valid for IPv6" : "De opgegeven IP-range is niet geldig voor IPv6", "The given time span is invalid" : "De opgegeven tijdspanne is ongeldig", "The given start time is invalid" : "De opgegeven begintijd is ongeldig", "The given end time is invalid" : "De opgegeven eindtijd is ongeldig", "The given group does not exist" : "De opgegeven groep bestaat niet", "Check %s is invalid or does not exist" : "Controleer: %s is ongeldig of bestaat niet", "Operation #%s does not exist" : "Bewerking #%s bestaat niet", "Operation %s does not exist" : "Bewerking %s bestaat niet", "Operation %s is invalid" : "Bewerking %s is ongeldig", "Check %s does not exist" : "Controleer: %s bestaat niet", "Check %s is invalid" : "Controleer: %s is ongeldig", "Check #%s does not exist" : "Controleer: #%s bestaat niet", "Workflow" : "Workflow", "Files workflow engine" : "Betand workflow engine", "Open documentation" : "Open documentatie", "Add rule group" : "Groepsrol toevoegen", "Short rule description" : "Korte rolbeschrijving", "Add rule" : "Voeg rol toe", "Reset" : "Reset", "Save" : "Opslaan", "Saving…" : "Opslaan...", "Loading…" : "Laden...", "Successfully saved" : "Succesvol opgeslagen", "File mime type" : "Bestand mime type" }, "nplurals=2; plural=(n != 1);");
pixelipo/server
apps/workflowengine/l10n/nl.js
JavaScript
agpl-3.0
3,565
/* * _ _ _ * | | | | | | * | | __ _| |__ ___ ___ __ _| |_ Labcoat (R) * | |/ _` | '_ \ / __/ _ \ / _` | __| Powerful development environment for Quirrel. * | | (_| | |_) | (_| (_) | (_| | |_ Copyright (C) 2010 - 2013 SlamData, Inc. * |_|\__,_|_.__/ \___\___/ \__,_|\__| All Rights Reserved. * * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ /* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { "use strict"; var oop = require("ace/lib/oop"); var EventEmitter = require("ace/lib/event_emitter").EventEmitter; var Editor = exports.Editor = function() { this._buffers = []; this._windows = []; }; (function() { oop.implement(this, EventEmitter); this.addBuffer = function(buffer) { this._buffers.push(buffer); return this._buffers.length-1; }; this.addWindow = function(win) { this._windows.push(win); return this._windows.length-1; }; this.openInWindow = function(bufferId, winId) { this._windows[winId || 0].setBuffer(this._buffers[bufferId]); }; }).call(Editor.prototype); });
precog/labcoat-legacy
js/ace/model/editor.js
JavaScript
agpl-3.0
3,492
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellIcon } from 'interface'; import { SpellLink } from 'interface'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import { ThresholdStyle } from 'parser/core/ParseResults'; import BoringValue from 'parser/ui/BoringValueText'; import Statistic from 'parser/ui/Statistic'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import React from 'react'; import { SPELLS_WHICH_REMOVE_BOC } from '../../constants'; const debug = false; const BOC_DURATION = 15000; class BlackoutCombo extends Analyzer { get dpsWasteThreshold() { return { actual: this.spellsBOCWasUsedOn[SPELLS.TIGER_PALM.id] / this.blackoutComboBuffs, isLessThan: { minor: 0.95, average: 0.9, major: 0.85, }, style: ThresholdStyle.PERCENTAGE, }; } blackoutComboConsumed = 0; blackoutComboBuffs = 0; lastBlackoutComboCast = 0; spellsBOCWasUsedOn = {}; statisticOrder = STATISTIC_ORDER.OPTIONAL(); constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.BLACKOUT_COMBO_TALENT.id); this.addEventListener( Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.BLACKOUT_COMBO_BUFF), this.onApplyBuff, ); this.addEventListener( Events.refreshbuff.by(SELECTED_PLAYER).spell(SPELLS.BLACKOUT_COMBO_BUFF), this.onRefreshBuff, ); this.addEventListener( Events.cast.by(SELECTED_PLAYER).spell(SPELLS_WHICH_REMOVE_BOC), this.onCast, ); } onApplyBuff(event) { debug && console.log('Blackout combo applied'); this.blackoutComboBuffs += 1; this.lastBlackoutComboCast = event.timestamp; } onRefreshBuff(event) { debug && console.log('Blackout combo refreshed'); this.blackoutComboBuffs += 1; this.lastBlackoutComboCast = event.timestamp; } onCast(event) { const spellId = event.ability.guid; // BOC should be up if ( this.lastBlackoutComboCast > 0 && this.lastBlackoutComboCast + BOC_DURATION > event.timestamp ) { this.blackoutComboConsumed += 1; if (this.spellsBOCWasUsedOn[spellId] === undefined) { this.spellsBOCWasUsedOn[spellId] = 0; } this.spellsBOCWasUsedOn[spellId] += 1; } this.lastBlackoutComboCast = 0; } suggestions(when) { const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs; when(wastedPerc) .isGreaterThan(0.1) .addSuggestion((suggest, actual, recommended) => suggest( <span> You wasted {formatPercentage(actual)}% of your{' '} <SpellLink id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> procs. Try to use the procs as soon as you get them so they are not overwritten. </span>, ) .icon(SPELLS.BLACKOUT_COMBO_BUFF.icon) .actual( t({ id: 'monk.brewmaster.suggestions.blackoutCombo.wasted', message: `${formatPercentage(actual)}% unused`, }), ) .recommended(`${Math.round(formatPercentage(recommended))}% or less is recommended`) .regular(recommended + 0.1) .major(recommended + 0.2), ); } statistic() { const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs; return ( <Statistic position={STATISTIC_ORDER.OPTIONAL()} size="flexible" tooltip={ <> You got total <strong>{this.blackoutComboBuffs}</strong> Blackout Combo procs and used{' '} <strong>{this.blackoutComboConsumed}</strong> of them. <br /> Blackout combo buff usage: <ul> {Object.keys(this.spellsBOCWasUsedOn) .sort((a, b) => this.spellsBOCWasUsedOn[b] - this.spellsBOCWasUsedOn[a]) .map((type) => ( <li key={type}> <em>{SPELLS[type].name || 'Unknown'}</em> was used{' '} {this.spellsBOCWasUsedOn[type]} time {this.spellsBOCWasUsedOn[type] === 1 ? '' : 's'} ( {formatPercentage(this.spellsBOCWasUsedOn[type] / this.blackoutComboConsumed)}%) </li> ))} </ul> </> } > <BoringValue label={ <> <SpellIcon id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> Wasted Blackout Combo </> } > <>{formatPercentage(wastedPerc)}%</> </BoringValue> </Statistic> ); } } export default BlackoutCombo;
anom0ly/WoWAnalyzer
analysis/monkbrewmaster/src/modules/spells/BlackoutCombo.js
JavaScript
agpl-3.0
4,812
$(document).ready(function () { var pathArray = window.location.pathname.split( '/' ); var targetname = pathArray[pathArray.length -1]; $('#targetloglist').DataTable({ 'paging' : true, 'lengthChange': false, 'searching' : true, 'ordering' : true, 'order' : [[0, "desc"]], 'info' : true, 'autoWidth' : true, 'deferRender' : true, "language": { "emptyTable": "No connection history for this target" }, 'ajax' : { url : '/ajax/target/lastconnections/' + targetname, dataSrc : 'data' } }) })
LibrIT/passhport
passhweb/app/static/librit/scripts/target_lastconnections.js
JavaScript
agpl-3.0
682
const { GenericCommand } = require('../../models/') const videos = [ 'https://www.pornhub.com/view_video.php?viewkey=ph5a5a31a130d7b', 'https://www.pornhub.com/view_video.php?viewkey=ph5925ca42189b1', 'https://www.pornhub.com/view_video.php?viewkey=ph58a2743e7bc0a', 'https://www.pornhub.com/view_video.php?viewkey=ph588bb994715f4', 'https://www.pornhub.com/view_video.php?viewkey=ph57a9e5cbbbc6b', 'https://www.pornhub.com/view_video.php?viewkey=ph594f81e1bb436', 'https://www.pornhub.com/view_video.php?viewkey=ph57f425354c95a', 'https://www.pornhub.com/view_video.php?viewkey=ph57cb90be0d19d', 'https://www.pornhub.com/view_video.php?viewkey=ph575460edacb01', 'https://www.pornhub.com/view_video.php?viewkey=ph588c05619d874', 'https://www.pornhub.com/view_video.php?viewkey=ph586f01bb87f0f' ] module.exports = new GenericCommand( async ({ Memer, msg, args }) => { return { title: 'Minecraft Porn', description: `You must [click here](${Memer.randomInArray(videos)}) to watch this weird shit.`, footer: { text: 'Why does this exist' } } }, { triggers: ['mcporn'], isNSFW: true, description: 'This is some good stuff, trust me' } )
melmsie/Dank-Memer
src/commands/nsfwCommands/mcporn.js
JavaScript
agpl-3.0
1,202
/* Copyright 2011 Daniel Lombraña González Users_Widget.js is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by Free Software Foundation, either version 3 of the License, or (at your option) any later version. Users_Widget.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Users_Widget.js. If not, see <http://www.gnu.org/licenses/>. */ google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(init); function drawChart(options) { console.log("Drawing charts for " + options.data); console.log("From: " + options.from + " to: " + options.to); $.throbber.show({overlay: false}); //if ( options.days == null ) options.days = 7; if ( options.type == null) options.type = 'total'; // options = { 'days': days, total: 1, with_credit: 1 }; $.getJSON('project_stats.php', options, function(data) { var d = new google.visualization.DataTable(); d.addColumn('string', 'Date'); if (options.type == 'with_credit') d.addColumn('number', 'With credit'); if (options.type == 'total') d.addColumn('number', 'Total'); if (options.type == 'new') d.addColumn('number', 'New'); var x = 0; $.each(data[options.data][0], function(key, val) { d.addRow(); d.setValue(x,0,key); d.setValue(x,1,val); x = x + 1; }); var chart = new google.visualization.LineChart(document.getElementById(options.div)); chart.draw(d, {width: 600, height: 440, colors: options.color, labelPosition: 'right', legend: {'position': 'none'}, title: options.description}); $.throbber.hide(); }); } function default_charts() { var data = $("input[@name=data]:checked").val(); var from = $("#from").val(); var to = $("#to").val(); // New Users or Hosts drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'new', 'div': 'new', 'description': 'New ' + data, 'color': ['red']}); // Total registered users or hosts drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'total', 'div': 'total', 'description': 'Total number of ' + data, 'color': ['blue']}); if (data != 'posts') { // Users or hosts with credit $("#with_credit").show(); drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'with_credit', 'div': 'with_credit', 'description': 'Number of ' + data + ' with credit', 'color': ['green']}); } else { $("#with_credit").hide(); } } function init() { $("input[name='data']").bind("click", default_charts); $("button").button(); var dates = $( "#from, #to" ).datepicker({ defaultDate: "-1w", changeMonth: true, changeYear: true, minDate: new Date(2010,10,01), maxDate: new Date(), dateFormat: 'yy-mm-dd', numberOfMonths: 1, onSelect: function( selectedDate ) { var option = this.id == "from" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } }); $("#from").datepicker("setDate","-1w"); $("#to").datepicker("setDate", new Date()); $("button").click( function() { var data = $("input[@name=data]:checked").val(); drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'new', 'div': 'new', 'description': 'New ' + data , 'color': ['red']}); drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'total', 'div': 'total', 'description': 'Total number of ' + data, 'color': ['blue']}); if (data != "posts") drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'with_credit', 'div': 'with_credit', 'description': 'Number of ' + data + ' with credit', 'color': ['green']}); }); default_charts(); }
teleyinex/boinc-widgets
project_stats.js
JavaScript
agpl-3.0
4,398
/** * Copyright (C) 2013-2014 Spark Labs, Inc. All rights reserved. - https://www.spark.io/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can download the source here: https://github.com/spark/spark-server */ var settings = require('../settings.js'); var CoreController = require('../lib/CoreController.js'); var roles = require('../lib/RolesController.js'); var sequence = require('when/sequence'); var parallel = require('when/parallel'); var pipeline = require('when/pipeline'); var logger = require('../lib/logger.js'); var utilities = require("../lib/utilities.js"); var fs = require('fs'); var when = require('when'); var util = require('util'); var path = require('path'); var ursa = require('ursa'); var moment = require('moment'); var crypto = require('crypto'); // var corepath; // var corepath = settings.getToCores(); /* * TODO: modularize duplicate code * TODO: implement proper session handling / user authentication * TODO: add cors handler without losing :params support * */ var Api = { loadViews: function (app) { //our middleware app.param("coreid", Api.loadCore); //core functions / variables app.post('/v1/devices/:coreid/:func', Api.fn_call); app.get('/v1/devices/:coreid/:var', Api.get_var); app.put('/v1/devices/:coreid', Api.set_core_attributes); app.get('/v1/devices/:coreid', Api.get_core_attributes); //doesn't need per-core permissions, only shows owned cores. app.get('/v1/devices', Api.list_devices); app.post('/v1/provisioning/:coreid', Api.provision_core); //app.delete('/v1/devices/:coreid', Api.release_device); app.post('/v1/devices', Api.claim_device); }, getSocketID: function (userID) { return userID + "_" + global._socket_counter++; }, getUserID: function (req) { if (!req.user) { logger.log("User obj was empty"); return null; } //req.user.id is set in authorise.validateAccessToken in the OAUTH code return req.user.id; }, list_devices: function (req, res) { var userid = Api.getUserID(req); logger.log("ListDevices", { userID: userid }); // corepath = settings.getToCores(userid); global.server.loadCoreData(userid); // console.log(corepath); //give me all the cores var allCoreIDs = global.server.getAllCoreIDs(userid); // console.log(allCoreIDs); devices = [], connected_promises = []; if(allCoreIDs == null){ var devices = ("no device is claimed by this user"); res.json(200, devices); } else{ for (var coreid in allCoreIDs) { if (!coreid) { continue; } var core = global.server.getCoreAttributes(coreid); var device = { id: coreid, name: (core) ? core.name : null, last_app: core ? core.last_flashed_app_name : null, last_heard: null }; if (utilities.check_requires_update(core, settings.cc3000_driver_version)) { device["requires_deep_update"] = true; } devices.push(device); connected_promises.push(Api.isDeviceOnline(userid, device.id)); } logger.log("ListDevices... waiting for connected state to settle ", { userID: userid }); //switched 'done' to 'then' - threw an exception with 'done' here. when.settle(connected_promises).then(function (descriptors) { for (var i = 0; i < descriptors.length; i++) { var desc = descriptors[i]; devices[i].connected = ('rejected' !== desc.state); devices[i].last_heard = (desc.value) ? desc.value.lastPing : null; } res.json(200, devices); }); } }, get_core_attributes: function (req, res) { var userid = Api.getUserID(req); var socketID = Api.getSocketID(userid), coreID = req.coreID, socket = new CoreController(socketID); logger.log("GetAttr", { coreID: coreID, userID: userid.toString() }); var objReady = parallel([ function () { return when.resolve(global.server.getCoreAttributes(coreID)); }, function () { return utilities.alwaysResolve(socket.sendAndListenForDFD(coreID, { cmd: "Describe" }, { cmd: "DescribeReturn" })); } ]); //whatever we get back... when(objReady).done(function (results) { try { if (!results || (results.length != 2)) { logger.error("get_core_attributes results was the wrong length " + JSON.stringify(results)); res.json(404, "Oops, I couldn't find that core"); return; } //we're expecting descResult to be an array: [ sender, {} ] var doc = results[0], descResult = results[1], coreState = null; if (!doc || !doc.coreID) { logger.error("get_core_attributes 404 error: " + JSON.stringify(doc)); res.json(404, "Oops, I couldn't find that core"); return; } if (util.isArray(descResult) && (descResult.length > 1)) { coreState = descResult[1].state || {}; } if (!coreState) { logger.error("get_core_attributes didn't get description: " + JSON.stringify(descResult)); } var device = { id: doc.coreID, name: doc.name || null, last_app: doc.last_flashed, connected: !!coreState, variables: (coreState) ? coreState.v : null, functions: (coreState) ? coreState.f : null, cc3000_patch_version: doc.cc3000_driver_version }; if (utilities.check_requires_update(doc, settings.cc3000_driver_version)) { device["requires_deep_update"] = true; } res.json(device); } catch (ex) { logger.error("get_core_attributes merge error: " + ex); res.json(500, { Error: "get_core_attributes error: " + ex }); } }, null); //get_core_attribs - end }, set_core_attributes: function (req, res) { var coreID = req.coreID; var userid = Api.getUserID(req); var promises = []; logger.log("set_core_attributes", { coreID: coreID, userID: userid.toString() }); var coreName = req.body ? req.body.name : null; if (coreName != null) { logger.log("SetAttr", { coreID: coreID, userID: userid.toString(), name: coreName }); global.server.setCoreAttribute(req.coreID, "name", coreName); promises.push(when.resolve({ ok: true, name: coreName })); } var hasFiles = req.files && req.files.file; if (hasFiles) { //oh hey, you want to flash firmware? promises.push(Api.compile_and__or_flash_dfd(req)); } var signal = req.body && req.body.signal; if (signal) { //get your hands up in the air! Or down. promises.push(Api.core_signal_dfd(req)); } var flashApp = req.body ? req.body.app : null; if (flashApp) { // It makes no sense to flash a known app and also // either signal or flash a file sent with the request if (!hasFiles && !signal) { // MUST sanitize app name here, before sending to Device Service if (utilities.contains(settings.known_apps, flashApp)) { promises.push(Api.flash_known_app_dfd(req)); } else { promises.push(when.reject("Can't flash unknown app " + flashApp)); } } } var app_id = req.body ? req.body.app_id : null; if (app_id && !hasFiles && !signal && !flashApp) { //we have an app id, and no files, and stuff //we must be flashing from the db! promises.push(Api.flash_app_in_db_dfd(req)); } var app_example_id = req.body ? req.body.app_example_id : null; if (app_example_id && !hasFiles && !signal && !flashApp && !app_id) { //we have an app id, and no files, and stuff //we must be flashing from the db! promises.push(Api.flash_example_app_in_db_dfd(req)); } if (promises.length >= 1) { when.all(promises).done( function (results) { var aggregate = {}; for (var i in results) { for (var key in results[i]) { aggregate[key] = results[i][key]; } } res.json(aggregate); }, function (err) { res.json({ ok: false, errors: [err] }); } ); } else { logger.error("set_core_attributes - nothing to do?", { coreID: coreID, userID: userid.toString() }); res.json({error: "Nothing to do?"}); } }, isDeviceOnline: function (userID, coreID) { var tmp = when.defer(); var socketID = Api.getSocketID(userID); var socket = new CoreController(socketID); var failTimer = setTimeout(function () { logger.log("isDeviceOnline: Ping timed out ", { coreID: coreID }); socket.close(); tmp.reject("Device is not connected"); }, settings.isCoreOnlineTimeout); //setup listener for response back from the device service socket.listenFor(coreID, { cmd: "Pong" }, function (sender, msg) { clearTimeout(failTimer); socket.close(); logger.log("isDeviceOnline: Device service thinks it is online... ", { coreID: coreID }); if (msg && msg.online) { tmp.resolve(msg); } else { tmp.reject(["Core isn't online", 404]); } }, true); logger.log("isDeviceOnline: Pinging core... ", { coreID: coreID }); //send it along to the device service if (!socket.send(coreID, { cmd: "Ping" })) { tmp.reject("send failed"); } return tmp.promise; }, claim_device: function (req, res) { res.json({ ok: true }); }, loadCore: function (req, res, next) { req.coreID = req.param('coreid') || req.body.id; //load core info! req.coreInfo = { "last_app": "", "last_heard": new Date(), "connected": false, "deviceID": req.coreID }; //if that user doesn't own that coreID, maybe they sent us a core name var userid = Api.getUserID(req); var gotCore = utilities.deferredAny([ function () { var core = global.server.getCoreAttributes(req.coreID); if (core && core.coreID) { return when.resolve(core); } else { return when.reject(); } }, function () { var core = global.server.getCoreByName(req.coreID); if (core && core.coreID) { return when.resolve(core); } else { return when.reject(); } } ]); when(gotCore).then( function (core) { if (core) { req.coreID = core.coreID || req.coreID; req.coreInfo = { last_handshake_at: core.last_handshake_at }; } next(); }, function (err) { //s`okay. next(); }) }, get_var: function (req, res) { var userid = Api.getUserID(req); var socketID = Api.getSocketID(userid), coreID = req.coreID, varName = req.param('var'), format = req.param('format'); logger.log("GetVar", {coreID: coreID, userID: userid.toString()}); //send it along to the device service //and listen for a response back from the device service var socket = new CoreController(socketID); var coreResult = socket.sendAndListenForDFD(coreID, { cmd: "GetVar", name: varName }, { cmd: "VarReturn", name: varName }, settings.coreRequestTimeout ); //sendAndListenForDFD resolves arr to ==> [sender, msg] when(coreResult) .then(function (arr) { var msg = arr[1]; if (msg.error) { //at this point, either we didn't get a describe return, or that variable //didn't exist, either way, 404 return res.json(404, { ok: false, error: msg.error }); } //TODO: make me look like the spec. msg.coreInfo = req.coreInfo; msg.coreInfo.connected = true; if (format && (format == "raw")) { return res.send("" + msg.result); } else { return res.json(msg); } }, function () { res.json(408, {error: "Timed out."}); } ).ensure(function () { socket.close(); }); }, fn_call: function (req, res) { var user_id = Api.getUserID(req), coreID = req.coreID, funcName = req.params.func, format = req.params.format; logger.log("FunCall", { coreID: coreID, user_id: user_id.toString() }); var socketID = Api.getSocketID(user_id); var socket = new CoreController(socketID); var core = socket.getCore(coreID); var args = req.body; delete args.access_token; logger.log("FunCall - calling core ", { coreID: coreID, user_id: user_id.toString() }); var coreResult = socket.sendAndListenForDFD(coreID, { cmd: "CallFn", name: funcName, args: args }, { cmd: "FnReturn", name: funcName }, settings.coreRequestTimeout ); //sendAndListenForDFD resolves arr to ==> [sender, msg] when(coreResult) .then( function (arr) { var sender = arr[0], msg = arr[1]; try { //logger.log("FunCall - heard back ", { coreID: coreID, user_id: user_id.toString() }); if (msg.error && (msg.error.indexOf("Unknown Function") >= 0)) { res.json(404, { ok: false, error: "Function not found" }); } else if (msg.error != null) { res.json(400, { ok: false, error: msg.error }); } else { if (format && (format == "raw")) { res.send("" + msg.result); } else { res.json({ id: core.coreID, name: core.name || null, last_app: core.last_flashed_app_name || null, connected: true, return_value: msg.result }); } } } catch (ex) { logger.error("FunCall handling resp error " + ex); res.json(500, { ok: false, error: "Error while api was rendering response" }); } }, function () { res.json(408, {error: "Timed out."}); } ).ensure(function () { socket.close(); }); //socket.send(coreID, { cmd: "CallFn", name: funcName, args: args }); // send the function call along to the device service }, /** * Ask the core to start / stop the "RaiseYourHand" signal * @param req */ core_signal_dfd: function (req) { var tmp = when.defer(); var userid = Api.getUserID(req), socketID = Api.getSocketID(userid), coreID = req.coreID, showSignal = parseInt(req.body.signal); logger.log("SignalCore", { coreID: coreID, userID: userid.toString()}); var socket = new CoreController(socketID); var failTimer = setTimeout(function () { socket.close(); tmp.reject({error: "Timed out, didn't hear back"}); }, settings.coreSignalTimeout); //listen for a response back from the device service socket.listenFor(coreID, { cmd: "RaiseHandReturn"}, function () { clearTimeout(failTimer); socket.close(); tmp.resolve({ id: coreID, connected: true, signaling: showSignal === 1 }); }, true); //send it along to the core via the device service socket.send(coreID, { cmd: "RaiseHand", args: { signal: showSignal } }); return tmp.promise; }, compile_and__or_flash_dfd: function (req) { var allDone = when.defer(); var userid = Api.getUserID(req), coreID = req.coreID; // // Did they pass us a source file or a binary file? // var hasSourceFiles = false; var sourceExts = [".cpp", ".c", ".h", ".ino" ]; if (req.files) { for (var name in req.files) { if (!req.files.hasOwnProperty(name)) { continue; } var ext = utilities.getFilenameExt(req.files[name].path); if (utilities.contains(sourceExts, ext)) { hasSourceFiles = true; break; } } } if (hasSourceFiles) { //TODO: federate? allDone.reject("Not yet implemented"); } else { //they sent a binary, just flash it! var flashDone = Api.flash_core_dfd(req); //pipe rejection / resolution of flash to response utilities.pipeDeferred(flashDone, allDone); } return allDone.promise; }, /** * Flashing firmware to the core, binary file! * @param req * @returns {promise|*|Function|Promise|when.promise} */ flash_core_dfd: function (req) { var tmp = when.defer(); var userid = Api.getUserID(req), socketID = Api.getSocketID(userid), coreID = req.coreID; logger.log("FlashCore", {coreID: coreID, userID: userid.toString()}); var args = req.query; delete args.coreid; if (req.files) { args.data = fs.readFileSync(req.files.file.path); } var socket = new CoreController(socketID); var failTimer = setTimeout(function () { socket.close(); tmp.reject({error: "Timed out."}); }, settings.coreFlashTimeout); //listen for the first response back from the device service socket.listenFor(coreID, { cmd: "Event", name: "Update" }, function (sender, msg) { clearTimeout(failTimer); socket.close(); var response = { id: coreID, status: msg.message }; if ("Update started" === msg.message) { tmp.resolve(response); } else { logger.error("flash_core_dfd rejected ", response); tmp.reject(response); } }, true); //send it along to the device service socket.send(coreID, { cmd: "UFlash", args: args }); return tmp.promise; }, provision_core: function (req, res) { //if we're here, the user should be allowed to provision cores. var done = Api.provision_core_dfd(req); when(done).then( function (result) { res.json(result); }, function (err) { //different status code here? res.json(400, err); }); }, provision_core_dfd: function (req) { var result = when.defer(), userid = Api.getUserID(req), deviceID = req.body.deviceID, publicKey = req.body.publicKey; if (!deviceID) { return when.reject({ error: "No deviceID provided" }); } try { var keyObj = ursa.createPublicKey(publicKey); if (!publicKey || (!ursa.isPublicKey(keyObj))) { return when.reject({ error: "No key provided" }); } } catch (ex) { logger.error("error while parsing publicKey " + ex); return when.reject({ error: "Key error " + ex }); } global.server.addCoreKey(userid, deviceID, publicKey); global.server.setCoreAttribute(deviceID, "registrar", userid); global.server.setCoreAttribute(deviceID, "timestamp", new Date()); result.resolve("Success!"); return result.promise; }, _: null }; exports = module.exports = Api; //implement :: save core data
SreejitS/spark-server
views/api_v1.js
JavaScript
agpl-3.0
18,143
import loadPolyfills from '../mastodon/load_polyfills'; import ready from '../mastodon/ready'; window.addEventListener('message', e => { const data = e.data || {}; if (!window.parent || data.type !== 'setHeight') { return; } ready(() => { window.parent.postMessage({ type: 'setHeight', id: data.id, height: document.getElementsByTagName('html')[0].scrollHeight, }, '*'); }); }); function main() { const { length } = require('stringz'); const IntlRelativeFormat = require('intl-relativeformat').default; const { delegate } = require('rails-ujs'); const emojify = require('../mastodon/features/emoji/emoji').default; const { getLocale } = require('../mastodon/locales'); const { localeData } = getLocale(); const VideoContainer = require('../mastodon/containers/video_container').default; const MediaGalleryContainer = require('../mastodon/containers/media_gallery_container').default; const CardContainer = require('../mastodon/containers/card_container').default; const React = require('react'); const ReactDOM = require('react-dom'); localeData.forEach(IntlRelativeFormat.__addLocaleData); ready(() => { const locale = document.documentElement.lang; const dateTimeFormat = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', }); const relativeFormat = new IntlRelativeFormat(locale); [].forEach.call(document.querySelectorAll('.emojify'), (content) => { content.innerHTML = emojify(content.innerHTML); }); [].forEach.call(document.querySelectorAll('time.formatted'), (content) => { const datetime = new Date(content.getAttribute('datetime')); const formattedDate = dateTimeFormat.format(datetime); content.title = formattedDate; content.textContent = formattedDate; }); [].forEach.call(document.querySelectorAll('time.time-ago'), (content) => { const datetime = new Date(content.getAttribute('datetime')); content.title = dateTimeFormat.format(datetime); content.textContent = relativeFormat.format(datetime); }); [].forEach.call(document.querySelectorAll('.logo-button'), (content) => { content.addEventListener('click', (e) => { e.preventDefault(); window.open(e.target.href, 'mastodon-intent', 'width=400,height=400,resizable=no,menubar=no,status=no,scrollbars=yes'); }); }); [].forEach.call(document.querySelectorAll('[data-component="Video"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<VideoContainer locale={locale} {...props} />, content); }); [].forEach.call(document.querySelectorAll('[data-component="MediaGallery"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<MediaGalleryContainer locale={locale} {...props} />, content); }); [].forEach.call(document.querySelectorAll('[data-component="Card"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<CardContainer locale={locale} {...props} />, content); }); }); delegate(document, '.webapp-btn', 'click', ({ target, button }) => { if (button !== 0) { return true; } window.location.href = target.href; return false; }); delegate(document, '.status__content__spoiler-link', 'click', ({ target }) => { const contentEl = target.parentNode.parentNode.querySelector('.e-content'); if (contentEl.style.display === 'block') { contentEl.style.display = 'none'; target.parentNode.style.marginBottom = 0; } else { contentEl.style.display = 'block'; target.parentNode.style.marginBottom = null; } return false; }); delegate(document, '.account_display_name', 'input', ({ target }) => { const nameCounter = document.querySelector('.name-counter'); if (nameCounter) { nameCounter.textContent = 30 - length(target.value); } }); delegate(document, '.account_note', 'input', ({ target }) => { const noteCounter = document.querySelector('.note-counter'); if (noteCounter) { noteCounter.textContent = 333 - length(target.value); } }); delegate(document, '#account_avatar', 'change', ({ target }) => { const avatar = document.querySelector('.card.compact .avatar img'); const [file] = target.files || []; const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc; avatar.src = url; }); delegate(document, '#account_header', 'change', ({ target }) => { const header = document.querySelector('.card.compact'); const [file] = target.files || []; const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc; header.style.backgroundImage = `url(${url})`; }); } loadPolyfills().then(main).catch(error => { console.error(error); });
WitchesTown/mastodon
app/javascript/packs/public.js
JavaScript
agpl-3.0
4,984
'use strict'; define(['bitcoinjs-lib', 'crypto-js', 'sjcl'], function(Bitcoin, CryptoJS, sjcl) { function TLCrypto() { } TLCrypto.wordsToBytes = function(words) { var bytes = [] for (var b = 0; b < words.length * 32; b += 8) { bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) } return bytes }; TLCrypto.wordArrayToBytes = function(wordArray) { return TLCrypto.wordsToBytes(wordArray.words) }; TLCrypto.hexStringToData = function(hexString) { return new Bitcoin.Buffer(hexString, 'hex'); }; TLCrypto.getPasswordDigest = function(password) { var SHA256 = CryptoJS.SHA256; var passwordDigest = TLCrypto.wordArrayToBytes(SHA256(SHA256(SHA256(password)))); return new Bitcoin.Buffer(passwordDigest).toString('hex'); // maybe go with this password digest or something to that effect //return sjcl.codec.base64.fromBits(sjcl.misc.pbkdf2(password, email, 1000)); }; TLCrypto.getPasswordHash = function(password) { var SHA256 = CryptoJS.SHA256; var passwordDigest = TLCrypto.wordArrayToBytes(SHA256(SHA256(SHA256(SHA256(SHA256(password)))))); return new Bitcoin.Buffer(passwordDigest).toString('hex'); }; TLCrypto.encrypt = function(plainText, password) { var passwordDigest = TLCrypto.getPasswordDigest(password); var privData = sjcl.encrypt(passwordDigest, plainText, {ks: 256, ts: 128}); return privData; }; TLCrypto.decrypt = function(cipherText, password) { var passwordDigest = TLCrypto.getPasswordDigest(password); var data = sjcl.decrypt(passwordDigest, cipherText); return data; }; return TLCrypto; });
arcbit/arcbit-web
src/js/model/TLCrypto.js
JavaScript
agpl-3.0
1,918
/*global plupload */ /*global qiniu */ function FileProgress(file, targetID) { this.fileProgressID = file.id; this.file = file; this.opacity = 100; this.height = 0; this.fileProgressWrapper = $('#' + this.fileProgressID); if (!this.fileProgressWrapper.length) { // <div class="progress"> // <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> // <span class="sr-only">20% Complete</span> // </div> // </div> this.fileProgressWrapper = $('<tr></tr>'); var Wrappeer = this.fileProgressWrapper; Wrappeer.attr('id', this.fileProgressID).addClass('progressContainer'); var progressText = $("<td/>"); progressText.addClass('progressName').text(file.name); var fileSize = plupload.formatSize(file.size).toUpperCase(); var progressSize = $("<td/>"); progressSize.addClass("progressFileSize").text(fileSize); var progressBarTd = $("<td/>"); var progressBarBox = $("<div/>"); progressBarBox.addClass('info'); var progressBarWrapper = $("<div/>"); progressBarWrapper.addClass("progress progress-striped"); var progressBar = $("<div/>"); progressBar.addClass("progress-bar progress-bar-info") .attr('role', 'progressbar') .attr('aria-valuemax', 100) .attr('aria-valuenow', 0) .attr('aria-valuein', 0) .width('0%'); var progressBarPercent = $('<span class=sr-only />'); progressBarPercent.text(fileSize); var progressCancel = $('<a href=javascript:; />'); progressCancel.show().addClass('progressCancel').text('×'); progressBar.append(progressBarPercent); progressBarWrapper.append(progressBar); progressBarBox.append(progressBarWrapper); progressBarBox.append(progressCancel); var progressBarStatus = $('<div class="status text-center"/>'); progressBarBox.append(progressBarStatus); progressBarTd.append(progressBarBox); Wrappeer.append(progressText); Wrappeer.append(progressSize); Wrappeer.append(progressBarTd); $('#' + targetID).append(Wrappeer); } else { this.reset(); } this.height = this.fileProgressWrapper.offset().top; this.setTimer(null); } FileProgress.prototype.setTimer = function(timer) { this.fileProgressWrapper.FP_TIMER = timer; }; FileProgress.prototype.getTimer = function(timer) { return this.fileProgressWrapper.FP_TIMER || null; }; FileProgress.prototype.reset = function() { this.fileProgressWrapper.attr('class', "progressContainer"); this.fileProgressWrapper.find('td .progress .progress-bar-info').attr('aria-valuenow', 0).width('0%').find('span').text(''); this.appear(); }; FileProgress.prototype.setChunkProgess = function(chunk_size) { var chunk_amount = Math.ceil(this.file.size / chunk_size); if (chunk_amount === 1) { return false; } var viewProgess = $('<button class="btn btn-default">查看分块上传进度</button>'); var progressBarChunkTr = $('<tr class="chunk-status-tr"><td colspan=3></td></tr>'); var progressBarChunk = $('<div/>'); for (var i = 1; i <= chunk_amount; i++) { var col = $('<div class="col-md-2"/>'); var progressBarWrapper = $('<div class="progress progress-striped"></div'); var progressBar = $("<div/>"); progressBar.addClass("progress-bar progress-bar-info text-left") .attr('role', 'progressbar') .attr('aria-valuemax', 100) .attr('aria-valuenow', 0) .attr('aria-valuein', 0) .width('0%') .attr('id', this.file.id + '_' + i) .text(''); var progressBarStatus = $('<span/>'); progressBarStatus.addClass('chunk-status').text(); progressBarWrapper.append(progressBar); progressBarWrapper.append(progressBarStatus); col.append(progressBarWrapper); progressBarChunk.append(col); } if(!this.fileProgressWrapper.find('td:eq(2) .btn-default').length){ this.fileProgressWrapper.find('td>div').append(viewProgess); } progressBarChunkTr.hide().find('td').append(progressBarChunk); progressBarChunkTr.insertAfter(this.fileProgressWrapper); }; FileProgress.prototype.setProgress = function(percentage, speed, chunk_size) { this.fileProgressWrapper.attr('class', "progressContainer green"); var file = this.file; var uploaded = file.loaded; var size = plupload.formatSize(uploaded).toUpperCase(); var formatSpeed = plupload.formatSize(speed).toUpperCase(); var progressbar = this.fileProgressWrapper.find('td .progress').find('.progress-bar-info'); if (this.fileProgressWrapper.find('.status').text() === '取消上传'){ return; } this.fileProgressWrapper.find('.status').text("已上传: " + size + " 上传速度: " + formatSpeed + "/s"); percentage = parseInt(percentage, 10); if (file.status !== plupload.DONE && percentage === 100) { percentage = 99; } progressbar.attr('aria-valuenow', percentage).css('width', percentage + '%'); if (chunk_size) { var chunk_amount = Math.ceil(file.size / chunk_size); if (chunk_amount === 1) { return false; } var current_uploading_chunk = Math.ceil(uploaded / chunk_size); var pre_chunk, text; for (var index = 0; index < current_uploading_chunk; index++) { pre_chunk = $('#' + file.id + "_" + index); pre_chunk.width('100%').removeClass().addClass('alert-success').attr('aria-valuenow', 100); text = "块" + index + "上传进度100%"; pre_chunk.next().html(text); } var currentProgessBar = $('#' + file.id + "_" + current_uploading_chunk); var current_chunk_percent; if (current_uploading_chunk < chunk_amount) { if (uploaded % chunk_size) { current_chunk_percent = ((uploaded % chunk_size) / chunk_size * 100).toFixed(2); } else { current_chunk_percent = 100; currentProgessBar.removeClass().addClass('alert-success'); } } else { var last_chunk_size = file.size - chunk_size * (chunk_amount - 1); var left_file_size = file.size - uploaded; if (left_file_size % last_chunk_size) { current_chunk_percent = ((uploaded % chunk_size) / last_chunk_size * 100).toFixed(2); } else { current_chunk_percent = 100; currentProgessBar.removeClass().addClass('alert-success'); } } currentProgessBar.width(current_chunk_percent + '%'); currentProgessBar.attr('aria-valuenow', current_chunk_percent); text = "块" + current_uploading_chunk + "上传进度" + current_chunk_percent + '%'; currentProgessBar.next().html(text); } this.appear(); }; FileProgress.prototype.setComplete = function(up, info) { var td = this.fileProgressWrapper.find('td:eq(2)'), tdProgress = td.find('.progress'); var res = Qiniu.parseJSON(info); var url; if (res.url) { url = res.url; str = "<div><strong>Link:</strong><a href=" + res.url + " target='_blank' > " + res.url + "</a></div>" + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>"; } else { var domain = up.getOption('domain'); url = domain + encodeURI(res.key); var link = domain + res.key; str = "<div><strong>Link:</strong><a href=" + url + " target='_blank' > " + link + "</a></div>" + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>"; } tdProgress.html(str).removeClass().next().next('.status').hide(); td.find('.progressCancel').hide(); var progressNameTd = this.fileProgressWrapper.find('.progressName'); var imageView = '?imageView2/1/w/100/h/100'; var isImage = function(url) { var res, suffix = ""; var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"]; var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/; if (!url || !suffixMatch.test(url)) { return false; } res = suffixMatch.exec(url); suffix = res[1].toLowerCase(); for (var i = 0, l = imageSuffixes.length; i < l; i++) { if (suffix === imageSuffixes[i]) { return true; } } return false; }; var isImg = isImage(url); var Wrapper = $('<div class="Wrapper"/>'); var imgWrapper = $('<div class="imgWrapper col-md-3"/>'); var linkWrapper = $('<a class="linkWrapper" target="_blank"/>'); var showImg = $('<img src="images/loading.gif"/>'); progressNameTd.append(Wrapper); if (!isImg) { showImg.attr('src', 'images/default.png'); Wrapper.addClass('default'); imgWrapper.append(showImg); Wrapper.append(imgWrapper); } else { linkWrapper.append(showImg); imgWrapper.append(linkWrapper); Wrapper.append(imgWrapper); var img = new Image(); if (!/imageView/.test(url)) { url += imageView } $(img).attr('src', url); var height_space = 340; $(img).on('load', function() { showImg.attr('src', url); linkWrapper.attr('href', url).attr('title', '查看原图'); function initImg(url, key, height) { $('#myModal-img').modal(); var modalBody = $('#myModal-img').find('.modal-body'); if (height <= 300) { $('#myModal-img').find('.text-warning').show(); } var newImg = new Image(); modalBody.find('img').attr('src', 'images/loading.gif'); newImg.onload = function() { modalBody.find('img').attr('src', url).data('key', key).data('h', height); modalBody.find('.modal-body-wrapper').find('a').attr('href', url); }; newImg.src = url; } var infoWrapper = $('<div class="infoWrapper col-md-6"></div>'); var fopLink = $('<a class="fopLink"/>'); fopLink.attr('data-key', res.key).text('查看处理效果'); infoWrapper.append(fopLink); fopLink.on('click', function() { var key = $(this).data('key'); var height = parseInt($(this).parents('.Wrapper').find('.origin-height').text(), 10); if (height > $(window).height() - height_space) { height = parseInt($(window).height() - height_space, 10); } else { height = parseInt(height, 10) || 300; //set a default height 300 for ie9- } var fopArr = []; fopArr.push({ fop: 'imageView2', mode: 3, h: height, q: 100, format: 'png' }); fopArr.push({ fop: 'watermark', mode: 1, image: 'http://www.b1.qiniudn.com/images/logo-2.png', dissolve: 100, gravity: 'SouthEast', dx: 100, dy: 100 }); var url = Qiniu.pipeline(fopArr, key); $('#myModal-img').on('hide.bs.modal', function() { $('#myModal-img').find('.btn-default').removeClass('disabled'); $('#myModal-img').find('.text-warning').hide(); }).on('show.bs.modal', function() { $('#myModal-img').find('.imageView').find('a:eq(0)').addClass('disabled'); $('#myModal-img').find('.watermark').find('a:eq(3)').addClass('disabled'); $('#myModal-img').find('.text-warning').hide(); }); initImg(url, key, height); return false; }); var ie = Qiniu.detectIEVersion(); if (!(ie && ie <= 9)) { var exif = Qiniu.exif(res.key); if (exif) { var exifLink = $('<a href="" target="_blank">查看exif</a>'); exifLink.attr('href', url + '?exif'); infoWrapper.append(exifLink); } var imageInfo = Qiniu.imageInfo(res.key); var infoArea = $('<div/>'); var infoInner = '<div>格式:<span class="origin-format">' + imageInfo.format + '</span></div>' + '<div>宽度:<span class="orgin-width">' + imageInfo.width + 'px</span></div>' + '<div>高度:<span class="origin-height">' + imageInfo.height + 'px</span></div>'; infoArea.html(infoInner); infoWrapper.append(infoArea); } Wrapper.append(infoWrapper); }).on('error', function() { showImg.attr('src', 'default.png'); Wrapper.addClass('default'); }); } }; FileProgress.prototype.setError = function() { this.fileProgressWrapper.find('td:eq(2)').attr('class', 'text-warning'); this.fileProgressWrapper.find('td:eq(2) .progress').css('width', 0).hide(); this.fileProgressWrapper.find('button').hide(); this.fileProgressWrapper.next('.chunk-status-tr').hide(); }; FileProgress.prototype.setCancelled = function(manual) { var progressContainer = 'progressContainer'; if (!manual) { progressContainer += ' red'; } this.fileProgressWrapper.attr('class', progressContainer); this.fileProgressWrapper.find('td .progress').remove(); this.fileProgressWrapper.find('td:eq(2) .btn-default').hide(); this.fileProgressWrapper.find('td:eq(2) .progressCancel').hide(); }; FileProgress.prototype.setStatus = function(status, isUploading) { if (!isUploading) { this.fileProgressWrapper.find('.status').text(status).attr('class', 'status text-left'); } }; // 绑定取消上传事件 FileProgress.prototype.bindUploadCancel = function(up) { var self = this; if (up) { self.fileProgressWrapper.find('td:eq(2) .progressCancel').on('click', function(){ self.setCancelled(false); self.setStatus("取消上传"); self.fileProgressWrapper.find('.status').css('left', '0'); up.removeFile(self.file); }); } }; FileProgress.prototype.appear = function() { if (this.getTimer() !== null) { clearTimeout(this.getTimer()); this.setTimer(null); } if (this.fileProgressWrapper[0].filters) { try { this.fileProgressWrapper[0].filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. this.fileProgressWrapper.css('filter', "progid:DXImageTransform.Microsoft.Alpha(opacity=100)"); } } else { this.fileProgressWrapper.css('opacity', 1); } this.fileProgressWrapper.css('height', ''); this.height = this.fileProgressWrapper.offset().top; this.opacity = 100; this.fileProgressWrapper.show(); };
edxzw/edx-platform
cms/static/cms/js/ui.js
JavaScript
agpl-3.0
16,012
OC.L10N.register( "settings", { "Enabled" : "Aktiviert", "Not enabled" : "Nicht aktiviert", "Wrong password" : "Falsches Passwort", "Saved" : "Gespeichert", "No user supplied" : "Kein Benutzer angegeben", "Unable to change password" : "Passwort konnte nicht geändert werden", "Authentication error" : "Authentifizierungsfehler", "Please provide an admin recovery password, otherwise all user data will be lost" : "Bitte geben Sie ein Wiederherstellungspasswort für das Administratorkonto an, da sonst alle Benutzerdaten verlorengehen können", "Wrong admin recovery password. Please check the password and try again." : "Falsches Wiederherstellungspasswort für das Admin-Konto. Bitte überprüfen Sie das Passwort und versuchen Sie es erneut.", "Backend doesn't support password change, but the user's encryption key was successfully updated." : "Das Backend unterstützt die Passwortänderung nicht, aber der Benutzerschlüssel wurde erfolgreich aktualisiert.", "installing and updating apps via the app store or Federated Cloud Sharing" : "Das Installieren und Aktualisieren von Apps durch den App-Store oder durch Federated Cloud Sharing", "Federated Cloud Sharing" : "Federated-Cloud-Sharing", "cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably." : "cURL verwendet eine veraltete %s Version (%s). Bitte aktualisieren Sie ihr Betriebssystem, da ansonsten Funktionen, wie z.B. %s, nicht zuverlässig funktionieren werden.", "A problem occurred, please check your log files (Error: %s)" : "Es ist ein Problem aufgetreten, bitte überprüfen Sie Ihre Logdateien (Fehler: %s)", "Migration Completed" : "Migration abgeschlossen", "Group already exists." : "Gruppe existiert bereits.", "Unable to add group." : "Gruppe konnte nicht angelegt werden.", "Unable to delete group." : "Gruppe konnte nicht gelöscht werden.", "test email settings" : "E-Mail-Einstellungen testen", "A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Beim Senden der E-Mail ist ein Problem aufgetreten. Bitte überprüfen Sie Ihre Einstellungen. (Fehler: %s)", "Email sent" : "E-Mail gesendet", "You need to set your user email before being able to send test emails." : "Sie müssen Ihre Benutzer-E-Mail-Adresse einstellen, bevor Sie Test-E-Mails versenden können.", "Invalid request" : "Ungültige Anforderung", "Invalid mail address" : "Ungültige E-Mail-Adresse", "No valid group selected" : "Keine gültige Gruppe ausgewählt", "A user with that name already exists." : "Ein Benutzer mit diesem Namen existiert bereits.", "To send a password link to the user an email address is required." : "Um einen Passwort-Link an einen Benutzer zu versenden wird eine E-Mail-Adresse benötigt.", "Unable to create user." : "Benutzer konnte nicht erstellt werden.", "Your %s account was created" : "Ihr %s-Konto wurde erstellt", "Unable to delete user." : "Benutzer konnte nicht gelöscht werden.", "Settings saved" : "Einstellungen gespeichert", "Unable to change full name" : "Der vollständige Name konnte nicht geändert werden", "Unable to change email address" : "E-Mail-Adresse konnte nicht geändert werden", "Your full name has been changed." : "Ihr vollständiger Name ist geändert worden.", "Forbidden" : "Verboten", "Invalid user" : "Ungültiger Benutzer", "Unable to change mail address" : "E-Mail-Adresse konnte nicht geändert werden", "Email saved" : "E-Mail-Adresse gespeichert", "Password confirmation is required" : "Passwortbestätigung erforderlich", "Couldn't remove app." : "Die App konnte nicht entfernt werden.", "Couldn't update app." : "Die App konnte nicht aktualisiert werden.", "Are you really sure you want add {domain} as trusted domain?" : "Sind Sie sich wirklich sicher, dass Sie {domain} als vertrauenswürdige Domain hinzufügen möchten?", "Add trusted domain" : "Vertrauenswürdige Domain hinzufügen", "Migration in progress. Please wait until the migration is finished" : "Migration in Arbeit. Bitte warten Sie, bis die Migration beendet ist", "Migration started …" : "Migration begonnen…", "Not saved" : "Nicht gespeichert", "Sending..." : "Wird gesendet…", "Official" : "Offiziell", "All" : "Alle", "Update to %s" : "Aktualisierung auf %s", "_You have %n app update pending_::_You have %n app updates pending_" : ["Es ist %n App-Aktualisierung verfügbar","Es sind %n App-Aktualisierungen verfügbar"], "No apps found for your version" : "Es wurden keine Apps für Ihre Version gefunden", "The app will be downloaded from the app store" : "Die App wird aus dem App-Store heruntergeladen", "Official apps are developed by and within the community. They offer central functionality and are ready for production use." : "Offizielle Apps werden von und innerhalb der Community entwickelt. Sie stellen die zentralen Funktionen bereit und sind für den produktiven Einsatz geeignet.", "Approved apps are developed by trusted developers and have passed a cursory security check. They are actively maintained in an open code repository and their maintainers deem them to be stable for casual to normal use." : "Geprüfte Apps werden von vertrauenswürdigen Entwicklern entwickelt und haben eine oberflächliche Sicherheitsprüfung durchlaufen. Sie werden innerhalb eines offenen Code-Repositorys aktiv gepflegt und ihre Betreuer erachten sie als stabil genug für für den gelegentlichen bis normalen Einsatz.", "This app is not checked for security issues and is new or known to be unstable. Install at your own risk." : "Diese App ist nicht auf Sicherheitsprobleme hin überprüft und ist neu oder bekanntermaßen instabil. Die Installation erfolgt auf eigenes Risiko.", "Disabling app …" : "App wird deaktiviert …", "Error while disabling app" : "Beim Deaktivieren der App ist ein Fehler aufgetreten", "Disable" : "Deaktivieren", "Enable" : "Aktivieren", "Enabling app …" : "Aktiviere App ...", "Error while enabling app" : "Beim Aktivieren der App ist ein Fehler aufgetreten", "Error: this app cannot be enabled because it makes the server unstable" : "Fehler: Diese App kann nicht aktiviert werden, da es den Server instabil macht.", "Error: could not disable broken app" : "Fehler: Die beschädigte Anwendung konnte nicht deaktiviert werden", "Error while disabling broken app" : "Beim Deaktivieren der defekten App ist ein Fehler aufgetreten", "Updating...." : "Aktualisiere…", "Error while updating app" : "Es ist ein Fehler während der Aktualisierung aufgetreten", "Updated" : "Aktualisiert", "Uninstalling ...." : "Wird deinstalliert…", "Error while uninstalling app" : "Fehler beim Deinstallieren der App", "Uninstall" : "Deinstallieren", "The app has been enabled but needs to be updated. You will be redirected to the update page in 5 seconds." : "Die App wurde aktiviert, aber sie benötigt ein Update. Sie werden zur Update Seite in 5 Sekunden weitergeleitet.", "App update" : "App aktualisieren", "Approved" : "Geprüft", "Experimental" : "Experimentell", "No apps found for {query}" : "Keine Applikationen für {query} gefunden", "Allow filesystem access" : "Erlaube Dateisystem-Zugriff", "Disconnect" : "Trennen", "Revoke" : "Widerrufen", "Internet Explorer" : "Internet Explorer", "Edge" : "Edge", "Firefox" : "Firefox", "Google Chrome" : "Google Chrome", "Safari" : "Safari", "Google Chrome for Android" : "Google Chrome für Android", "iPhone iOS" : "iPhone iOS", "iPad iOS" : "iPad iOS", "iOS Client" : "iOS-Client", "Android Client" : "Android-Client", "Sync client - {os}" : "Sync-Client - {os}", "This session" : "Diese Sitzung", "Copy" : "Kopieren", "Copied!" : "Kopiert!", "Not supported!" : "Nicht unterstützt!", "Press ⌘-C to copy." : "⌘-C zum Kopieren drücken.", "Press Ctrl-C to copy." : "Ctrl-C zum Kopieren drücken.", "Error while loading browser sessions and device tokens" : "Fehler beim Laden der Browser-Sitzungen und Geräte-Token", "Error while creating device token" : "Fehler beim Erstellen des Geräte-Tokens", "Error while deleting the token" : "Fehler beim Löschen des Geräte-Tokens", "An error occurred. Please upload an ASCII-encoded PEM certificate." : "Es ist ein Fehler aufgetreten. Bitte laden Sie ein ASCII-kodiertes PEM-Zertifikat hoch.", "Valid until {date}" : "Gültig bis {date}", "Delete" : "Löschen", "Local" : "Lokal", "Private" : "Privat", "Only visible to local users" : "Nur für lokale Benutzer sichtbar", "Only visible to you" : "Nur für Sie sichtbar", "Contacts" : "Kontakte", "Visible to local users and to trusted servers" : "Sichtbar für lokale Nutzer und vertrauenswürdige Server", "Public" : "Öffentlich", "Will be synced to a global and public address book" : "Wird mit einem globalen und einem öffentlichen Adressbuch synchronisiert", "Select a profile picture" : "Wählen Sie ein Profilbild", "Very weak password" : "Sehr schwaches Passwort", "Weak password" : "Schwaches Passwort", "So-so password" : "Akzeptables Passwort", "Good password" : "Gutes Passwort", "Strong password" : "Starkes Passwort", "Groups" : "Gruppen", "Unable to delete {objName}" : "Löschen von {objName} nicht möglich", "Error creating group: {message}" : "Fehler beim Erstellen einer Gruppe: {message}", "A valid group name must be provided" : "Ein gültiger Gruppenname muss angegeben werden", "deleted {groupName}" : "{groupName} gelöscht", "undo" : "rückgängig machen", "never" : "niemals", "deleted {userName}" : "{userName} gelöscht", "Unable to add user to group {group}" : "Benutzer kann nicht zur Gruppe {group} hinzugefügt werden ", "Unable to remove user from group {group}" : "Benutzer kann nicht aus der Gruppe {group} entfernt werden ", "Add group" : "Gruppe hinzufügen", "Invalid quota value \"{val}\"" : "Ungültiger Grenzwert \"{val}\"", "no group" : "Keine Gruppe", "Password successfully changed" : "Das Passwort wurde erfolgreich geändert", "Changing the password will result in data loss, because data recovery is not available for this user" : "Die Änderung des Passworts führt zu Datenverlust, weil die Datenwiederherstellung für diesen Benutzer nicht verfügbar ist", "Could not change the users email" : "Die E-Mail-Adresse des Nutzers konnte nicht geändert werden", "A valid username must be provided" : "Es muss ein gültiger Benutzername angegeben werden", "Error creating user: {message}" : "Fehler beim Erstellen eines Benutzers: {message}", "A valid password must be provided" : "Es muss ein gültiges Passwort angegeben werden", "A valid email must be provided" : "Es muss eine gültige E-Mail-Adresse angegeben werden", "__language_name__" : "Deutsch (Förmlich: Sie)", "Unlimited" : "Unbegrenzt", "Personal info" : "Persönliche Informationen", "Sessions" : "Sitzungen", "App passwords" : "App-PINs", "Sync clients" : "Sync-Clients", "None" : "Keine", "Login" : "Anmelden", "Plain" : "Klartext", "NT LAN Manager" : "NT-LAN-Manager", "SSL/TLS" : "SSL/TLS", "STARTTLS" : "STARTTLS", "Email server" : "E-Mail-Server", "Open documentation" : "Dokumentation öffnen", "This is used for sending out notifications." : "Dies wird für das Senden von Benachrichtigungen verwendet.", "Send mode" : "Sendemodus", "Encryption" : "Verschlüsselung", "From address" : "Absenderadresse", "mail" : "Mail", "Authentication method" : "Authentifizierungsmethode", "Authentication required" : "Authentifizierung benötigt", "Server address" : "Serveradresse", "Port" : "Port", "Credentials" : "Zugangsdaten", "SMTP Username" : "SMTP-Benutzername", "SMTP Password" : "SMTP-Passwort", "Store credentials" : "Anmeldeinformationen speichern", "Test email settings" : "E-Mail-Einstellungen testen", "Send email" : "E-Mail senden", "Server-side encryption" : "Serverseitige Verschlüsselung", "Enable server-side encryption" : "Serverseitige Verschlüsselung aktivieren", "Please read carefully before activating server-side encryption: " : "Bitte lesen Sie ganz genau, bevor Sie die serverseitige Verschlüsselung aktivieren:", "Once encryption is enabled, all files uploaded to the server from that point forward will be encrypted at rest on the server. It will only be possible to disable encryption at a later date if the active encryption module supports that function, and all pre-conditions (e.g. setting a recover key) are met." : "Wird die Verschlüsselung einmal aktiviert, so werden alle ab diesem Zeitpunkt hochgeladene Dateien verschlüsselt. Sie kann nur wieder deaktiviert werden, wenn das Verschlüsselungsmodul dies unterstützt und alle Voraussetzungen (wie das Setzen eines Wiederherstellungsschlüssels) im Vorhinein erfüllt wurden.", "Encryption alone does not guarantee security of the system. Please see documentation for more information about how the encryption app works, and the supported use cases." : "Verschlüsselung alleine garantiert nicht die Systemsicherheit. Bitte lese in der Dokumentation nach, wie die Verschlüsselungs-app funktioniert und welche Anwendungsfälle unterstützt werden.", "Be aware that encryption always increases the file size." : "Bedenken Sie, dass durch die Verschlüsselung die Dateigröße zunimmt. ", "It is always good to create regular backups of your data, in case of encryption make sure to backup the encryption keys along with your data." : "Es ist immer gut, regelmäßig Sicherungskopien von ihren Daten zu machen. Falls Sie die Verschlüsselung nutzen, sollten Sie auch eine Sicherung der Verschlüsselungsschlüssel zusammen mit ihren Daten machen.", "This is the final warning: Do you really want to enable encryption?" : "Dies ist die letzte Warnung: Wollen Sie die Verschlüsselung wirklich aktivieren?", "Enable encryption" : "Verschlüsselung aktivieren", "No encryption module loaded, please enable an encryption module in the app menu." : "Kein Verschlüsselungs-Modul geladen, bitte aktiviere ein Verschlüsselungs-Modul im Anwendungs-Menü.", "Select default encryption module:" : "Standard-Verschlüsselungs-Modul auswählen:", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please enable the \"Default encryption module\" and run 'occ encryption:migrate'" : "Sie müssen Ihre Verschlüsselungsschlüssel von der alten Verschlüsselung (ownCloud <= 8.0) zur Neuen migrieren. Bitte aktivieren Sie das \"Default Encryption Module\" und rufen Sie 'occ encryption:migrate' auf.", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one." : "Sie müssen Ihre Verschlüsselungsschlüssel von der alten Verschlüsselung (ownCloud <= 8.0) zur Neuen migrieren.", "Start migration" : "Migration beginnen", "Security & setup warnings" : "Sicherheits- & Einrichtungswarnungen", "php does not seem to be setup properly to query system environment variables. The test with getenv(\"PATH\") only returns an empty response." : "PHP scheint zur Abfrage von Systemumgebungsvariablen nicht richtig eingerichtet zu sein. Der Test mit getenv (\"PATH\") liefert nur eine leere Antwort zurück.", "Please check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation documentation ↗</a> for php configuration notes and the php configuration of your server, especially when using php-fpm." : "Bitte schauen Sie in der <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Installationsdokumentation ↗</a>auf Hinweise zur PHP-Konfiguration, sowie die PHP-Konfiguration ihres Servers, insbesondere dann, wenn Sie PHP-FPM einsetzten.", "The Read-Only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Die schreibgeschützte Konfiguration wurde aktiviert. Dies verhindert das Setzen einiger Einstellungen über die Web-Schnittstelle. Weiterhin muss bei jedem Update der Schreibzugriff auf die Datei händisch aktiviert werden.", "PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "PHP ist offenbar so konfiguriert, dass PHPDoc-Blöcke in der Anweisung entfernt werden. Dadurch sind mehrere Kern-Apps nicht erreichbar.", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Dies wird wahrscheinlich durch Zwischenspeicher/Beschleuniger wie etwa Zend OPcache oder eAccelerator verursacht.", "Your database does not run with \"READ COMMITTED\" transaction isolation level. This can cause problems when multiple actions are executed in parallel." : "Ihre Datenbank läuft nicht mit der \"READ COMMITED\" Transaktionsisolationsstufe. Dies kann Probleme hervorrufen, wenn mehrere Aktionen parallel ausgeführt werden.", "%1$s below version %2$s is installed, for stability and performance reasons we recommend updating to a newer %1$s version." : "%1$s ist in einer älteren Version als %2$s installiert. Aus Stabilitäts- und Performancegründen empfehlen wir eine Aktualisierung auf eine neuere %1$s-Version", "The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "Das PHP-Modul 'fileinfo' fehlt. Wir empfehlen Ihnen dieses Modul zu aktivieren, um die besten Resultate bei der Bestimmung der Dateitypen zu erzielen.", "Transactional file locking is disabled, this might lead to issues with race conditions. Enable 'filelocking.enabled' in config.php to avoid these problems. See the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a> for more information." : "Transaktionales Sperren ist deaktiviert, was zu Problemen mit Laufzeitbedingungen führen kann. Aktivieren Sie 'filelocking.enabled' in der config.php diese Probleme zu vermeiden. Weitere Informationen findest Sie in unserer <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Dokumentation ↗</a>.", "System locale can not be set to a one which supports UTF-8." : "Es kann kein Systemgebietsschema gesetzt werden, das UTF-8 unterstützt.", "This means that there might be problems with certain characters in file names." : "Dies bedeutet, dass es zu Problemen mit bestimmten Zeichen in Dateinamen kommen kann.", "We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Wir empfehlen dringend, die erforderlichen Pakete auf Ihrem System zu installieren, damit eines der folgenden Gebietsschemata unterstützt wird: %s.", "If your installation is not installed in the root of the domain and uses system cron, there can be issues with the URL generation. To avoid these problems, please set the \"overwrite.cli.url\" option in your config.php file to the webroot path of your installation (Suggested: \"%s\")" : "Wenn sich Ihre Installation nicht im Wurzelverzeichnis der Domain befindet und Cron aus dem System genutzt wird, kann es zu Fehlern bei der URL-Generierung kommen. Um dies zu verhindern, setzen Sie bitte die „overwrite.cli.url“-Option in Ihrer config.php auf das Web-Wurzelverzeichnis Ihrer Installation (Vorschlag: „%s“).", "It was not possible to execute the cronjob via CLI. The following technical errors have appeared:" : "Die Ausführung des Cron-Jobs über die Kommandozeile war nicht möglich. Die folgenden technischen Fehler sind dabei aufgetreten:", "Please double check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation guides ↗</a>, and check for any errors or warnings in the <a href=\"%s\">log</a>." : "Bitte überprüfen Sie noch einmal die <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Installationsanleitungen ↗</a> und kontrollieren Sie das <a href=\"%s\">Log</a> auf mögliche Fehler oder Warnungen.", "All checks passed." : "Alle Checks bestanden.", "Cron" : "Cron", "Last cron job execution: %s." : "Letzte Cron-Job-Ausführung: %s.", "Last cron job execution: %s. Something seems wrong." : "Letzte Cron-Job-Ausführung: %s. Möglicherweise liegt ein Fehler vor.", "Cron was not executed yet!" : "Cron wurde bislang noch nicht ausgeführt!", "Execute one task with each page loaded" : "Eine Aufgabe bei jedem Laden einer Seite ausführen", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php ist als Webcron-Dienst registriert, der die cron.php alle 15 Minuten per HTTP aufruft.", "Use system's cron service to call the cron.php file every 15 minutes." : "Benutzen Sie den systemeigenen Cron-Dienst, um die cron.php alle 15 Minuten aufzurufen.", "The cron.php needs to be executed by the system user \"%s\"." : "Die cron.php muss durch den Systemnutzer \"%s\" ausgeführt werden.", "To run this you need the PHP posix extension. See {linkstart}PHP documentation{linkend} for more details." : "Um dies auszuführen, benötigen Sie die PHP-Posix Erweiterung. Weitere Informationen in der {linkstart}PHP-Dokumentation{linkend}.", "Version" : "Version", "Sharing" : "Teilen", "Allow apps to use the Share API" : "Apps die Benutzung der Share-API erlauben", "Allow users to share via link" : "Benutzern erlauben, Inhalte über Links zu teilen", "Allow public uploads" : "Öffentliches Hochladen erlauben", "Enforce password protection" : "Passwortschutz erzwingen", "Set default expiration date" : "Standardmäßiges Ablaufdatum setzen", "Expire after " : "Ablauf nach ", "days" : "Tagen", "Enforce expiration date" : "Ablaufdatum erzwingen", "Allow resharing" : "Weiterteilen erlauben", "Allow sharing with groups" : "Mit Gruppen teilen erlauben", "Restrict users to only share with users in their groups" : "Benutzer auf das Teilen innerhalb ihrer Gruppen beschränken", "Exclude groups from sharing" : "Gruppen von Freigaben ausschließen", "These groups will still be able to receive shares, but not to initiate them." : "Diese Gruppen können weiterhin Freigaben empfangen, aber selbst keine mehr initiieren.", "Allow username autocompletion in share dialog. If this is disabled the full username needs to be entered." : "Die Auto-Vervollständigung von Benutzernamen im Teilen-Dialog erlauben. Wenn dies deaktiviert ist, muss der vollständige Benutzername eingegeben werden.", "Show disclaimer text on the public link upload page. (Only shown when the file list is hidden.)" : "Zeige Haftungsausschluss auf der öffentlichen Upload-Seite. (Wird nur gezeigt wenn die Dateiliste nicht angezeigt wird.) ", "This text will be shown on the public link upload page when the file list is hidden." : "Dieser Text wird auf der öffentlichen Upload-Seite angezeigt wenn die Dateiliste nicht angezeigt wird.", "Tips & tricks" : "Tipps & Tricks", "SQLite is currently being used as the backend database. For larger installations we recommend that you switch to a different database backend." : "SQLite wird als Datenbank verwendet. Bei größeren Installationen empfehlen wir, auf ein anderes Datenbank-Backend zu wechseln.", "This is particularly recommended when using the desktop client for file synchronisation." : "Dies wird insbesondere bei der Benutzung des Dektop-Clients zur Synchronisierung empfohlen.", "To migrate to another database use the command line tool: 'occ db:convert-type', or see the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a>." : "Um zu einer anderen Datenbank zu migrieren, benutzen Sie bitte die Kommandozeile: 'occ db:convert-type', oder in die <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Dokumentation ↗</a> schauen.", "How to do backups" : "Wie man Datensicherungen anlegt", "Advanced monitoring" : "Erweitertes Monitoring", "Performance tuning" : "Leistungsoptimierung", "Improving the config.php" : "Die config.php optimieren", "Theming" : "Themes verwenden", "Hardening and security guidance" : "Systemhärtung und Sicherheitsempfehlungen", "Developer documentation" : "Dokumentation für Entwickler", "by %s" : "von %s", "%s-licensed" : "%s-Lizensiert", "Documentation:" : "Dokumentation:", "User documentation" : "Benutzer-Dokumentation", "Admin documentation" : "Administratoren-Dokumentation", "Visit website" : "Webseite besuchen", "Report a bug" : "Melden Sie einen technischen Fehler", "Show description …" : "Beschreibung anzeigen…", "Hide description …" : "Beschreibung ausblenden…", "This app has an update available." : "Für diese Anwendung ist eine Aktualisierung verfügbar.", "This app has no minimum Nextcloud version assigned. This will be an error in the future." : "Für diese App wurde keine untere Versionsgrenze für Nextcloud gesetzt. Dies wird zukünftig als Fehler behandelt.", "This app has no maximum Nextcloud version assigned. This will be an error in the future." : "Für diese App wurde keine obere Versionsgrenze für Nextcloud gesetzt. Dies wird zukünftig als Fehler behandelt.", "This app cannot be installed because the following dependencies are not fulfilled:" : "Diese App kann nicht installiert werden, weil die folgenden Abhängigkeiten nicht erfüllt sind:", "Enable only for specific groups" : "Nur für bestimmte Gruppen aktivieren", "Uninstall app" : "App deinstallieren", "SSL Root Certificates" : "SSL Root Zertifikate", "Common Name" : "Allgemeiner Name", "Valid until" : "Gültig bis", "Issued By" : "Ausgestellt von:", "Valid until %s" : "Gültig bis %s", "Import root certificate" : "Root-Zertifikat importieren", "Hey there,<br><br>just letting you know that you now have a %s account.<br><br>Your username: <strong>%s</strong><br>Access it: <strong><a href=\"%s\">%s</a></strong><br><br>" : "Hallo,<br><br>hier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.<br><br>Ihr Benutzername: <strong>%s</strong><br>Greifen Sie darauf zu: <strong><a href=\"%s\">%s</a></strong><br><br>", "Cheers!" : "Noch einen schönen Tag!", "Hey there,\n\njust letting you know that you now have a %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hallo,\n\nhier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.\n\nIhr Benutzername: %s\nZugriff: %s\n\n", "Administrator documentation" : "Dokumentation für Administratoren", "Online documentation" : "Online-Dokumentation", "Forum" : "Forum", "Getting help" : "Hilfe bekommen", "Commercial support" : "Kommerzieller Support", "You are using <strong>%s</strong> of <strong>%s</strong>" : "Sie verwenden <strong>%s</strong> der verfügbaren <strong>%s</strong>", "Profile picture" : "Profilbild", "Upload new" : "Neues hochladen", "Select from Files" : "Aus Dateien wählen", "Remove image" : "Bild entfernen", "png or jpg, max. 20 MB" : "png oder jpg, max. 20 MB", "Picture provided by original account" : "Bild von Original-Konto zur Verfügung gestellt", "Cancel" : "Abbrechen", "Choose as profile picture" : "Als Profilbild auswählen", "Full name" : "Vollständiger Name", "No display name set" : "Kein Anzeigename angegeben", "Email" : "E-Mail", "Your email address" : "Ihre E-Mail-Adresse", "No email address set" : "Keine E-Mail-Adresse angegeben", "For password reset and notifications" : "Für Passwort-Wiederherstellung und Benachrichtigungen", "Phone number" : "Telefonnummer", "Your phone number" : "Ihre Telefonnummer", "Address" : "Adresse", "Your postal address" : "Ihre Postadresse", "Website" : "Webseite", "Your website" : "Ihre Internetseite", "Twitter" : "Twitter", "Your Twitter handle" : "Ihr Twitter-Handle", "You are member of the following groups:" : "Sie sind Mitglied folgender Gruppen:", "Password" : "Passwort", "Current password" : "Aktuelles Passwort", "New password" : "Neues Passwort", "Change password" : "Passwort ändern", "Language" : "Sprache", "Help translate" : "Helfen Sie bei der Übersetzung", "Get the apps to sync your files" : "Installieren Sie die Anwendungen, um Ihre Dateien zu synchronisieren", "Desktop client" : "Desktop-Client", "Android app" : "Android-App", "iOS app" : "iOS-App", "If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!" : "Wenn Sie das Projekt unterstützen wollen {contributeopen} helfen Sie bei der Entwicklung{linkclose} oder {contributeopen} verbreiten Sie es{linkclose}!", "Show First Run Wizard again" : "Den Einrichtungsassistenten erneut anzeigen", "Web, desktop and mobile clients currently logged in to your account." : "Aktuell in Ihrem Konto eingeloggte Web-, Desktop- und Mobil-Clients.", "Device" : "Gerät", "Last activity" : "Letzte Aktivität", "Passcodes that give an app or device permissions to access your account." : "PINs mit denen Apps oder Geräte auf Ihr Konto zugreifen können.", "Name" : "Name", "App name" : "App-Name", "Create new app password" : "Neues App-Passwort erstellen", "Use the credentials below to configure your app or device." : "Nutzen Sie die unten angebenen Anmeldeinformationen, um ihre App oder ihr Gerät zu konfigurieren.", "For security reasons this password will only be shown once." : "Aus Sicherheitsgründen wird das Passwort nur einmal angezeigt.", "Username" : "Benutzername", "Done" : "Erledigt", "Developed by the {communityopen}Nextcloud community{linkclose}, the {githubopen}source code{linkclose} is licensed under the {licenseopen}AGPL{linkclose}." : "Entwickelt von der {communityopen}Nextcloud Community{linkclose}, der {githubopen}Quellcode{linkclose} ist lizensiert unter {licenseopen}AGPL{linkclose}-Lizenz.", "Follow us on Google Plus!" : "Folgen Sie uns zu Google Plus!", "Like our facebook page!" : "Liken Sie uns auf unserer Facebook-Seite!", "Subscribe to our twitter channel!" : "Abonnieren Sie unseren Twitter-Kanal!", "Subscribe to our news feed!" : "Abonnieren Sie unseren RSS-Feed!", "Subscribe to our newsletter!" : "Abonnieren Sie unseren Newsletter!", "Show storage location" : "Speicherort anzeigen", "Show last log in" : "Letzte Anmeldung anzeigen", "Show user backend" : "Benutzer-Backend anzeigen", "Send email to new user" : "E-Mail an neuen Benutzer senden", "When the password of the new user is left empty an activation email with a link to set the password is send to the user" : "Wenn das Passwort für den neuen Benutzer leer gelassen wird, wird an ihn eine Aktivierungs-E-Mail mit einem Link zur Passwortvergabe versandt.", "Show email address" : "E-Mail Adresse anzeigen", "E-Mail" : "E-Mail", "Create" : "Erstellen", "Admin Recovery Password" : "Admin-Passwort-Wiederherstellung", "Enter the recovery password in order to recover the users files during password change" : "Geben Sie das Wiederherstellungspasswort ein, um die Benutzerdateien während der Passwortänderung wiederherzustellen", "Group name" : "Gruppenname", "Everyone" : "Jeder", "Admins" : "Administratoren", "Default quota" : "Standard-Kontingent", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Bitte Speicherkontingent eingeben (z.B.: „512 MB“ oder „12 GB“)", "Other" : "Andere", "Group admin for" : "Gruppenadministrator für", "Quota" : "Kontingent", "Storage location" : "Speicherort", "User backend" : "Benutzer-Backend", "Last login" : "Letzte Anmeldung", "change full name" : "Vollständigen Namen ändern", "set new password" : "Neues Passwort setzen", "change email address" : "E-Mail-Adresse ändern", "Default" : "Standard", "log-level out of allowed range" : "Log-Level außerhalb des erlaubten Bereichs", "Language changed" : "Sprache geändert", "Admins can't remove themself from the admin group" : "Administratoren können sich nicht selbst aus der admin-Gruppe löschen", "Unable to add user to group %s" : "Der Benutzer konnte nicht zur Gruppe %s hinzugefügt werden", "Unable to remove user from group %s" : "Der Benutzer konnte nicht aus der Gruppe %s entfernt werden", "Are you really sure you want add \"{domain}\" as trusted domain?" : "Sind Sie sich wirklich sicher, dass Sie \"{domain}\" als vertrauenswürdige Domain hinzufügen möchten?", "Please wait...." : "Bitte warten…", "add group" : "Gruppe hinzufügen", "Everything (fatal issues, errors, warnings, info, debug)" : "Alles (fatale Probleme, Fehler, Warnungen, Infos, Fehlerdiagnose)", "Info, warnings, errors and fatal issues" : "Infos, Warnungen, Fehler und fatale Probleme", "Warnings, errors and fatal issues" : "Warnungen, Fehler und fatale Probleme", "Errors and fatal issues" : "Fehler und fatale Probleme", "Fatal issues only" : "Nur kritische Fehler", "Log" : "Log", "What to log" : "Was geloggt wird", "Download logfile" : "Logdatei herunterladen", "More" : "Mehr", "Less" : "Weniger", "The logfile is bigger than 100 MB. Downloading it may take some time!" : "Die Logdatei ist größer als 100 MB. Es kann etwas Zeit beanspruchen, sie herunterzuladen!", "Allow users to send mail notification for shared files" : "Benutzern erlauben, E-Mail-Benachrichtigungen für freigegebene Dateien zu senden", "Allow users to send mail notification for shared files to other users" : "Benutzern erlauben, E-Mail-Benachrichtigungen für freigegebene Dateien an andere Benutzer zu senden", "SQLite is used as database. For larger installations we recommend to switch to a different database backend." : "SQLite wird als Datenbank verwendet. Bei größeren Installationen wird empfohlen, auf ein anderes Datenbank-Backend zu wechseln.", "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "Insbesondere bei der Nutzung des Desktop Clients zur Dateisynchronisierung wird vom Einsatz von SQLite abgeraten.", "Experimental applications ahead" : "Experimentelle Apps nachfolgend", "Experimental apps are not checked for security issues, new or known to be unstable and under heavy development. Installing them can cause data loss or security breaches." : "Experimentelle Apps sind nicht auf Sicherheitsprobleme hin überprüft, sind neu oder bekanntermaßen instabil und befinden sich in intensiver Entwicklung. Ihre Installation kann Datenverlust oder Sicherheitslücken hervorrufen.", "Uninstall App" : "App deinstallieren", "Enable experimental apps" : "Experimentelle Apps aktivieren", "Hey there,<br><br>just letting you know that you now have an %s account.<br><br>Your username: %s<br>Access it: <a href=\"%s\">%s</a><br><br>" : "Hallo,<br><br>hier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.<br><br>Ihr Benutzername: %s<br>Greifen Sie darauf zu: <a href=\"%s\">%s</a><br><br>", "Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hallo,\n\nhier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.\n\nIhr Benutzername: %s\nGreifen Sie darauf zu: %s\n\n", "For password recovery and notifications" : "Für Passwort-Wiederherstellung und Benachrichtigungen", "If you want to support the project\n\t\t<a href=\"https://nextcloud.com/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">join development</a>\n\t\tor\n\t\t<a href=\"https://nextcloud.com/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">spread the word</a>!" : "Wenn Sie das Projekt unterstützen möchten\n⇥⇥<a href=\"https://nextcloud.com/contribute\"\n⇥⇥⇥target=\"_blank\" rel=\"noreferrer\">helfen Sie bei der Weiterentwicklung</a>\n⇥⇥oder\n⇥⇥<a href=\"https://nextcloud.com/contribute\"\n⇥⇥⇥target=\"_blank\" rel=\"noreferrer\">empfehlen Sie es weiter</a>!", "Add Group" : "Gruppe hinzufügen", "Group" : "Gruppe", "Default Quota" : "Standard-Quota", "Full Name" : "Vollständiger Name", "Group Admin for" : "Gruppenadministrator für", "Storage Location" : "Speicherort", "User Backend" : "Benutzer-Backend", "Last Login" : "Letzte Anmeldung" }, "nplurals=2; plural=(n != 1);");
whitekiba/server
settings/l10n/de_DE.js
JavaScript
agpl-3.0
36,870
/* Copyright 2008 Clipperz Srl This file is part of Clipperz Community Edition. Clipperz Community Edition is a web-based password manager and a digital vault for confidential data. For further information about its features and functionalities please refer to http://www.clipperz.com * Clipperz Community Edition is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * Clipperz Community Edition is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Clipperz Community Edition. If not, see <http://www.gnu.org/licenses/>. */ if (typeof(Clipperz) == 'undefined') { Clipperz = {}; } if (typeof(Clipperz.PM) == 'undefined') { Clipperz.PM = {}; } if (typeof(Clipperz.PM.Components) == 'undefined') { Clipperz.PM.Components = {}; } if (typeof(Clipperz.PM.Components.Panels) == 'undefined') { Clipperz.PM.Components.Panels = {}; } //############################################################################# Clipperz.PM.Components.Panels.ContactsPanel = function(anElement, args) { args = args || {}; Clipperz.PM.Components.Panels.ContactsPanel.superclass.constructor.call(this, anElement, args); this.render(); return this; } //============================================================================= YAHOO.extendX(Clipperz.PM.Components.Panels.ContactsPanel, Clipperz.PM.Components.Panels.BasePanel, { 'toString': function() { return "Clipperz.PM.Components.ContactsPanel component"; }, //------------------------------------------------------------------------- 'render': function() { // var tabPanelControllerConfig; Clipperz.YUI.DomHelper.append(this.element().dom, {tag:'table', border:'0', cellspacing:'0', cellpadding:'0', children:[ {tag:'tbody', children:[ {tag:'tr', children:[ {tag:'td', valign:'top', width:'200', children:[ {tag:'ul', id:"dataSubMenu", cls:'subMenu', children:[ {tag:'li', id:this.getId('contacts'), htmlString:Clipperz.PM.Strings['contactsTabLabel']}, ]} ]}, {tag:'td', valign:'top', children:[ {tag:'ul', cls:'clipperzTabPanels', children:[ {tag:'li', id:this.getId('contactsPanel'), children:[ {tag:'div', cls:'clipperzSubPanel', children:[ {tag:'h5', htmlString:Clipperz.PM.Strings['contactsTabTitle']}, {tag:'div', htmlString:Clipperz.PM.Strings['comingSoon']} ]} ]} ]} ]} ]} ]} ]}); // tabPanelControllerConfig = {} // tabPanelControllerConfig[this.getId('contacts')] = this.getId('contactsPanel'); // new Clipperz.PM.Components.TabPanel.TabPanelController({ config:tabPanelControllerConfig, selectedTab:this.getId('contacts') }); this.tabPanelController().setUp(); }, //------------------------------------------------------------------------- 'tabPanelController': function() { if (this._tabPanelController == null) { var tabPanelControllerConfig; tabPanelControllerConfig = {} tabPanelControllerConfig[this.getId('contacts')] = this.getId('contactsPanel'); this._tabPanelController = new Clipperz.PM.Components.TabPanel.TabPanelController({ config:tabPanelControllerConfig, selectedTab:this.getId('contacts') }); } return this._tabPanelController; }, //------------------------------------------------------------------------- __syntaxFix__: "syntax fix" });
weisslj/clipperz-communityEdition
js/src/Clipperz/PM/Components/Panels/ContactsPanel.js
JavaScript
agpl-3.0
3,757
import mongoose from 'mongoose'; import Boom from 'boom'; import Bounce from 'bounce'; import { log, logErr } from '../../shared/utils'; import eventStore from '../stores/eventStore'; import alertStore from '../stores/alertStore'; import userStore from '../stores/userStore'; const ObjectId = mongoose.Types.ObjectId; const alertController = { async createAlert(req, h) { let alert = null; let user; let payloadEvent; try { if (!ObjectId.isValid(req.payload.event)) throw new Error("Event ID is not valid."); payloadEvent = await eventStore.getEvent(req.payload.event); if (!payloadEvent) throw new Error("Event not found."); if (req.payload && req.payload["sent.by"]) { if (!ObjectId.isValid(req.payload["sent.by"])) throw new Error("Sent by user ID is not valid."); user = await userStore.getUser(ObjectId(req.payload["sent.by"])); if (!user) throw new Error("Sent by user not found."); } const newLoad = { ...payloadEvent.toObject(), // TO-DO: add parser with string formatting type: payloadEvent.type.toString(), event: ObjectId(req.payload.event), sent: { by: (req.payload["sent.by"]) ? req.payload["sent.by"] : null, at: Date.now() } }; delete newLoad["id"]; alert = await alertStore.createAlert(newLoad); if (!alert) throw new Error("Alert returned empty."); const response = h.response(alert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController createAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error creating alert."); } }, async updateAlert(req, h) { // updateAlert just sets expireNow to true let alert; let updatedAlert; try { alert = await alertStore.updateAlert(req.params.alertID); if (!alert) throw new Error("Alert not found."); updatedAlert = await alertStore.getAlert(alert.id); const response = h.response(updatedAlert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController updateAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error updating alert."); } }, async getAlerts(req, h) { // only fetches unexpired alerts let alerts; try { alerts = await alertStore.getAlerts(); if (!alerts) throw new Error("No alerts found."); const response = h.response(alerts); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAlerts error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alerts."); } }, async getAlert(req, h) { let alert; try { alert = await alertStore.getAlert(ObjectId(req.params.alertID)); if (!alert) throw new Error("Alert not found."); const response = h.response(alert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alert."); } }, async getAllAlerts(req, h) { let alerts; try { alerts = await alertStore.getAllAlerts(); if (!alerts) throw new Error("No alerts found."); const response = h.response(alerts); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAllAlerts error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alerts."); } }, }; export default alertController;
Cosecha/redadalertas-api
src/server/app/api/controllers/alertController.js
JavaScript
agpl-3.0
3,644
import ENV from 'irene/config/environment'; class ENVHandler { constructor(envHandlerConst) { this.envHandlerConst = envHandlerConst; } isRuntimeAvailable() { return !(typeof runtimeGlobalConfig == 'undefined'); } getEnv(env_key) { const host_key = 'IRENE_API_HOST'; this.assertEnvKey(env_key); if (this.isAvailableInRuntimeENV(env_key)) { const runtimeValue = this.getRuntimeObject()[env_key]; if (env_key === host_key) { if (runtimeValue === '/') { return ''; } } return runtimeValue; } if (this.isAvailableInProcessENV(env_key)) { const processValue = this.envHandlerConst.processENV[env_key]; if (env_key === host_key) { if (processValue === '/') { return ''; } } return processValue; } return this.getDefault(env_key); } isRegisteredEnv(env_key) { return this.envHandlerConst.possibleENVS.indexOf(env_key) > -1; } isAvailableInENV(env_key) { return ( this.isAvailableInRuntimeENV(env_key) || this.isAvailableInProcessENV(env_key) ); } getRuntimeObject() { if (this.isRuntimeAvailable()) { return runtimeGlobalConfig; // eslint-disable-line } return {}; } isAvailableInRuntimeENV(env_key) { const runtimeObj = this.getRuntimeObject(); return env_key in runtimeObj; } isAvailableInProcessENV(env_key) { return env_key in this.envHandlerConst.processENV; } assertEnvKey(env_key) { if (!this.isRegisteredEnv(env_key)) { throw new Error(`ENV: ${env_key} not registered`); } } isTrue(value) { value = String(value).toLowerCase(); return value === 'true'; } getBoolean(env_key) { return this.isTrue(this.getEnv(env_key)); } getDefault(env_key) { this.assertEnvKey(env_key); return this.envHandlerConst.defaults[env_key]; } getValueForPlugin(env_key) { const enterpriseKey = 'ENTERPRISE'; this.assertEnvKey(enterpriseKey); this.assertEnvKey(env_key); if (this.isAvailableInENV(env_key)) { return this.getBoolean(env_key); } if (this.isAvailableInENV(enterpriseKey)) { return !this.getBoolean(enterpriseKey); } return this.getDefault(env_key); } } const handler = new ENVHandler(ENV.ENVHandlerCONST); const initialize = function (application) { // inject Ajax application.inject('route', 'ajax', 'service:ajax'); application.inject('component', 'ajax', 'service:ajax'); // Inject notify application.inject('route', 'notify', 'service:notifications'); application.inject('component', 'notify', 'service:notifications'); application.inject('authenticator', 'notify', 'service:notifications'); // Inject realtime application.inject('component', 'realtime', 'service:realtime'); // Inject Store application.inject('component', 'store', 'service:store'); ENV.host = handler.getEnv('IRENE_API_HOST'); ENV.devicefarmHost = handler.getEnv('IRENE_DEVICEFARM_HOST'); ENV.isEnterprise = handler.getBoolean('ENTERPRISE'); ENV.showLicense = handler.getBoolean('IRENE_SHOW_LICENSE'); ENV.whitelabel = Object.assign({}, ENV.whitelabel, { enabled: handler.getBoolean('WHITELABEL_ENABLED'), }); if (ENV.whitelabel.enabled) { ENV.whitelabel = Object.assign({}, ENV.whitelabel, { enabled: handler.getBoolean('WHITELABEL_ENABLED'), // adding for consistency name: handler.getEnv('WHITELABEL_NAME'), logo: handler.getEnv('WHITELABEL_LOGO'), theme: handler.getEnv('WHITELABEL_THEME'), favicon: handler.getEnv('WHITELABEL_FAVICON'), }); } ENV.enableHotjar = handler.getValueForPlugin('IRENE_ENABLE_HOTJAR'); ENV.enablePendo = handler.getValueForPlugin('IRENE_ENABLE_PENDO'); ENV.enableCSB = handler.getValueForPlugin('IRENE_ENABLE_CSB'); ENV.enableMarketplace = handler.getValueForPlugin('IRENE_ENABLE_MARKETPLACE'); ENV.emberRollbarClient = { enabled: handler.getValueForPlugin('IRENE_ENABLE_ROLLBAR'), }; // Inject ENV if (ENV.environment !== 'test') { // FIXME: Fix this test properly application.register('env:main', ENV, { singleton: true, instantiate: false, }); return application.inject('component', 'env', 'env:main'); } }; const IreneInitializer = { name: 'irene', initialize, }; export { initialize }; export default IreneInitializer;
appknox/irene
app/initializers/irene.js
JavaScript
agpl-3.0
4,399
OC.L10N.register( "deck", { "Deck" : "Deck", "Personal" : "Personal", "Finished" : "Terminado", "To review" : "Para revisar", "Action needed" : "Acción requerida", "Later" : "Después", "copy" : "copiar", "Done" : "Hecho", "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" : "El archivo subido sobrepasa el valor MAX_FILE_SIZE especificada en el formulario HTML", "No file was uploaded" : "No se subió ningún archivo ", "Missing a temporary folder" : "Falta un directorio temporal", "Add board" : "Nuevo Tablero", "Cancel" : "Cancelar", "Hide archived cards" : "Ocultar tarjetas archivadas", "Show archived cards" : "Mostrar tarjetas archivadas", "Details" : "Detalles", "Sharing" : "Compartiendo", "Tags" : "Etiquetas", "Undo" : "Deshacer", "Can edit" : "Puede editar", "Can share" : "Puede compartir", "Delete" : "Eliminar", "Edit" : "Editar", "Members" : "Miembros", "Attachments" : "Adjuntos", "Comments" : "Comentarios", "Modified" : "Modificado", "Created" : "Creado", "Due date" : "Fecha de vencimiento", "Select Date" : "Seleccionar fecha", "Today" : "Hoy", "Tomorrow" : "Mañana", "Save" : "Guardar", "Reply" : "Responder", "Update" : "Actualizar", "Description" : "Descripción", "Formatting help" : "Ayuda de formato", "(group)" : "(grupo)", "seconds ago" : "segundos", "All boards" : "Todos los Tableros", "Shared with you" : "Compartido con usted", "Board details" : "Detalles del tablero", "Edit board" : "Editar Tablero", "Clone board" : "Clonar Tablero", "Delete board" : "Eliminar Tablero", "An error occurred" : "Ocurrió un error", "This week" : "Esta semana" }, "nplurals=2; plural=(n != 1);");
nextcloud/deck
l10n/es_AR.js
JavaScript
agpl-3.0
1,856
var error = require('parts/error'); exports.create = function(callback, millisec, cyclic){ if(typeof(setInterval) == 'undefined' &&typeof(setTimeout) == 'undefined') return new error('not supported', 'this platform is not supported timer functionality'); var id = cyclic ? setInterval(callback, millisec) : setTimeout(callback, millisec); return { destroy : function(){ cyclic ? clearInterval(id) : clearTimeout(id); } }; }
ixdu/capsule
modules/timer.js
JavaScript
agpl-3.0
457
/* * NASA Worldview * * This code was originally developed at NASA/Goddard Space Flight Center for * the Earth Science Data and Information System (ESDIS) project. * * Copyright (C) 2013 - 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. */ var wv = wv || {}; wv.proj = (function(self) { self.parse = function(state, errors, config) { // Permalink version 1.0 - 1.1 if ( state["switch"] ) { state.p = state["switch"]; delete state["switch"]; } var projId = state.p; if ( projId ) { if ( !config.projections[projId] ) { delete state.p; errors.push({message: "Unsupported projection: " + projId}); } } }; return self; })(wv.proj || {});
cchang3/worldview-design
src/animation-module/code/web/js/proj/wv.proj.js
JavaScript
agpl-3.0
885
import Ember from 'ember'; import _validate from 'ember-simple-validate/utils/validate'; import Validator from 'ember-simple-validate/lib/validator'; var get = Ember.get; var set = Ember.set; var validValidator = function(validator) { return validator instanceof Validator; }; export default Ember.Mixin.create({ init: function() { this._super(); set(this, 'isValid', undefined); }, validate: function() { set(this, 'validationErrors', {}); if(!this.canValidate()) { set(this, 'isValid', true); } else { var self = this; var validators = get(this, 'validators'); set(this, 'isValid', _validate(this, validators)); Ember.keys(validators).forEach(function(key) { Ember.makeArray(validators[key]).forEach(function(validator) { self.addErrors(key, get(validator, 'errors')); }); }); } return this.get('isValid'); }, canValidate: function() { var validators = get(this, 'validators') || {}; var canValidate = true; var keys = Ember.keys(validators); if(keys && keys.length) { keys.forEach(function(key) { var validatorList = Ember.makeArray(validators[key]); validatorList.forEach(function(validator) { if(!validValidator(validator)) { canValidate = false; return false; } }); }); } else { canValidate = false; } return canValidate; }, addErrors: function(key, errors) { var self = this; Ember.makeArray(errors).forEach(function(error) { self.addError(key, error); }); }, addError: function(key, error) { var self = this; var keyParts = key.split('.'); var path = 'validationErrors'; keyParts.forEach(function(key, i) { path += '.' + key; if(!get(self, path)) { var blank = i === keyParts.length - 1 ? Ember.A() : {}; set(self, path, blank); } }); get(this, 'validationErrors.' + key).pushObject(error); } });
ChinookBook/ember-simple-validate
addon/mixins/simple-validation-mixin.js
JavaScript
agpl-3.0
2,032
import _ from 'lodash'; import React from 'react'; import {PreviewModal} from '../previewModal'; SendItem.$inject = ['$q', 'api', 'desks', 'notify', 'authoringWorkspace', 'superdeskFlags', '$location', 'macros', '$rootScope', 'deployConfig', 'authoring', 'send', 'editorResolver', 'confirm', 'archiveService', 'preferencesService', 'multi', 'datetimeHelper', 'config', 'privileges', 'storage', 'modal', 'gettext', 'urls']; export function SendItem($q, api, desks, notify, authoringWorkspace, superdeskFlags, $location, macros, $rootScope, deployConfig, authoring, send, editorResolver, confirm, archiveService, preferencesService, multi, datetimeHelper, config, privileges, storage, modal, gettext, urls) { return { scope: { item: '=', view: '=', orig: '=', _beforeSend: '&beforeSend', _editable: '=editable', _publish: '&publish', _action: '=action', mode: '@', }, controller: function() { this.userActions = { send_to: 'send_to', publish: 'publish', duplicate_to: 'duplicate_to', externalsource_to: 'externalsource_to', }; }, controllerAs: 'vm', templateUrl: 'scripts/apps/authoring/views/send-item.html', link: function sendItemLink(scope, elem, attrs, ctrl) { scope.mode = scope.mode || 'authoring'; scope.desks = null; scope.stages = null; scope.macros = null; scope.userDesks = null; scope.allDesks = null; scope.task = null; scope.selectedDesk = null; scope.selectedStage = null; scope.selectedMacro = null; scope.beforeSend = scope._beforeSend || $q.when; scope.destination_last = {send_to: null, publish: null, duplicate_to: null}; scope.origItem = angular.extend({}, scope.item); scope.subscribersWithPreviewConfigured = []; // key for the storing last desk/stage in the user preferences for send action. var PREFERENCE_KEY = 'destination:active'; // key for the storing last user action (send to/publish) in the storage. var USER_ACTION_KEY = 'send_to_user_action'; scope.$watch('item', activateItem); scope.$watch(send.getConfig, activateConfig); scope.publish = function() { scope.loading = true; var result = scope._publish(); return $q .resolve(result) .then(null, (e) => $q.reject(false)) .finally(() => { scope.loading = false; }); }; function activateConfig(config, oldConfig) { if (scope.mode !== 'authoring' && config !== oldConfig) { scope.isActive = !!config; scope.item = scope.isActive ? {} : null; scope.multiItems = multi.count ? multi.getItems() : null; scope.config = config; activate(); } } function activateItem(item) { if (scope.mode === 'monitoring') { superdeskFlags.flags.fetching = !!item; } scope.isActive = !!item; activate(); } function activate() { if (scope.isActive) { api.query('subscribers') .then((res) => { const allSubscribers = res['_items']; scope.subscribersWithPreviewConfigured = allSubscribers .map( (subscriber) => { subscriber.destinations = subscriber.destinations.filter( (destination) => typeof destination.preview_endpoint_url === 'string' && destination.preview_endpoint_url.length > 0 ); return subscriber; } ) .filter((subscriber) => subscriber.destinations.length > 0); }); desks .initialize() .then(fetchDesks) .then(initialize) .then(setDesksAndStages); } } scope.preview = function() { if (scope.$parent.save_enabled() === true) { modal.alert({ headerText: gettext('Preview'), bodyText: gettext( 'In order to preview the item, save the changes first.' ), }); } else { modal.createCustomModal() .then(({openModal, closeModal}) => { openModal( <PreviewModal subscribersWithPreviewConfigured={scope.subscribersWithPreviewConfigured} documentId={scope.item._id} urls={urls} closeModal={closeModal} gettext={gettext} /> ); }); } }; scope.close = function() { if (scope.mode === 'monitoring') { superdeskFlags.flags.fetching = false; } if (scope.$parent.views) { scope.$parent.views.send = false; } else if (scope.item) { scope.item = null; } $location.search('fetch', null); if (scope.config) { scope.config.reject(); } }; scope.selectDesk = function(desk) { scope.selectedDesk = _.cloneDeep(desk); scope.selectedStage = null; fetchStages(); fetchMacros(); }; scope.selectStage = function(stage) { scope.selectedStage = stage; }; scope.selectMacro = function(macro) { if (scope.selectedMacro === macro) { scope.selectedMacro = null; } else { scope.selectedMacro = macro; } }; scope.send = function(open) { updateLastDestination(); return runSend(open); }; scope.$on('item:nextStage', (_e, data) => { if (scope.item && scope.item._id === data.itemId) { var oldStage = scope.selectedStage; scope.selectedStage = data.stage; scope.send().then((sent) => { if (!sent) { scope.selectedStage = oldStage; } }); } }); // events on which panel should close var closePanelEvents = ['item:spike', 'broadcast:preview']; angular.forEach(closePanelEvents, (event) => { scope.$on(event, shouldClosePanel); }); /** * @description Closes the opened 'duplicate/send To' panel if the same item getting * spiked or any item is opening for authoring. * @param {Object} event * @param {Object} data - contains the item(=itemId) that was spiked or {item: null} when * any item opened for authoring (utilising, 'broadcast:preview' with {item: null}) */ function shouldClosePanel(event, data) { if ( (scope.config != null && data != null && _.includes(scope.config.itemIds, data.item)) || (data == null || data.item == null) ) { scope.close(); } } /* * Returns true if Destination field and Send button needs to be displayed, false otherwise. * @returns {Boolean} */ scope.showSendButtonAndDestination = function() { if (scope.itemActions) { var preCondition = scope.mode === 'ingest' || scope.mode === 'personal' || scope.mode === 'monitoring' || scope.mode === 'authoring' && scope.isSendEnabled() && scope.itemActions.send || scope.mode === 'spike'; if (scope.currentUserAction === ctrl.userActions.publish) { return preCondition && scope.showSendAndPublish(); } return preCondition; } }; /* * Returns true if Send and Send and Continue button needs to be disabled, false otherwise. * @returns {Boolean} */ scope.disableSendButton = function() { return !scope.selectedDesk || scope.mode !== 'ingest' && scope.selectedStage && scope.mode !== 'spike' && (_.get(scope, 'item.task.stage') === scope.selectedStage._id || _.includes(_.map(scope.multiItems, 'task.stage'), scope.selectedStage._id)); }; /* * Returns true if user is not a member of selected desk, false otherwise. * @returns {Boolean} */ scope.disableFetchAndOpenButton = function() { if (scope.selectedDesk) { var _isNonMember = _.isEmpty(_.find(desks.userDesks, {_id: scope.selectedDesk._id})); return _isNonMember; } }; /** * Returns true if Publish Schedule needs to be displayed, false otherwise. */ scope.showPublishSchedule = function() { return scope.item && archiveService.getType(scope.item) !== 'ingest' && scope.item.type !== 'composite' && !scope.item.embargo_date && !scope.item.embargo_time && ['published', 'killed', 'corrected', 'recalled'].indexOf(scope.item.state) === -1 && canPublishOnDesk(); }; /** * Returns true if timezone needs to be displayed, false otherwise. */ scope.showTimezone = function() { return (scope.item.publish_schedule || scope.item.embargo) && (scope.showPublishSchedule() || scope.showEmbargo()); }; /** * Returns true if Embargo needs to be displayed, false otherwise. */ scope.showEmbargo = function() { // If user doesn't have embargo privilege then don't display embargo fields if (!privileges.privileges.embargo) { return false; } if (config.ui && config.ui.publishEmbargo === false) { return false; } var prePublishCondition = scope.item && archiveService.getType(scope.item) !== 'ingest' && scope.item.type !== 'composite' && !scope.item.publish_schedule_date && !scope.item.publish_schedule_time; if (prePublishCondition && authoring.isPublished(scope.item)) { if (['published', 'corrected'].indexOf(scope.item.state) >= 0) { return scope.origItem.embargo; } // for published states other than 'published', 'corrected' return false; } return prePublishCondition; }; /** * Returns true if Embargo needs to be displayed, false otherwise. */ scope.isEmbargoEditable = function() { var publishedCondition = authoring.isPublished(scope.item) && scope.item.schedule_settings && scope.item.schedule_settings.utc_embargo && datetimeHelper.greaterThanUTC(scope.item.schedule_settings.utc_embargo); return scope.item && scope.item._editable && (!authoring.isPublished(scope.item) || publishedCondition); }; /** * Send the content to different desk/stage * @param {Boolean} open - True to open the item. * @return {Object} promise */ function runSend(open) { scope.loading = true; scope.item.sendTo = true; var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; if (scope.mode === 'authoring') { return sendAuthoring(deskId, stageId, scope.selectedMacro); } else if (scope.mode === 'archive') { return sendContent(deskId, stageId, scope.selectedMacro, open); } else if (scope.config) { scope.config.promise.finally(() => { scope.loading = false; }); return scope.config.resolve({ desk: deskId, stage: stageId, macro: scope.selectedMacro ? scope.selectedMacro.name : null, open: open, }); } else if (scope.mode === 'ingest') { return sendIngest(deskId, stageId, scope.selectedMacro, open); } } /** * Enable Disable the Send and Publish button. * Send And Publish is enabled using `superdesk.config.js`. */ scope.showSendAndPublish = () => !config.ui || angular.isUndefined(config.ui.sendAndPublish) || config.ui.sendAndPublish; /** * Check if the Send and Publish is allowed or not. * Following conditions are to met for Send and Publish action * - Item is not Published i.e. not state Published, Corrected, Killed or Scheduled * - Selected destination (desk/stage) should be different from item current location (desk/stage) * - Mode should be authoring * - Publish Action is allowed on that item. * @return {Boolean} */ scope.canSendAndPublish = function() { if (scope.mode !== 'authoring' || !scope.item) { return false; } // Selected destination desk should be different from item current location desk var isDestinationChanged = scope.selectedDesk && scope.item.task.desk !== scope.selectedDesk._id; return scope.showSendAndPublish() && !authoring.isPublished(scope.item) && isDestinationChanged && scope.mode === 'authoring' && scope.itemActions.publish; }; /** * Returns true if 'send' button should be displayed. Otherwise, returns false. * @return {boolean} */ scope.isSendEnabled = () => scope.item && !authoring.isPublished(scope.item); /* * Send the current item to different desk or stage and publish the item from new location. */ scope.sendAndPublish = function() { return runSendAndPublish(); }; /* * Returns true if 'send' action is allowed, otherwise false * @returns {Boolean} */ scope.canSendItem = function() { var itemType = [], typesList; if (scope.multiItems) { angular.forEach(scope.multiItems, (item) => { itemType[item._type] = 1; }); typesList = Object.keys(itemType); itemType = typesList.length === 1 ? typesList[0] : null; } return scope.mode === 'authoring' || itemType === 'archive' || scope.mode === 'spike' || (scope.mode === 'monitoring' && _.get(scope, 'config.action') === scope.vm.userActions.send_to); }; /** * Check if it is allowed to publish on current desk * @returns {Boolean} */ function canPublishOnDesk() { return !(isAuthoringDesk() && config.features.noPublishOnAuthoringDesk); } /** * If the action is correct and kill then the publish privilege needs to be checked. */ scope.canPublishItem = function() { if (!scope.itemActions || !canPublishOnDesk()) { return false; } if (scope._action === 'edit') { return scope.item ? !scope.item.flags.marked_for_not_publication && scope.itemActions.publish : scope.itemActions.publish; } else if (scope._action === 'correct') { return privileges.privileges.publish && scope.itemActions.correct; } else if (scope._action === 'kill') { return privileges.privileges.publish && scope.itemActions.kill; } return false; }; /** * Set the User Action. */ scope.setUserAction = function(action) { if (scope.currentUserAction === action) { return; } scope.currentUserAction = action; storage.setItem(USER_ACTION_KEY, action); setDesksAndStages(); }; /** * Checks if a given item is valid to publish * * @param {Object} item story to be validated * @return {Object} promise */ const validatePublish = (item) => api.save('validate', {act: 'publish', type: item.type, validate: item}); /** * Sends and publishes the current item in scope * First checks if the item is dirty and pops up save dialog if needed * Then checks if the story is valid to publish before sending * Then sends the story to the destination * Then publishes it * * @param {Object} item story to be validated * @return {Object} promise */ const runSendAndPublish = () => { var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; // send releases lock, increment version. return scope.beforeSend({action: 'Send and Publish'}) .then(() => validatePublish(scope.item) .then((validationResult) => { if (_.get(validationResult, 'errors.length')) { for (var i = 0; i < validationResult.errors.length; i++) { notify.error('\'' + _.trim(validationResult.errors[i]) + '\''); } return $q.reject(); } return sendAuthoring(deskId, stageId, scope.selectedMacro, true) .then((item) => { scope.loading = true; // open the item for locking and publish return authoring.open(scope.item._id, false); }) .then((item) => { // update the original item to avoid 412 error. scope.orig._etag = scope.item._etag = item._etag; scope.orig._locked = scope.item._locked = item._locked; scope.orig.task = scope.item.task = item.task; // change the desk location. $rootScope.$broadcast('desk_stage:change'); // if locked then publish if (item._locked) { return scope.publish(); } return $q.reject(); }) .then((result) => { if (result) { authoringWorkspace.close(false); } }) .catch((error) => { notify.error(gettext('Failed to send and publish.')); }); }) .finally(() => { scope.loading = false; }) ); }; /** * Run the macro and returns to the modified item. * @param {Object} item * @param {String} macro * @return {Object} promise */ function runMacro(item, macro) { if (macro) { return macros.call(macro, item, true).then((res) => angular.extend(item, res)); } return $q.when(item); } /** * Send to different location from authoring. * @param {String} deskId - selected desk Id * @param {String} stageId - selected stage Id * @param {String} macro - macro to apply * @return {Object} promise */ function sendAuthoring(deskId, stageId, macro) { var msg; scope.loading = true; return runMacro(scope.item, macro) .then((item) => api.find('tasks', scope.item._id) .then((task) => { scope.task = task; msg = 'Send'; return scope.beforeSend({action: msg}); }) .then((result) => { if (result && result._etag) { scope.task._etag = result._etag; } return api.save('move', {}, {task: {desk: deskId, stage: stageId}}, scope.item); }) .then((value) => { notify.success(gettext('Item sent.')); if (scope.currentUserAction === ctrl.userActions.send_to) { // Remember last destination desk and stage for send_to. var lastDestination = scope.destination_last[scope.currentUserAction]; if (!lastDestination || (lastDestination.desk !== deskId || lastDestination.stage !== stageId)) { updateLastDestination(); } } authoringWorkspace.close(true); return true; }, (err) => { if (err) { if (angular.isDefined(err.data._message)) { notify.error(err.data._message); } else if (angular.isDefined(err.data._issues['validator exception'])) { notify.error(err.data._issues['validator exception']); } } })) .finally(() => { scope.loading = false; }); } /** * Update the preferences to store last destinations * @param {String} key */ function updateLastDestination() { var updates = {}; var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; updates[PREFERENCE_KEY] = {desk: deskId, stage: stageId}; preferencesService.update(updates, PREFERENCE_KEY); } /** * Send content to different desk and stage * @param {String} deskId * @param {String} stageId * @param {String} macro * @param {Boolean} open - If true open the item. */ function sendContent(deskId, stageId, macro, open) { var finalItem; scope.loading = true; return api.save('duplicate', {}, {desk: scope.item.task.desk}, scope.item) .then((item) => api.find('archive', item._id)) .then((item) => runMacro(item, macro)) .then((item) => { finalItem = item; return api.find('tasks', item._id); }) .then((_task) => { scope.task = _task; api.save('tasks', scope.task, { task: _.extend(scope.task.task, {desk: deskId, stage: stageId}), }); }) .then(() => { notify.success(gettext('Item sent.')); scope.close(); if (open) { $location.url('/authoring/' + finalItem._id); } else { $rootScope.$broadcast('item:fetch'); } }) .finally(() => { scope.loading = false; }); } /** * Fetch content from ingest to a different desk and stage * @param {String} deskId * @param {String} stageId * @param {String} macro * @param {Boolean} open - If true open the item. */ function sendIngest(deskId, stageId, macro, open) { scope.loading = true; return send.oneAs(scope.item, { desk: deskId, stage: stageId, macro: macro ? macro.name : macro, }).then((finalItem) => { notify.success(gettext('Item fetched.')); if (open) { authoringWorkspace.edit(finalItem); } else { $rootScope.$broadcast('item:fetch'); } }) .finally(() => { scope.loading = false; }); } /** * Fetch desk and last selected desk and stage for send_to and publish action * @return {Object} promise */ function fetchDesks() { return desks.initialize() .then(() => { // get all desks scope.allDesks = desks.desks._items; // get user desks return desks.fetchCurrentUserDesks(); }) .then((deskList) => { scope.userDesks = deskList; return preferencesService.get(PREFERENCE_KEY); }) .then((result) => { if (result) { scope.destination_last.send_to = { desk: result.desk, stage: result.stage, }; scope.destination_last.duplicate_to = { desk: result.desk, stage: result.stage, }; } }); } /** * Set the last selected desk based on the user action. * To be called after currentUserAction is set */ function setDesksAndStages() { if (!scope.currentUserAction) { return; } // set the desks for desk filter if (scope.currentUserAction === ctrl.userActions.publish) { scope.desks = scope.userDesks; } else { scope.desks = scope.allDesks; } if (scope.mode === 'ingest') { scope.selectDesk(desks.getCurrentDesk()); } else { // set the last selected desk or current desk var itemDesk = desks.getItemDesk(scope.item); var lastDestination = scope.destination_last[scope.currentUserAction]; if (itemDesk) { if (lastDestination && !_.isNil(lastDestination.desk)) { scope.selectDesk(desks.deskLookup[lastDestination.desk]); } else { scope.selectDesk(itemDesk); } } else if (lastDestination && !_.isNil(lastDestination.desk)) { scope.selectDesk(desks.deskLookup[lastDestination.desk]); } else { scope.selectDesk(desks.getCurrentDesk()); } } } /** * Set stages and last selected stage. */ function fetchStages() { if (!scope.selectedDesk) { return; } scope.stages = desks.deskStages[scope.selectedDesk._id]; var stage = null; if (scope.currentUserAction === ctrl.userActions.send_to || scope.currentUserAction === ctrl.userActions.duplicate_to) { var lastDestination = scope.destination_last[scope.currentUserAction]; if (lastDestination) { stage = _.find(scope.stages, {_id: lastDestination.stage}); } else if (scope.item.task && scope.item.task.stage) { stage = _.find(scope.stages, {_id: scope.item.task.stage}); } } if (!stage) { stage = _.find(scope.stages, {_id: scope.selectedDesk.incoming_stage}); } scope.selectedStage = stage; } /** * Fetch macros for the selected desk. */ function fetchMacros() { if (!scope.selectedDesk) { return; } macros.getByDesk(scope.selectedDesk.name) .then((_macros) => { scope.macros = _macros; }); } /** * Initialize Item Actios and User Actions. */ function initialize() { initializeItemActions(); initializeUserAction(); } /** * Initialize User Action */ function initializeUserAction() { // default user action scope.currentUserAction = storage.getItem(USER_ACTION_KEY) || ctrl.userActions.send_to; if (scope.orig || scope.item) { if (scope.config && scope.config.action === 'externalsourceTo') { scope.currentUserAction = ctrl.userActions.externalsource_to; } // if the last action is send to but item is published open publish tab. if (scope.config && scope.config.action === 'duplicateTo') { scope.currentUserAction = ctrl.userActions.duplicate_to; } if (scope.currentUserAction === ctrl.userActions.send_to && scope.canPublishItem() && !scope.isSendEnabled()) { scope.currentUserAction = ctrl.userActions.publish; } else if (scope.currentUserAction === ctrl.userActions.publish && !scope.canPublishItem() && scope.showSendButtonAndDestination()) { scope.currentUserAction = ctrl.userActions.send_to; } else if (scope.currentUserAction === ctrl.userActions.publish && isAuthoringDesk() && noPublishOnAuthoringDesk()) { scope.currentUserAction = ctrl.userActions.send_to; } } } /** * The itemActions defined in parent scope (Authoring Directive) is made accessible via this method. * scope.$parent isn't used as send-item directive is used in multiple places and has different * hierarchy. */ function initializeItemActions() { if (scope.orig || scope.item) { scope.itemActions = authoring.itemActions(scope.orig || scope.item); } } /** * Test if desk of current item is authoring type. * * @return {Boolean} */ function isAuthoringDesk() { if (!_.get(scope, 'item.task.desk')) { return false; } const desk = desks.getItemDesk(scope.item); return desk && desk.desk_type === 'authoring'; } /** * Test if noPublishOnAuthoringDesk config is active. * * @return {Boolean} */ function noPublishOnAuthoringDesk() { return config.features.noPublishOnAuthoringDesk; } // update actions on item save scope.$watch('orig._current_version', initializeItemActions); }, }; }
jerome-poisson/superdesk-client-core
scripts/apps/authoring/authoring/directives/SendItem.js
JavaScript
agpl-3.0
35,674
/** The FlamingLayer Class **/ /** * @constructor * @augments Layer * @description The superclass for all flamingolayers * @param id The id of the layer * @param options The options to be given to the layer * @param flamingoObject The flamingo object of the layer * */ Ext.define("viewer.viewercontroller.flamingo.FlamingoLayer",{ enabledEvents: null, type: null, constructor :function (config){ if (config.id){ this.id = config.viewerController.mapComponent.makeFlamingoAcceptableId(config.id); config.id = this.id; } this.enabledEvents=new Object(); this.map = this.viewerController ? this.viewerController.mapComponent.getMap() : null; return this; }, /** * Get's the frameworklayer: the viewer specific layer. */ getFrameworkLayer : function(){ if (this.map==null){ return null; } return this.map.getFrameworkMap(); }, toXML : function(){ Ext.Error.raise({msg: "FlamingoLayer.toXML(): .toXML() must be made!"}); }, getTagName : function(){ Ext.Error.raise({msg: "FlamingoLayer.getTagName: .getTagName() must be made!"}); }, setOption : function(optionKey,optionValue){ this.options[optionKey]=optionValue; }, getId : function(){ return this.id; }, getFrameworkId: function(){ return this.map.getId()+"_"+this.getId(); }, setAlpha : function (alpha){ // Fixup wrong Flash alpha, it thinks 0 is transparent and 100 is opaque if(this.map) { this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"setAlpha",alpha) } }, getAlpha : function (){ return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getAlpha"); }, /** * Get the last getMap request array * @see viewer.viewerController.controller.Layer#getLastMapRequest */ getLastMapRequest: function(){ var request=this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getLastGetMapRequest"); if (request==null){ return null; } return [request]; }, /** * Returns the type of the layer. */ getType: function(){ return this.type; }, /** * reloads the framework map */ reload: function(){ if (this.map !=null && this.map.getFrameworkMap()){ return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"update"); } }, /** * Overwrites the addListener function. Add's the event to allowexternalinterface of flamingo * so flamingo is allowed to broadcast the event. */ addListener : function(event,handler,scope){ //enable flamingo event broadcasting var flamEvent=this.viewerController.mapComponent.eventList[event]; if (flamEvent!=undefined){ //if not enabled yet, add it if (this.enabledEvents[flamEvent]==undefined){ this.map.getFrameworkMap().callMethod(this.viewerController.mapComponent.getId(),"addAllowExternalInterface",this.getFrameworkId()+"."+flamEvent); this.enabledEvents[flamEvent]=true; } } /* fix for infinite loop: * If this is called from a layer that extends the FlamingoArcLayer the superclass is * that FlamingoArcLayer and this function is called again when this.superclass.function is called **/ if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){ this.superclass.superclass.addListener.call(this,event,handler,scope); }else{ this.superclass.addListener.call(this,event,handler,scope); } //viewer.viewercontroller.controller.Layer.superclass.addListener.call(this,event,handler,scope); }, setVisible : function (visible){ this.visible = visible; if (this.options!=null){ this.options["visible"] = visible; } if (this.map !=null){ this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "setVisible", visible); } }, /** * Get the visibility */ getVisible : function (){ if (this.map !=null){ this.visible = this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "getVisible"); } if (this.options!=null) this.options["visible"] = this.visible; return this.visible; }, /** * Overwrite destroy, clear Listeners and forward to super.destroy */ destroy: function(){ /* fix for infinite loop: * If this is called from a layer that extends the FlamingoArcLayer the superclass is * that FlamingoArcLayer and this function is called again when this.superclass.function is called **/ if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){ this.superclass.superclass.destroy.call(this); }else{ this.superclass.destroy.call(this); } } });
mvdstruijk/flamingo
viewer/src/main/webapp/viewer-html/common/viewercontroller/flamingo/FlamingoLayer.js
JavaScript
agpl-3.0
5,324
import React from 'react'; import { DragSource, DropTarget } from 'react-dnd'; import { compose } from 'redux'; import DragDropItemTypes from './DragDropItemTypes'; import { HeaderDeleted, HeaderNormal } from './SampleDetailsContainersAux'; const orderSource = { beginDrag(props) { const { container, sample } = props; return { cId: container.id, sId: sample.id }; }, }; const orderTarget = { drop(targetProps, monitor) { const { container, sample, handleMove } = targetProps; const tgTag = { cId: container.id, sId: sample.id }; const scTag = monitor.getItem(); if (tgTag.sId === scTag.sId && tgTag.cId !== scTag.cId) { handleMove(scTag, tgTag); } }, }; const orderDragCollect = (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), }); const orderDropCollect = (connect, monitor) => ({ connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop(), }); const ContainerRow = ({ sample, container, mode, readOnly, isDisabled, handleRemove, handleSubmit, handleAccordionOpen, toggleAddToReport, handleUndo, connectDragSource, connectDropTarget, isDragging, isOver, canDrop, }) => { const style = {}; if (canDrop) { style.borderStyle = 'dashed'; style.borderWidth = 2; } if (isOver) { style.borderColor = '#337ab7'; } if (isDragging) { style.opacity = 0.2; } const oPanelCN = container.is_deleted ? "order-panel-delete" : "order-panel"; return compose(connectDragSource, connectDropTarget)( <div className={oPanelCN} style={style}> <div className="dnd-btn"> <span className="text-info fa fa-arrows" /> </div> { container.is_deleted ? <HeaderDeleted container={container} handleUndo={handleUndo} mode={mode} /> : <HeaderNormal sample={sample} container={container} mode={mode} handleUndo={handleUndo} readOnly={readOnly} isDisabled={isDisabled} handleRemove={handleRemove} handleSubmit={handleSubmit} handleAccordionOpen={handleAccordionOpen} toggleAddToReport={toggleAddToReport} /> } </div>, ); }; export default compose( DragSource(DragDropItemTypes.CONTAINER, orderSource, orderDragCollect), DropTarget(DragDropItemTypes.CONTAINER, orderTarget, orderDropCollect), )(ContainerRow);
ComPlat/chemotion_ELN
app/packs/src/components/SampleDetailsContainersDnd.js
JavaScript
agpl-3.0
2,510
var round = function(number, increment, offset) { return Math.ceil((number - offset) / increment) * increment + offset; }; Partup.client.chatmessages = { groupByDelay: function(messages, options) { var delay = options.seconds ? options.seconds * 1000 : 1000; var outputArray = []; messages.forEach(function(item, index) { var outputLastIndex = outputArray.length - 1; var lastCreatedAt; if (outputArray[outputLastIndex]) { lastCreatedAt = new Date(outputArray[outputLastIndex].messages[outputArray[outputLastIndex].messages.length - 1].created_at).getTime(); } var currentCreatedAt = new Date(item.created_at).getTime(); if (outputArray[outputLastIndex] && lastCreatedAt && (currentCreatedAt - lastCreatedAt) < delay) { outputArray[outputLastIndex].messages.push(item); } else { outputArray.push({ messages: [item] }); } }); return outputArray.reverse(); }, groupByCreationDay: function(messages) { var outputArray = []; messages.forEach(function(item, index) { var outputLastIndex = outputArray.length - 1; if (outputArray[outputLastIndex] && outputArray[outputLastIndex].day === new Date(item.created_at).setHours(0, 0, 0, 0, 0)) { outputArray[outputLastIndex].messages.push(item); } else { outputArray.push({ day: new Date(item.created_at).setHours(0, 0, 0, 0, 0), messages: [item] }); } }); return outputArray.reverse(); }, groupByCreatorId: function(messages) { var outputArray = []; messages.forEach(function(item, index) { var outputLastIndex = outputArray.length - 1; if (outputArray[outputLastIndex] && outputArray[outputLastIndex].creator_id === item.creator_id) { outputArray[outputLastIndex].messages.push(item); } else { outputArray.push({ creator_id: item.creator_id, messages: [item] }); } }); return outputArray.reverse(); }, groupByChat: function(messages) { var outputObject = {}; messages.forEach(function(item, index) { if (outputObject[item.chat_id] && outputObject[item.chat_id].chat_id === item.chat_id) { outputObject[item.chat_id].messages.push(item); } else { outputObject[item.chat_id] = { chat_id: item.chat_id, messages: [item] }; } }); var outputArray = _.values(outputObject); return outputArray; } };
part-up/part-up
app/packages/partup-client-base/client/chatmessages.js
JavaScript
agpl-3.0
2,893
define(function (require) { 'use strict'; var Vector2 = require('vector2-node'); /** * Returns a new unit vector in the direction specified by the angle */ Vector2.fromAngle = function(angle) { return new Vector2(1, 0).rotate(angle); }; Vector2.prototype.toString = function(precision) { if (precision === undefined) precision = 4; return '(' + this.x.toFixed(precision) + ', ' + this.y.toFixed(precision) + ')'; }; /** * Rounds each component to the nearest integer. */ Vector2.prototype.round = function() { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; }; return Vector2; });
Connexions/simulations
common/math/vector2.js
JavaScript
agpl-3.0
731
const ERR = require('async-stacktrace'); const _ = require('lodash'); const async = require('async'); const sqldb = require('../prairielib/lib/sql-db'); module.exports = { pages(chosenPage, count, pageSize) { let lastPage = Math.ceil(count / pageSize); if (lastPage === 0) lastPage = 1; let currPage = Number(chosenPage); if (!_.isInteger(currPage)) currPage = 1; let prevPage = currPage - 1; let nextPage = currPage + 1; currPage = Math.max(1, Math.min(lastPage, currPage)); prevPage = Math.max(1, Math.min(lastPage, prevPage)); nextPage = Math.max(1, Math.min(lastPage, nextPage)); return { currPage, prevPage, nextPage, lastPage }; }, /** * Utility function to facilitate extremely large queries whose results * cannot fit in memory all at once. The given query must accept an "offset" * param that will be used to paginate the query. The "receiveRow" callback * will be called once for each row in the result set. The "done" callback * is called either if an error has occurred or when all rows have been * delivered. */ paginateQuery(sql, params, receiveRow, done) { const _params = Object.assign({}, params); let offset = 0; async.doWhilst( (callback) => { _params.offset = offset; sqldb.query(sql, _params, (err, result) => { if (ERR(err, callback)) return; async.eachSeries(result.rows, receiveRow, (err) => { if (ERR(err, callback)) return; offset += result.rows.length; callback(null, result.rows.length); }); }); }, (count, callback) => { callback(null, count > 0); }, (err) => { if (ERR(err, done)) return; done(null); } ); }, };
PrairieLearn/PrairieLearn
lib/paginate.js
JavaScript
agpl-3.0
1,786
define("imcms-templates-tab-builder", [ "imcms-bem-builder", "imcms-components-builder", "imcms-templates-rest-api", "imcms-document-types", "imcms-i18n-texts", "imcms-page-info-tab" ], function (BEM, components, templatesRestApi, docTypes, texts, PageInfoTab) { texts = texts.pageInfo.appearance; const tabData = {}; const TemplatesTab = function (name, docType) { PageInfoTab.apply(this, arguments); }; TemplatesTab.prototype = Object.create(PageInfoTab.prototype); TemplatesTab.prototype.tabElementsFactory = () => { const $templateSelectContainer = components.selects.selectContainer("<div>", { name: "template", text: texts.template }), $templateSelect = $templateSelectContainer.getSelect(), $defaultChildTemplateSelectContainer = components.selects.selectContainer("<div>", { name: "childTemplate", text: texts.defaultChildTemplate }), $defaultChildTemplateSelect = $defaultChildTemplateSelectContainer.getSelect(); tabData.$templateSelect = $templateSelect; tabData.$defaultChildTemplateSelect = $defaultChildTemplateSelect; templatesRestApi.read(null) .done(templates => { const templatesDataMapped = templates.map(template => ({ text: template.name, "data-value": template.name })); components.selects.addOptionsToSelect(templatesDataMapped, $templateSelect); components.selects.addOptionsToSelect(templatesDataMapped, $defaultChildTemplateSelect); }); return [ $templateSelectContainer, $defaultChildTemplateSelectContainer ]; }; TemplatesTab.prototype.fillTabDataFromDocument = document => { if (document.template) { tabData.$templateSelect.selectValue(document.template.templateName); tabData.$defaultChildTemplateSelect.selectValue(document.template.childrenTemplateName); } }; TemplatesTab.prototype.saveData = function (documentDTO) { if (!this.isDocumentTypeSupported(documentDTO.type)) { return documentDTO; } documentDTO.template.templateName = tabData.$templateSelect.getSelectedValue(); documentDTO.template.childrenTemplateName = tabData.$defaultChildTemplateSelect.getSelectedValue(); return documentDTO; }; TemplatesTab.prototype.clearTabData = () => { tabData.$templateSelect.selectFirst(); tabData.$defaultChildTemplateSelect.selectFirst(); }; return new TemplatesTab(texts.name, docTypes.TEXT); } );
imCodePartnerAB/imcms
src/main/webapp/imcms/js/builders/components/page_info_tabs/imcms-templates-tab-builder.js
JavaScript
agpl-3.0
2,976
/* This file is part of ContentManager. ContentManager 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. ContentManager 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 ContentManager. If not, see <http://www.gnu.org/licenses/>. */ var messageHandler = { displayInfoMessage : function (message) { var messageJson = {messageClass : "alert-info", message : message} $("#app-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#app-message").html(''); },1500) }, displayLoadMessage : function (message) { var messageJson = {message : message} $("#app-message").html(Mustache.render($('#message-template').html() ,messageJson)); }, displayErrorMessage : function (message) { var messageJson = {messageClass : "alert-danger", message : message} $("#app-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#app-message").html(''); },3000) }, resetMessage : function(){ $("#app-message").html(Mustache.render($('#message-template').html() ,{})); }, showJiveErrorMessage : function(message){ osapi.jive.core.container.sendNotification( {'message':message, 'severity' : 'error'} ); }, getCurrentMessage : function(){ return $("#app-message").text() }, displayTagErrorMessage : function (message) { var messageJson = {messageClass : "alert-danger", message : message} $("#tag-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#tag-message").html(''); },1500) }, displayCategoryErrorMessage : function(message){ var messageJson = {messageClass : "alert-danger", message : message} $("#category-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#category-message").html(''); },1500) } }
siddharthadeshpande89/jive-content-manager
apps/content_manager/public/javascripts/helpers/messageViewHandler.js
JavaScript
agpl-3.0
2,511
var origShow = jQuery.fn.show, origHide = jQuery.fn.hide; jQuery.fn.show = function() { $(this).removeClass("hidden"); return origShow.apply(this, arguments); }; jQuery.fn.hide = function() { $(this).addClass("hidden"); return origHide.apply(this, arguments); }; $.ajaxSetup({ cache: false }); function onBlur() { document.body.className = 'blurred'; } function onFocus() { document.body.className = 'focused'; } function getNotification(type) { sendRequest({type: type}, "notifications", "get", function(res) { $("#notification-dropdown").html(function() { var str = ""; if (type !== "messages") { if (res.result !== null && typeof res.result !== "undefined" && res.result.length > 0) { for (x in res.result) str += tmpl("notification-" + type, res.result[x]); } else str = tmpl("notification-empty", {}); return str; } else if (type === "messages") { if (res.conversations !== null && typeof res.conversations !== "undefined" && res.conversations.length > 0) { $.getJSON(siteurl + "style/" + design + "/img/emoticons/emoticons.json", function(data) { smileys = new Array(); for (x in data) smileys[data[x]] = '<img src="' + siteurl + 'style/' + design + '/img/emoticons/' + data[x] + '.png" class="message-smiley" data-key="' + data[x] + '">'; for (con in res.conversations) { var c = res.conversations[con], i = 0, image = null; if (c.users !== null && typeof c.users === "string") { us = c.users.split(","), userstring = ""; for (user in us) { if (i === 2) { userstring += ", +" + (us.length - 2); break; } var tmp = us[user].split("|"); userstring += ", " + tmp[0]; i++; } userstring = userstring.substr(2); } else if (c.users !== null & typeof c.users === "object") { // there is only one user userstring = c.users.name; image = c.users.pimg; } else userstring = "None"; c.message = c.message.substr(0, 35); for (x in smileys) c.message = replaceAll('[:' + x + ':]', smileys[x], c.message); str += tmpl("notification-messages", {name: userstring, message: c.message, conversation: c.conversation, sendername: c.sendername, time: c.time, image: checkImage(image, "users", "cr_")}); } $("#notification-dropdown").html(str); return; }); } else return tmpl("notification-empty", {}); } }).removeClass("notification-messages notification-friends notification-general").addClass("notification-" + type).show(); }); } function sendRequest(requestData, module, action, callback) { if (typeof requestData !== "undefined") { return $.ajax({ url: convertUrl({module: module, action: action}), dataType: "json", data: requestData, type: 'POST', success: function(data) { if (typeof data.session !== "undefined" && data.session === 0) { alert("Your session is timed out! Please login again!"); location.href = convertUrl({module: "start"}); } else if (data.status == false) { if (typeof data.msg == "undefined") data.msg = "Error"; bootbox.alert(data.msg); } else if (typeof callback == 'function') { callback(data); refreshTime(); } } }); } return null; } function convertUrl(data) { if (modrewrite) { var str = siteurl + data.module; if (typeof data.action !== "undefined" && data.action !== null) str += "/" + data.action; if (typeof data.x !== "undefined" && data.x !== null) str += "/" + data.x; if (typeof data.y !== "undefined" && data.y !== null) str += "/" + data.y; return str; } else { var str = siteurl + "index.php?m=" + data.module; if (typeof data.action !== "undefined" && data.x !== null) str += "&action=" + data.action; if (typeof data.x !== "undefined" && data.x !== null) str += "&x=" + data.y; if (typeof data.y !== "undefined" && data.x !== null) str += "&y=" + data.y; return str; } } function checkImage(filename, type, prefix) { prefix = (typeof prefix === "undefined") ? "" : prefix; if (filename === null || typeof filename === "undefined" || filename.length === 0) return siteurl + 'style/' + design + '/img/placeholders/noimg-' + type + '.png'; return prefix + filename; } function getErrorMessage(tplname) { return tmpl(tplname, {}); } function like(ref_name, ref_id, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "like", callback); } function dislike(ref_name, ref_id, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "dislike", callback); } function unlike(ref_name, ref_id, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "unlike", callback); } function comment(ref_name, ref_id, content, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id, "content": content}, "comments", "add", callback); } function deleteComment(comment_id) { bootbox.confirm("Are You sure you want to delete this comment?", function(r) { if (r) { sendRequest({"comment_id": comment_id}, "comments", "remove", function() { $("#comment-" + comment_id).remove(); }); } }); } function getLikes(refname, refid, dislike, title) { sendRequest({"ref_name": refname, "ref_id": refid, "dislike": dislike}, "likes", "get", function(res) { if (typeof res.likes !== "undefined" && res.likes.length > 0) { bootbox.dialog({ message: function() { var msg = ""; for (x in res.likes) msg += tmpl("like-list", res.likes[x]); return '<div class="likesmodalbox">' + msg + '</div>'; }, title: title, buttons: { main: { label: "Ok", className: "btn-primary" } }, className: "likelistmodal" }); } }); } function refreshTime() { $(".timestring").each(function() { var el = $(this); el.replaceWith(function() { return convertDate(el.data("source")); }); }); $(".tooltip").remove(); $(".tooltip-trigger").tooltip({ container: 'body' }); } function convertDate(timestring) { if (typeof timestring == "undefined" || timestring === "" || timestring === null) return "NaN"; var now = new Date(); var then = new Date(timestring.replace(/-/g, '/')); var r = ""; then.setMinutes(then.getMinutes() + now.getTimezoneOffset() * (-1)); var since = Math.round((now.getTime() - then.getTime()) / 1000); var chunks = [ [22896000, 'year'], [2592000, 'month'], [604800, 'week'], [86400, 'day'], [3600, 'hour'], [60, 'minute'] ]; if (since < 60) r = "just now"; else { var count; for (i = 0, j = chunks.length; i < j; i++) { seconds = chunks[i][0]; name = chunks[i][1]; count = Math.floor(since / seconds); if (count !== 0) break; } r = ((count === 1) ? '1 ' + name : count + " " + name + "s") + " ago"; } return '<span class="tooltip-trigger timestring" data-source="' + timestring + '" data-title="' + then.toLocaleString() + '">' + r + '</span>'; } function escapeRegExp(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } function replaceAll(find, replace, str) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } $(document).ready(function() { if (/*@cc_on!@*/false) { // check for Internet Explorer document.onfocusin = onFocus; document.onfocusout = onBlur; } else { window.onfocus = onFocus; window.onblur = onBlur; } $(".sidebar").css("minHeight", window.innerHeight - 101); $('input.filefakeinput').change(function() { $($(this).data("rel")).val($(this).val()); }); $('.dropdown-menu').on('click', function(e) { if ($(this).hasClass('dropdown-checkbox-menu')) { e.stopPropagation(); } }); $('.btn[data-loading-text]').click(function() { $(this).button('loading'); }); $("a[href=\"#\"],a[href=\"\"]").click(function(e) { e.preventDefault(); }); $("#mobile-slide-nav > .mobile-menu").html($(".main-menu > .nav").html()); $(document).on("click", "#menu-trigger", function() { if (login) { if ($("body").hasClass("menu-active")) $("body").removeClass("menu-active"); else $("body").addClass("menu-active"); } else location.href = convertUrl({module: "start"}); }).on("mouseenter", ".notification-general-item:not(.read)", function() { var el = $(this); sendRequest({id: el.data("id")}, "notifications", "markRead", function() { el.addClass("read"); el.find(".label-new").fadeOut("slow"); }); }); if (login) { //Load unread messages badge sendRequest({type: "messages"}, "notifications", "get", function(res) { if (typeof res.conversations !== "undefined" && res.conversations.length > 0) { $(".main-menu-item-messages > a > .badge").html(res.conversations.length); $(".notification-link-messages").addClass("active"); } else $(".notification-link-messages").removeClass("active"); }); sendRequest({type: "friends"}, "notifications", "get", function(res) { if (typeof res.result !== "undefined" && res.result !== null && res.result.length > 0) { $(".main-menu-item-friends > a > .badge").html(res.result.length); $(".notification-link-friends").addClass("active"); } else $(".notification-link-friends").removeClass("active"); }); sendRequest({type: "general"}, "notifications", "get", function(res) { if (res.new > 0) $(".notification-link-general").addClass("active"); else $(".notification-link-general").removeClass("active"); }); } $(document).on("click", "a.close", function(e) { e.stopPropagation(); }); $(document).on("submit", "form.ajaxform", function(e) { e.preventDefault(); var form = $(this); form.find("input[type='submit'],button[type='submit']").button('loading'); if (form.prop("ajaxform-send") === true) return; if (form.attr("enctype") === "multipart/form-data") { var name = "ajaxformframe" + Math.random(); var frame = $("<iframe/>", {"name": name, class: "hidden"}).appendTo(form); form.attr("target", name).prop("ajaxform-send", true).submit(); frame.on("load", function() { form.find("input[type='submit'],button[type='submit']").button('reset'); if (form.find(".ajaxform-callback").length > 0) { console.log(frame.contents().find('body').html()); var callback = window[form.find(".ajaxform-callback").val()]; if (typeof callback === "function") callback(jQuery.parseJSON(frame.contents().find('body').html())); } }); } else { $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), dataType: "json" }).done(function(data) { form.find("input[type='submit'],button[type='submit']").button('reset'); if (form.find(".ajaxform-callback").length > 0) { var callback = window[form.find(".ajaxform-callback").val()]; if (data.status === false) { bootbox.alert(data.msg); } else if (typeof callback === "function") callback(data); } }); } }).on("click", function(e) { if ($(e.target).attr("id") !== "notification-dropdown" && $("#notification-dropdown").length > 0) $("#notification-dropdown").hide(); }); $("#infoModal").on('show.bs.modal', function(e) { $("#infoModal").find(".modal-title").html($(e.relatedTarget).data("title")); if (typeof $(e.relatedTarget).data("href") !== "undefined") $("#infoModal").find(".modal-body").html('<iframe src="' + $(e.relatedTarget).data("href") + '" style="border:0;width:100%"></iframe>').css("padding", 10); }); $("*[data-moveto]").each(function() { $(this).appendTo($(this).data("moveto")).removeAttr("data-moveto"); }); });
kolplex/cunity
style/CunityRefreshed/javascript/cunity-core.js
JavaScript
agpl-3.0
14,280
/* Code for Life Copyright (C) 2015, Ocado Innovation Limited This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ADDITIONAL TERMS – Section 7 GNU General Public Licence This licence does not grant any right, title or interest in any “Ocado” logos, trade names or the trademark “Ocado” or any other trademarks or domain names owned by Ocado Innovation Limited or the Ocado group of companies or any other distinctive brand features of “Ocado” as may be secured from time to time. You must not distribute any modification of this program using the trademark “Ocado” or claim any affiliation or association with Ocado or its employees. You are not authorised to use the name Ocado (or any of its trade names) or the names of any author or contributor in advertising or for publicity purposes pertaining to the distribution of this program, without the prior written authorisation of Ocado. Any propagation, distribution or conveyance of this program must include this copyright notice and these terms. You must not misrepresent the origins of this program; modified versions of the program must be marked as such and not identified as the original program. */ 'use strict'; var ocargo = ocargo || {}; var Blockly = Blockly || {}; function initCustomBlocks() { initCustomBlocksDescription(); initCustomBlocksPython(); } function initCustomBlocksDescription() { Blockly.Blocks['start'] = { // Beginning block - identifies the start of the program init: function() { ocargo.blocklyControl.numStartBlocks++; this.setColour(50); this.appendDummyInput() .appendField('Start') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + CHARACTER_EN_FACE_URL, ocargo.BlocklyControl.BLOCK_CHARACTER_HEIGHT, ocargo.BlocklyControl.BLOCK_CHARACTER_WIDTH)); this.setNextStatement(true, 'Action'); this.setTooltip('The beginning of the program'); this.setDeletable(false); } }; /*****************/ /* Action Blocks */ /*****************/ Blockly.Blocks['move_forwards'] = { // Block for moving forward init: function() { this.setColour(160); this.appendDummyInput() .appendField('move forwards') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/forward.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Move the van forwards'); } }; Blockly.Blocks['turn_left'] = { // Block for turning left init: function() { this.setColour(160); this.appendDummyInput() .appendField('turn left') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 38, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/left.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Turn the van left'); } }; Blockly.Blocks['turn_right'] = { // Block for turning right init: function() { this.setColour(160); this.appendDummyInput() .appendField('turn right') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 29, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/right.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Turn the van right'); } }; Blockly.Blocks['turn_around'] = { // Block for turning around init: function() { this.setColour(160); this.appendDummyInput() .appendField('turn around') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 12, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/turn_around.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Turn the van around'); } }; Blockly.Blocks['wait'] = { // Block for not moving the van for a time init: function() { this.setColour(160); this.appendDummyInput() .appendField('wait') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 60, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/wait.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Keep the van stationary'); } }; Blockly.Blocks['deliver'] = { // Block for delivering (only on levels with multiple destinations) init: function() { this.setColour(160); this.appendDummyInput() .appendField('deliver') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 43, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/deliver.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Deliver the goods from the van'); } }; Blockly.Blocks['puff_up'] = { // Block for puffing up the van init: function() { this.setColour(330); this.appendDummyInput() .appendField('puff up') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 43, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'EventAction'); this.setNextStatement(false); this.setTooltip('Puff up the van to scare away the cows'); } }; Blockly.Blocks['sound_horn'] = { // Block for puffing up the van init: function() { this.setColour(330); this.appendDummyInput() .appendField('sound horn') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 43, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'EventAction'); this.setNextStatement(false); this.setTooltip('Sound the horn to scare away the cows'); } }; /*****************/ /* Conditions */ /*****************/ Blockly.Blocks['road_exists'] = { init: function() { var BOOLEANS = [['road exists forward', 'FORWARD'], ['road exists left', 'LEFT'], ['road exists right', 'RIGHT']]; this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField(new Blockly.FieldDropdown(BOOLEANS), 'CHOICE') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; Blockly.Blocks['traffic_light'] = { init: function() { var BOOLEANS = [['traffic light red', ocargo.TrafficLight.RED], ['traffic light green', ocargo.TrafficLight.GREEN]]; this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField(new Blockly.FieldDropdown(BOOLEANS), 'CHOICE') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; Blockly.Blocks['dead_end'] = { init: function() { this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField('is dead end') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; Blockly.Blocks['at_destination'] = { init: function() { this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField('at destination') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; /****************/ /* Procedures */ /****************/ Blockly.Blocks['call_proc'] = { // Block for calling a defined procedure init: function() { var name = ''; this.setColour(260); this.appendDummyInput() .appendField('Call') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 7, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldTextInput(name),'NAME'); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Call'); } }; Blockly.Blocks['declare_proc'] = { // Block for declaring a procedure init: function() { var name = ''; this.setColour(260); this.appendDummyInput() .appendField('Define') .appendField(new Blockly.FieldTextInput(name),'NAME'); this.appendStatementInput('DO') .setCheck('Action') .appendField('Do'); this.setTooltip('Declares the procedure'); this.statementConnection_ = null; } }; /****************/ /* Events */ /****************/ Blockly.Blocks['declare_event'] = { // Block for declaring an event handler init: function() { this.setColour(260); var dropdown = new Blockly.FieldDropdown([['white', ocargo.Cow.WHITE], ['brown', ocargo.Cow.BROWN]], function(option) { var imageUrl = ocargo.Drawing.imageDir + ocargo.Drawing.cowUrl(option); this.sourceBlock_.getField('IMAGE').setValue(imageUrl); }); this.appendDummyInput('Event') .appendField('On ') .appendField(dropdown, 'TYPE') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + ocargo.Drawing.whiteCowUrl, ocargo.BlocklyControl.COW_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT), 'IMAGE'); this.getField('IMAGE').EDITABLE = true; //saves the image path as well in the XML this.appendStatementInput('DO') .setCheck('EventAction') .appendField('Do'); this.setTooltip('Declares the event handler'); this.statementConnection_ = null; }, }; /*******************/ /* Control Flows */ /*******************/ Blockly.Blocks['controls_repeat_while'] = { // Block for repeat while init: function() { this.setColour(120); this.appendValueInput("condition") .setCheck("Boolean") .appendField("repeat while"); this.appendStatementInput("body") .setCheck("Action") .appendField("do"); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('While a value is true, do some statements'); } }; Blockly.Blocks['controls_repeat_until'] = { // Block for repeat until init: function() { this.setColour(120); this.appendValueInput("condition") .setCheck("Boolean") .appendField("repeat until"); this.appendStatementInput("body") .setCheck("Action") .appendField("do"); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Until a value is true, do some statements'); } }; // Set text colour to red var textBlock = Blockly.Blocks['text']; var originalTextInit = textBlock.init; textBlock.init = function() { originalTextInit.call(this); this.setColour(260); }; //Customise controls_repeat block to not allow more than a sensible number of repetitions var controlsRepeatBlock = Blockly.Blocks['controls_repeat']; var originalInit = controlsRepeatBlock.init; controlsRepeatBlock.init = function () { originalInit.call(this); this.setPreviousStatement(!0, 'Action'); this.setNextStatement(!0, 'Action'); this.inputList[1].setCheck('Action'); //Disallow event action blocks to be in body var input = this.inputList[0]; var field = input.fieldRow[1]; field.changeHandler_ = function(text) { var n = Blockly.FieldTextInput.numberValidator(text); if (n) { n = String(Math.min(Math.max(0, Math.floor(n)), 20)); } return n; }; }; // Make 'not' taller var notBlock = Blockly.Blocks['logic_negate']; var originalNotInit = notBlock.init; notBlock.init = function () { originalNotInit.call(this); this.inputList[0].appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); }; } function initCustomBlocksPython() { Blockly.Python['start'] = function(block) { return ''; }; Blockly.Python['move_forwards'] = function(block) { return 'v.move_forwards()\n'; }; Blockly.Python['turn_left'] = function(block) { return 'v.turn_left()\n'; }; Blockly.Python['turn_right'] = function(block) { return 'v.turn_right()\n'; }; Blockly.Python['turn_around'] = function(block) { return 'v.turn_around()\n'; }; Blockly.Python['wait'] = function(block) { return 'v.wait()\n'; }; Blockly.Python['deliver'] = function(block) { return 'v.deliver()\n'; }; Blockly.Python['road_exists'] = function(block) { if(block.inputList[0].fieldRow[1].value_ === 'FORWARD'){ var python = "v.is_road('FORWARD')"; }else if(block.inputList[0].fieldRow[1].value_ === 'LEFT'){ var python = "v.is_road('LEFT')"; }else{ var python = "v.is_road('RIGHT')"; } return [python, Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to }; Blockly.Python['traffic_light'] = function(block) { var python; if(block.inputList[0].fieldRow[1].value_ === ocargo.TrafficLight.RED){ python = "v.at_traffic_light('RED')"; }else{ python = "v.at_traffic_light('GREEN')"; } return [python, Blockly.Python.ORDER_NONE]; //TODO: figure out what this ordering relates to }; Blockly.Python['dead_end'] = function(block) { return ['v.at_dead_end()', Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to }; Blockly.Python['cow_crossing'] = function(block) { return ['v.cow_crossing()', Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to }; Blockly.Python['at_destination'] = function(block) { return ['v.at_destination()', Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to; }; Blockly.Python['call_proc'] = function(block) { return block.inputList[0].fieldRow[2].text_ + '()\n'; }; Blockly.Python['declare_proc'] = function(block) { var branch = Blockly.Python.statementToCode(block, 'DO'); return 'def ' + block.inputList[0].fieldRow[1].text_ + '():\n' + branch; // TODO: get code out of sub-blocks (there's a Blockly function for it) }; Blockly.Python['declare_event'] = function(block) { // TODO support events in python throw 'events not supported in python'; }; Blockly.Python['controls_repeat_while'] = function(block) { var condition = Blockly.Python.valueToCode(block, 'condition', Blockly.Python.ORDER_ATOMIC); var subBlock = Blockly.Python.statementToCode(block, 'body'); var code = 'while ' + condition + ':\n' + subBlock; return code; }; Blockly.Python['controls_repeat_until'] = function(block) { var condition = Blockly.Python.valueToCode(block, 'condition', Blockly.Python.ORDER_ATOMIC); var subBlock = Blockly.Python.statementToCode(block, 'body'); var code = 'while not ' + condition + ':\n' + subBlock; return code; }; }
mikebryant/rapid-router
game/static/game/js/blocklyCustomBlocks.js
JavaScript
agpl-3.0
20,655
/** * Copyright (C) 2016 Jorge Campos Serrano. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ Template.notificationsWidget.helpers({ notifications: function() { return Notifications.find({userId: Meteor.userId(), read: false}, {limit: 4}); }, notificationCount: function(){ return Notifications.find({userId: Meteor.userId(), read: false}).count(); } });
jcamposs/coderoom
client/templates/notifications/notifications_widget.js
JavaScript
agpl-3.0
1,772
/** * This file is part of RLO-Plan. * * Copyright 2009, 2010 Tillmann Karras, Josua Grawitter * * RLO-Plan is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RLO-Plan is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with RLO-Plan. If not, see <http://www.gnu.org/licenses/>. */ var column_titles = ['Uhrzeit', 'Klasse', 'Fach', 'Dauer', 'Vertretung', 'Änderung', 'Alter Raum', 'Neuer Raum']; var column_names = ['time', 'course', 'subject', 'duration', 'sub', 'change', 'oldroom', 'newroom']; var column_widths = ['40px', '40px', '45px', '25px', '150px', '245px', '40px', '40px']; var column_maxLengths = [ 5, 5, 6, 3, 30, 40, 5, 5]; var day_names = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag']; var relative_day_names = ['heute', 'morgen', 'übermorgen']; // array index corresponds to distance from today function modify_entry(button) { hide_buttons(button); show_buttons(button.nextSibling.nextSibling); var row = button.parentNode.parentNode; for (var i = 0; i < row.childNodes.length - 1; i++) { var cell = row.childNodes[i]; make_textbox(cell, i); make_backup(cell, cell.lastChild.value); } } function remove_row(row) { if (row.parentNode.childNodes.length == 2) { var teacher = row.parentNode.parentNode; var day = teacher.parentNode; if (day.childNodes.length == 4) { remove(day); } else { remove(teacher); } } else { remove(row); } } function delete_entry(button) { hide_buttons(button.previousSibling); var row = button.parentNode.parentNode; var msg = 'action=delete&id=' + row.id.substr(5); // remove 'entry' from 'entry123' var status = newStatus('Wird gelöscht...', row.lastChild); send_msg(msg, function(xhr) { if (xhr.status == 200) { remove_row(row); } else { show_buttons(button.previousSibling); remove_status(status, xhr); } }); } function save_entry(button) { var row = button.parentNode.parentNode; var teacher = row.parentNode.parentNode; var day = teacher.parentNode; var date = parse_date(day.firstChild.textContent); if (date === null) { alert('Bitte berichtigen Sie erst das Datum.'); return; } date = format_date_server(date); var msg = '&date=' + date + '&teacher=' + teacher.firstChild.textContent; var contentHasChanged = false; for (var i = 0; i < row.childNodes.length - 1; i++) { var cell = row.childNodes[i]; var new_value = cell.firstChild.value; if (i == 0) { new_value = parse_time(new_value); if (new_value === null) { alert('Die Uhrzeit ist fehlerhaft.'); return; } hide_buttons(button); } if (new_value != cell.lastChild.textContent) { cell.textContent = new_value; msg += '&' + column_names[i] + '=' + new_value; contentHasChanged = true; } else { cell.textContent = cell.lastChild.textContent; } } if (contentHasChanged) { msg = 'action=update&id=' + row.id.substr(5) + msg; var status = newStatus('Wird gespeichert...', row.lastChild); send_msg(msg, function(xhr) { show_buttons(button.previousSibling.previousSibling); if (xhr.status != 200) { button.previousSibling.previousSibling.click(); } remove_status(status, xhr); }); } else { show_buttons(button.previousSibling.previousSibling); } } function save_new_entry(button) { var row = button.parentNode.parentNode; var teacher = row.parentNode.parentNode; var day = teacher.parentNode; var date = parse_date(day.firstChild.textContent); if (date === null) { alert('Bitte berichtigen Sie erst das Datum.'); return; } date = format_date_server(date); var msg = '&date=' + date + '&teacher=' + teacher.firstChild.textContent; for (var i = 0; i < row.childNodes.length - 1; i++) { var cell = row.childNodes[i]; var new_value = cell.firstChild.value; if (i == 0) { new_value = parse_time(new_value); if (new_value === null) { alert('Die Uhrzeit ist fehlerhaft.'); return; } hide_buttons(button); } cell.textContent = new_value; msg += '&' + column_names[i] + '=' + cell.textContent; } msg = 'action=add' + msg; var status = newStatus('Wird hinzugefügt...', row.lastChild); send_msg(msg, function(xhr) { remove_status(status, xhr); if (xhr.status == 200) { row.id = 'entry' + xhr.responseText; } else { row.lastChild.firstChild.onclick(); } // TODO: is this ok here? show_buttons(button.previousSibling.previousSibling); button.onclick = function() { save_entry(button); } button.nextSibling.innerHTML = 'Abbrechen'; button.nextSibling.onclick = function() { cancel_editing(button.nextSibling); } }); } function delete_new_entry(button) { remove_row(button.parentNode.parentNode); } function add_new_entry(button) { var row = newElement('tr'); // data cells: for (var i = 0; i < column_widths.length; i++) { var cell = newCell(''); make_textbox(cell, i); row.appendChild(cell); } // button cell: var button_cell = newElement('td'); var mod_button = newButton('Bearbeiten', modify_entry); mod_button.style.display = 'none'; button_cell.appendChild(mod_button); var del_button = newButton('Löschen', delete_entry); del_button.style.display = 'none'; button_cell.appendChild(del_button); var save_button = newButton('Speichern', save_new_entry); button_cell.appendChild(save_button); var cancel_button = newButton('Löschen', delete_new_entry); button_cell.appendChild(cancel_button); row.appendChild(button_cell); button.previousSibling.appendChild(row); row.firstChild.firstChild.focus(); } function add_teacher(button) { var day = button.parentNode; var teacher = newTeacher('Neuer Lehrer', []); day.insertBefore(teacher, day.lastChild); teacher.childNodes[1].value = ''; teacher.firstChild.onclick(); } function parse_time(time) { var matches = time.match(/^(\d\d?).(\d\d?)$/); if (matches !== null) { for (var i = 1; i <= 2; i++) { if (matches[i].length == 1) { matches[i] = '0' + matches[i]; } } return matches[1] + ':' + matches[2]; } return null; } function parse_date(date) { var matches = date.match(/(\d\d?).(\d\d?).((\d\d)?\d\d)$/); if (matches !== null) { var year = matches[3]; if (year.length == 2) { year = '20' + year; } return new Date(year, matches[2] - 1, matches[1], 0, 0, 0, 0); } var lower_date = date.toLowerCase(); for (var i = 0; i < relative_day_names.length; i++) { if (lower_date == relative_day_names[i]) { var result = new Date(); result.setDate(result.getDate() + i); return result; } } if (date.length <= 10) { // length of 'Donnerstag' for (var i = 0; i < day_names.length; i++) { if (lower_date == day_names[i].substr(0, lower_date.length).toLowerCase()) { var result = new Date(); var today = result.getDay(); if (i < today) { i += 7; } result.setDate(result.getDate() + i - today); return result; } } } return null; } // DayOfWeek, DD.MM.YYYY function format_date_client(d) { var day = d.getDate() + ''; if (day.length == 1) { day = '0' + day; } var month = (d.getMonth() + 1) + ''; if (month.length == 1) { month = '0' + month; } return day_names[d.getDay()] + ', ' + day + '.' + month + '.' + d.getFullYear(); } // YYYY-MM-DD function format_date_server(d) { return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate(); } function get_default_date() { var d = new Date(); var last_day = document.getElementById('ovp').lastChild.previousSibling; if (last_day) { var last_date = parse_date(last_day.firstChild.textContent); if (last_date && last_date.getDate() >= d.getDate()) { d = last_date; d.setDate(d.getDate() + 1); } } if (d.getDay() == 0) { // skip Sunday d.setDate(d.getDate() + 1); } else if (d.getDay() == 6) { // skip Saturday d.setDate(d.getDate() + 2); } return format_date_client(d); } function add_day(button) { var ovp = button.parentNode; var date = get_default_date(); var day = newDay(date, []); ovp.insertBefore(day, ovp.lastChild); day.firstChild.onclick(); } // 'id' is from the database function newEntry(id, cols) { var row = newElement('tr'); row.id = 'entry' + id; // data cells: for (i in cols) { row.appendChild(newCell(cols[i])); } // button cell: var button_cell = newElement('td'); var mod_button = newButton('Bearbeiten', modify_entry); button_cell.appendChild(mod_button); var del_button = newButton('Löschen', delete_entry); button_cell.appendChild(del_button); var save_button = newButton('Speichern', save_entry); save_button.style.display = 'none'; button_cell.appendChild(save_button); var cancel_button = newButton('Abbrechen', cancel_editing); cancel_button.style.display = 'none'; button_cell.appendChild(cancel_button); row.appendChild(button_cell); return row; } function save_teacher(teacher) { // subfunction needed since otherwise "status" would reference one variable only function update_entry(msg, parent) { var status = newStatus('Wird aktualisiert...', parent); send_msg(msg, function(xhr) { remove_status(status, xhr); }); } var date = parse_date(teacher.parentNode.firstChild.textContent); if (date === null) { alert('Bitte berichtigen Sie erst das Datum.'); return; } date = format_date_server(date); var rows = teacher.childNodes[2].childNodes; for (var i = 1; i < rows.length; i++) { var row = rows[i]; if (row.id) { var cells = row.childNodes; var msg = 'action=update&id=' + row.id.substr(5) + '&date=' + date + '&teacher=' + teacher.firstChild.textContent; for (var j = 0; j < cells.length - 1; j++) { msg += '&' + column_names[j] + '=' + cells[j].textContent; } update_entry(msg, row.lastChild); } } } function newTeacher(name, entries) { var teacher = newElement('section'); var header = newElement('h3'); header.style.display = 'table'; header.innerHTML = name; header.onclick = function() { header.style.display = 'none'; var textbox = header.nextSibling; textbox.style.display = 'block'; textbox.focus(); textbox.select(); } teacher.appendChild(header); var textbox = newElement('input'); textbox.type = 'text'; textbox.style.display = 'none'; textbox.value = name; textbox['last_key'] = 0; textbox.onkeydown = function(e) { var key; if (window.event) { key = event.keyCode; } else if (e) { key = e.which; } if (key == 9 && textbox['last_key'] == 0) { textbox['create_entry_on_first_blur'] = true; } textbox['last_key'] = key - 9; return true; } textbox.onkeyup = function() { textbox['last_key'] = 0; } textbox.onblur = function() { textbox.style.display = 'none'; var header = textbox.previousSibling; var table = textbox.nextSibling; if (textbox.value != header.textContent && textbox.value != '') { header.textContent = textbox.value; if (table.childNodes.length > 1) { save_teacher(textbox.parentNode); } } if (table.childNodes.length == 1 && textbox['create_entry_on_first_blur']) { textbox.parentNode.lastChild.onclick(); } header.style.display = 'table'; } teacher.appendChild(textbox); var table = newElement('table'); table.setAttribute('class', 'ovp_table'); var header_row = newElement('tr'); for (var i = 0; i < column_titles.length; i++) { header_row.appendChild(newCell(column_titles[i])); } header_row.appendChild(newCell('Aktion')); table.appendChild(header_row); for (i in entries) { table.appendChild(entries[i]); } teacher.appendChild(table); var entry_button = newButton('+ Eintrag', add_new_entry); teacher.appendChild(entry_button); return teacher; } function newDay(title, teachers) { var day = newElement('section'); var header = newElement('h2'); header.style.display = 'table'; header.innerHTML = title; header.onclick = function() { header.style.display = 'none'; var textbox = header.nextSibling; textbox.style.display = 'block'; textbox.focus(); textbox.select(); } day.appendChild(header); var textbox = newElement('input'); textbox.type = 'text'; textbox.style.display = 'none'; textbox.value = title; textbox['last_key'] = 0; textbox.onkeydown = function(e) { var key; if (window.event) { key = event.keyCode; } else if (e) { key = e.which; } if (key == 9 && textbox['last_key'] == 0) { textbox['create_teacher_on_first_blur'] = true; } textbox['last_key'] = key - 9; return true; } textbox.onkeyup = function() { textbox['last_key'] = 0; } textbox.onblur = function() { var header = textbox.previousSibling; if (textbox.value != '') { var new_date = parse_date(textbox.value); if (new_date) { var new_header = format_date_client(new_date); if (header.textContent != new_header) { header.textContent = new_header; var teachers = textbox.parentNode.getElementsByTagName('section'); for (var i = 0; i < teachers.length; i++) { save_teacher(teachers[i]); } } } else { header.innerHTML = '<span class="ovp_error">' + textbox.value + '</span>'; } } textbox.style.display = 'none'; header.style.display = 'table'; if (textbox.parentNode.childNodes.length == 3 && textbox['create_teacher_on_first_blur']) { textbox.parentNode.lastChild.onclick(); } } day.appendChild(textbox); for (i in teachers) { day.appendChild(teachers[i]); } day.appendChild(newButton('+ Lehrer', add_teacher)); return day; } function insert_days(days) { var ovp = document.getElementById('ovp'); for (i in days) { ovp.insertBefore(days[i], ovp.lastChild); } } function init_entry() { document.getElementById('ovp').appendChild(newButton('+ Tag', add_day)); fill_in_data(); } document.addEventListener("DOMContentLoaded", init_entry, false);
gwater/rlo-plan
entry.js
JavaScript
agpl-3.0
16,345
'use strict'; define(function(require) { var Backbone = require('backbone'), routes = require('routes'), GroupModel = require('model/groups/group-model'); var GroupsList = Backbone.Collection.extend({ model: GroupModel, url: routes.absoluteUrl(routes.GROUPS_DATA), fetch: function(options){ if (this.search) { (options || (options = {})).data = { search: this.search }; } return Backbone.Collection.prototype.fetch.call(this, options); } }); return GroupsList; })
hflabs/perecoder
rcd-web/src/main/javascript/app/model/groups/groups-list.js
JavaScript
agpl-3.0
619
/** @jsx React.DOM */ 'use strict'; var Lazy = require('lazy.js'), React = require('react'), ReactIntlMixin = require('react-intl'); var EnumerationControl = React.createClass({ mixins: [ReactIntlMixin], propTypes: { default: React.PropTypes.string, error: React.PropTypes.string, label: React.PropTypes.element.isRequired, labels: React.PropTypes.object.isRequired, name: React.PropTypes.string.isRequired, onChange: React.PropTypes.func.isRequired, suggestion: React.PropTypes.string, value: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), }, handleChange(event) { this.props.onChange(event.target.value); }, render() { var firstOptionLabel = `${this.getIntlMessage('notIndicated')} (${ this.props.suggestion ? this.formatMessage(this.getIntlMessage('suggestedValue'), {value: this.props.labels[this.props.suggestion]}) : this.formatMessage(this.getIntlMessage('defaultValue'), {value: this.props.labels[this.props.default]}) })`; return ( <div> {this.props.label} <select className="form-control" id={this.props.name} onChange={this.handleChange} value={this.props.value} > <option value="">{firstOptionLabel}</option> { Lazy(this.props.labels).map((label, labelId) => <option key={labelId} value={labelId}>{label}</option> ).toArray() } </select> </div> ); }, }); module.exports = EnumerationControl;
openfisca/openfisca-web-ui
openfisca_web_ui/static/js/components/test-case/form/enumeration-control.js
JavaScript
agpl-3.0
1,605
var searchData= [ ['unknown',['UNKNOWN',['../classtetgenmesh.xhtml#a1d02bed7b59566d57b896776d78a6b25a51233a7db87ef44baab2026b0ebdf22f',1,'tetgenmesh']]], ['unusedvertex',['UNUSEDVERTEX',['../classtetgenmesh.xhtml#ad0458f823a5eef2de89c7fae067aa2aca1d0b671fcad449d30b826305df861a52',1,'tetgenmesh']]] ];
vroland/SimpleAnalyzer
doc/html/search/enumvalues_75.js
JavaScript
agpl-3.0
306
/* * Latch integration for Meteor framework * Copyright (C) 2015 Bruno Orcha García <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ Session.setDefault('Meteor._latch.pairing', false); Template._latchAccountLinks.helpers({ isPairing: function() { return Session.get('Meteor._latch.pairing'); }, isPaired: Latch.isPaired }); Template._latchAccountLinks.events({ "click #latch-pair-link" : function (evt, tmpl) { Accounts._loginButtonsSession.resetMessages(); Tracker.flush(); var token = prompt("Open your Latch app and select 'Add a new service'.\nWrite down the token code shown."); if (!token) return; Session.set('Meteor._latch.pairing', true); Latch.pair(token, function(err, res) { Session.set('Meteor._latch.pairing', false); if (err) { Accounts._loginButtonsSession.errorMessage(err.reason); } else { Accounts._loginButtonsSession.infoMessage("Account protected with Latch!"); } }); }, "click #latch-unpair-link" : function (evt, tmpl) { Accounts._loginButtonsSession.resetMessages(); Tracker.flush(); if (!confirm("You're going to disable Latch protection for your account. Are your sure?")) return; Latch.unpair(function(err, res) { if (err) { Accounts._loginButtonsSession.errorMessage(err.reason); } else { Accounts._loginButtonsSession.infoMessage("Account protection disabled."); } }); } }); injectTemplate("_latchAccountLinks", "_loginButtonsLoggedInDropdownActions")
gimco/meteor-accounts-ui-latch
accounts_ui_latch.js
JavaScript
lgpl-2.1
2,278
/* * This file is part of Cockpit. * * Copyright (C) 2015 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ import cockpit from "cockpit"; import { mustache } from "mustache"; import day_header_template from 'raw-loader!journal_day_header.mustache'; import line_template from 'raw-loader!journal_line.mustache'; import reboot_template from 'raw-loader!journal_reboot.mustache'; import moment from "moment"; moment.locale(cockpit.language); const _ = cockpit.gettext; export var journal = { }; /** * journalctl([match, ...], [options]) * @match: any number of journal match strings * @options: an object containing further options * * Load and (by default) stream journal entries as * json objects. This function returns a jQuery deferred * object which delivers the various journal entries. * * The various @match strings are journalctl matches. * Zero, one or more can be specified. They must be in * string format, or arrays of strings. * * The optional @options object can contain the following: * * "host": the host to load journal from * * "count": number of entries to load and/or pre-stream. * Default is 10 * * "follow": if set to false just load entries and don't * stream further journal data. Default is true. * * "directory": optional directory to load journal files * * "boot": when set only list entries from this specific * boot id, or if null then the current boot. * * "since": if specified list entries since the date/time * * "until": if specified list entries until the date/time * * "cursor": a cursor to start listing entries from * * "after": a cursor to start listing entries after * * Returns a jQuery deferred promise. You can call these * functions on the deferred to handle the responses. Note that * there are additional non-jQuery methods. * * .done(function(entries) { }): Called when done, @entries is * an array of all journal entries loaded. If .stream() * has been invoked then @entries will be empty. * .fail(funciton(ex) { }): called if the operation fails * .stream(function(entries) { }): called when we receive entries * entries. Called once per batch of journal @entries, * whether following or not. * .stop(): stop following or retrieving entries. */ journal.build_cmd = function build_cmd(/* ... */) { var matches = []; var i, arg; var options = { follow: true }; for (i = 0; i < arguments.length; i++) { arg = arguments[i]; if (typeof arg == "string") { matches.push(arg); } else if (typeof arg == "object") { if (arg instanceof Array) { matches.push.apply(matches, arg); } else { cockpit.extend(options, arg); break; } } else { console.warn("journal.journalctl called with invalid argument:", arg); } } if (options.count === undefined) { if (options.follow) options.count = 10; else options.count = null; } var cmd = ["journalctl", "-q"]; if (!options.count) cmd.push("--no-tail"); else cmd.push("--lines=" + options.count); cmd.push("--output=" + (options.output || "json")); if (options.directory) cmd.push("--directory=" + options.directory); if (options.boot) cmd.push("--boot=" + options.boot); else if (options.boot !== undefined) cmd.push("--boot"); if (options.since) cmd.push("--since=" + options.since); if (options.until) cmd.push("--until=" + options.until); if (options.cursor) cmd.push("--cursor=" + options.cursor); if (options.after) cmd.push("--after=" + options.after); /* journalctl doesn't allow reverse and follow together */ if (options.reverse) cmd.push("--reverse"); else if (options.follow) cmd.push("--follow"); cmd.push("--"); cmd.push.apply(cmd, matches); return [cmd, options]; }; journal.journalctl = function journalctl(/* ... */) { var [cmd, options] = journal.build_cmd.apply(null, arguments); var dfd = cockpit.defer(); var promise; var buffer = ""; var entries = []; var streamers = []; var interval = null; function fire_streamers() { var ents, i; if (streamers.length && entries.length > 0) { ents = entries; entries = []; for (i = 0; i < streamers.length; i++) streamers[i].apply(promise, [ents]); } else { window.clearInterval(interval); interval = null; } } var proc = cockpit.spawn(cmd, { host: options.host, batch: 8192, latency: 300, superuser: "try" }) .stream(function(data) { if (buffer) data = buffer + data; buffer = ""; var lines = data.split("\n"); var last = lines.length - 1; lines.forEach(function(line, i) { if (i == last) { buffer = line; } else if (line && line.indexOf("-- ") !== 0) { try { entries.push(JSON.parse(line)); } catch (e) { console.warn(e, line); } } }); if (streamers.length && interval === null) interval = window.setInterval(fire_streamers, 300); }) .done(function() { fire_streamers(); dfd.resolve(entries); }) .fail(function(ex) { /* The journalctl command fails when no entries are matched * so we just ignore this status code */ if (ex.problem == "cancelled" || ex.exit_status === 1) { fire_streamers(); dfd.resolve(entries); } else { dfd.reject(ex); } }) .always(function() { window.clearInterval(interval); }); promise = dfd.promise(); promise.stream = function stream(callback) { streamers.push(callback); return this; }; promise.stop = function stop() { proc.close("cancelled"); }; return promise; }; journal.printable = function printable(value) { if (value === undefined || value === null) return _("[no data]"); else if (typeof (value) == "string") return value; else if (value.length !== undefined) return cockpit.format(_("[$0 bytes of binary data]"), value.length); else return _("[binary data]"); }; function output_funcs_for_box(box) { /* Dereference any jQuery object here */ if (box.jquery) box = box[0]; mustache.parse(day_header_template); mustache.parse(line_template); mustache.parse(reboot_template); function render_line(ident, prio, message, count, time, entry) { var parts = { cursor: entry.__CURSOR, time: time, message: message, service: ident }; if (count > 1) parts.count = count; if (ident === 'abrt-notification') { parts.problem = true; parts.service = entry.PROBLEM_BINARY; } else if (prio < 4) parts.warning = true; return mustache.render(line_template, parts); } var reboot = _("Reboot"); var reboot_line = mustache.render(reboot_template, { message: reboot }); function render_reboot_separator() { return reboot_line; } function render_day_header(day) { return mustache.render(day_header_template, { day: day }); } function parse_html(string) { var div = document.createElement("div"); div.innerHTML = string.trim(); return div.children[0]; } return { render_line: render_line, render_day_header: render_day_header, render_reboot_separator: render_reboot_separator, append: function(elt) { if (typeof (elt) == "string") elt = parse_html(elt); box.appendChild(elt); }, prepend: function(elt) { if (typeof (elt) == "string") elt = parse_html(elt); if (box.firstChild) box.insertBefore(elt, box.firstChild); else box.appendChild(elt); }, remove_last: function() { if (box.lastChild) box.removeChild(box.lastChild); }, remove_first: function() { if (box.firstChild) box.removeChild(box.firstChild); }, }; } /* Render the journal entries by passing suitable HTML strings back to the caller via the 'output_funcs'. Rendering is context aware. It will insert 'reboot' markers, for example, and collapse repeated lines. You can extend the output at the bottom and also at the top. A new renderer is created by calling 'journal.renderer' like so: var renderer = journal.renderer(funcs); You can feed new entries into the renderer by calling various methods on the returned object: - renderer.append(journal_entry) - renderer.append_flush() - renderer.prepend(journal_entry) - renderer.prepend_flush() A 'journal_entry' is one element of the result array returned by a call to 'Query' with the 'cockpit.journal_fields' as the fields to return. Calling 'append' will append the given entry to the end of the output, naturally, and 'prepend' will prepend it to the start. The output might lag behind what has been input via 'append' and 'prepend', and you need to call 'append_flush' and 'prepend_flush' respectively to ensure that the output is up-to-date. Flushing a renderer does not introduce discontinuities into the output. You can continue to feed entries into the renderer after flushing and repeated lines will be correctly collapsed across the flush, for example. The renderer will call methods of the 'output_funcs' object to produce the desired output: - output_funcs.append(rendered) - output_funcs.remove_last() - output_funcs.prepend(rendered) - output_funcs.remove_first() The 'rendered' argument is the return value of one of the rendering functions described below. The 'append' and 'prepend' methods should add this element to the output, naturally, and 'remove_last' and 'remove_first' should remove the indicated element. If you never call 'prepend' on the renderer, 'output_func.prepend' isn't called either. If you never call 'renderer.prepend' after 'renderer.prepend_flush', then 'output_func.remove_first' will never be called. The same guarantees exist for the 'append' family of functions. The actual rendering is also done by calling methods on 'output_funcs': - output_funcs.render_line(ident, prio, message, count, time, cursor) - output_funcs.render_day_header(day) - output_funcs.render_reboot_separator() */ journal.renderer = function renderer(funcs_or_box) { var output_funcs; if (funcs_or_box.render_line) output_funcs = funcs_or_box; else output_funcs = output_funcs_for_box(funcs_or_box); function copy_object(o) { var c = { }; for (var p in o) c[p] = o[p]; return c; } // A 'entry' object describes a journal entry in formatted form. // It has fields 'bootid', 'ident', 'prio', 'message', 'time', // 'day', all of which are strings. function format_entry(journal_entry) { var d = moment(journal_entry.__REALTIME_TIMESTAMP / 1000); // timestamps are in µs return { cursor: journal_entry.__CURSOR, full: journal_entry, day: d.format('LL'), time: d.format('LT'), bootid: journal_entry._BOOT_ID, ident: journal_entry.SYSLOG_IDENTIFIER || journal_entry._COMM, prio: journal_entry.PRIORITY, message: journal.printable(journal_entry.MESSAGE) }; } function entry_is_equal(a, b) { return (a && b && a.day == b.day && a.bootid == b.bootid && a.ident == b.ident && a.prio == b.prio && a.message == b.message); } // A state object describes a line that should be eventually // output. It has an 'entry' field as per description above, and // also 'count', 'last_time', and 'first_time', which record // repeated entries. Additionally: // // line_present: When true, the line has been output already with // some preliminary data. It needs to be removed before // outputting more recent data. // // header_present: The day header has been output preliminarily // before the actual log lines. It needs to be removed before // prepending more lines. If both line_present and // header_present are true, then the header comes first in the // output, followed by the line. function render_state_line(state) { return output_funcs.render_line(state.entry.ident, state.entry.prio, state.entry.message, state.count, state.last_time, state.entry.full); } // We keep the state of the first and last journal lines, // respectively, in order to collapse repeated lines, and to // insert reboot markers and day headers. // // Normally, there are two state objects, but if only a single // line has been output so far, top_state and bottom_state point // to the same object. var top_state, bottom_state; top_state = bottom_state = { }; function start_new_line() { // If we now have two lines, split the state if (top_state === bottom_state && top_state.entry) { top_state = copy_object(bottom_state); } } function top_output() { if (top_state.header_present) { output_funcs.remove_first(); top_state.header_present = false; } if (top_state.line_present) { output_funcs.remove_first(); top_state.line_present = false; } if (top_state.entry) { output_funcs.prepend(render_state_line(top_state)); top_state.line_present = true; } } function prepend(journal_entry) { var entry = format_entry(journal_entry); if (entry_is_equal(top_state.entry, entry)) { top_state.count += 1; top_state.first_time = entry.time; } else { top_output(); if (top_state.entry) { if (entry.bootid != top_state.entry.bootid) output_funcs.prepend(output_funcs.render_reboot_separator()); if (entry.day != top_state.entry.day) output_funcs.prepend(output_funcs.render_day_header(top_state.entry.day)); } start_new_line(); top_state.entry = entry; top_state.count = 1; top_state.first_time = top_state.last_time = entry.time; top_state.line_present = false; } } function prepend_flush() { top_output(); if (top_state.entry) { output_funcs.prepend(output_funcs.render_day_header(top_state.entry.day)); top_state.header_present = true; } } function bottom_output() { if (bottom_state.line_present) { output_funcs.remove_last(); bottom_state.line_present = false; } if (bottom_state.entry) { output_funcs.append(render_state_line(bottom_state)); bottom_state.line_present = true; } } function append(journal_entry) { var entry = format_entry(journal_entry); if (entry_is_equal(bottom_state.entry, entry)) { bottom_state.count += 1; bottom_state.last_time = entry.time; } else { bottom_output(); if (!bottom_state.entry || entry.day != bottom_state.entry.day) { output_funcs.append(output_funcs.render_day_header(entry.day)); bottom_state.header_present = true; } if (bottom_state.entry && entry.bootid != bottom_state.entry.bootid) output_funcs.append(output_funcs.render_reboot_separator()); start_new_line(); bottom_state.entry = entry; bottom_state.count = 1; bottom_state.first_time = bottom_state.last_time = entry.time; bottom_state.line_present = false; } } function append_flush() { bottom_output(); } return { prepend: prepend, prepend_flush: prepend_flush, append: append, append_flush: append_flush }; }; journal.logbox = function logbox(match, max_entries) { var entries = []; var box = document.createElement("div"); function render() { var renderer = journal.renderer(box); while (box.firstChild) box.removeChild(box.firstChild); for (var i = 0; i < entries.length; i++) { renderer.prepend(entries[i]); } renderer.prepend_flush(); if (entries.length === 0) { const empty_message = document.createElement("span"); empty_message.textContent = _("No log entries"); empty_message.setAttribute("class", "empty-message"); box.appendChild(empty_message); } } render(); var promise = journal.journalctl(match, { count: max_entries }) .stream(function(tail) { entries = entries.concat(tail); if (entries.length > max_entries) entries = entries.slice(-max_entries); render(); }) .fail(function(error) { box.appendChild(document.createTextNode(error.message)); box.removeAttribute("hidden"); }); /* Both a DOM element and a promise */ return promise.promise(box); };
cockpituous/cockpit
pkg/lib/journal.js
JavaScript
lgpl-2.1
19,214
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2007 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Editor configuration settings. * * Follow this link for more information: * http://wiki.fckeditor.net/Developer%27s_Guide/Configuration/Configurations_Settings */ FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; FCKConfig.EditorAreaStyles = '' ; FCKConfig.ToolbarComboPreviewCSS = '' ; FCKConfig.DocType = '' ; FCKConfig.BaseHref = '' ; FCKConfig.FullPage = false ; // The following option determines whether the "Show Blocks" feature is enabled or not at startup. FCKConfig.StartupShowBlocks = false ; FCKConfig.Debug = false ; FCKConfig.AllowQueryStringDebug = true ; FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ; FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ; FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ; // FCKConfig.Plugins.Add( 'autogrow' ) ; // FCKConfig.Plugins.Add( 'dragresizetable' ); FCKConfig.AutoGrowMax = 400 ; // FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%> // FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code // FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control> FCKConfig.AutoDetectLanguage = true ; FCKConfig.DefaultLanguage = 'en' ; FCKConfig.ContentLangDirection = 'ltr' ; FCKConfig.ProcessHTMLEntities = true ; FCKConfig.IncludeLatinEntities = true ; FCKConfig.IncludeGreekEntities = true ; FCKConfig.ProcessNumericEntities = false ; FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'" FCKConfig.FillEmptyBlocks = true ; FCKConfig.FormatSource = true ; FCKConfig.FormatOutput = true ; FCKConfig.FormatIndentator = ' ' ; FCKConfig.GeckoUseSPAN = false ; FCKConfig.StartupFocus = false ; FCKConfig.ForcePasteAsPlainText = false ; FCKConfig.AutoDetectPasteFromWord = true ; // IE only. FCKConfig.ShowDropDialog = true ; FCKConfig.ForceSimpleAmpersand = false ; FCKConfig.TabSpaces = 0 ; FCKConfig.ShowBorders = true ; FCKConfig.SourcePopup = false ; FCKConfig.ToolbarStartExpanded = true ; FCKConfig.ToolbarCanCollapse = true ; FCKConfig.IgnoreEmptyParagraphValue = true ; FCKConfig.PreserveSessionOnFileBrowser = false ; FCKConfig.FloatingPanelsZIndex = 10000 ; FCKConfig.HtmlEncodeOutput = false ; FCKConfig.TemplateReplaceAll = true ; FCKConfig.TemplateReplaceCheckbox = true ; FCKConfig.ToolbarLocation = 'In' ; FCKConfig.ToolbarSets["Default"] = [ ['Source','DocProps','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'], '/', ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'], '/', ['Style','FontFormat','FontName','FontSize'], ['TextColor','BGColor'], ['FitWindow','ShowBlocks','-','About'] // No comma for the last row. ] ; FCKConfig.ToolbarSets["Basic"] = [ ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About'] ] ; FCKConfig.ToolbarSets["Copix"] = [ ['Source'], ['Cut','Copy','Paste','PasteText','PasteWord'], ['Undo','Redo','-','Find','Replace'], ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Rule','SpecialChar','Smiley'] //['Style', 'mailto'],//, 'phototheque','document','cmslink','cmslinkpopup'],'/', //['Table','-','TableInsertRow','TableDeleteRows','TableInsertColumn','TableDeleteColumns','TableInsertCell','TableDeleteCells','TableMergeCells','TableSplitCell'] ] ; FCKConfig.EnterMode = 'p' ; // p | div | br FCKConfig.ShiftEnterMode = 'br' ; // p | div | br FCKConfig.Keystrokes = [ [ CTRL + 65 /*A*/, true ], [ CTRL + 67 /*C*/, true ], [ CTRL + 70 /*F*/, true ], [ CTRL + 83 /*S*/, true ], [ CTRL + 88 /*X*/, true ], [ CTRL + 86 /*V*/, 'Paste' ], [ SHIFT + 45 /*INS*/, 'Paste' ], [ CTRL + 88 /*X*/, 'Cut' ], [ SHIFT + 46 /*DEL*/, 'Cut' ], [ CTRL + 90 /*Z*/, 'Undo' ], [ CTRL + 89 /*Y*/, 'Redo' ], [ CTRL + SHIFT + 90 /*Z*/, 'Redo' ], [ CTRL + 76 /*L*/, 'Link' ], [ CTRL + 66 /*B*/, 'Bold' ], [ CTRL + 73 /*I*/, 'Italic' ], [ CTRL + 85 /*U*/, 'Underline' ], [ CTRL + SHIFT + 83 /*S*/, 'Save' ], [ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ], [ CTRL + 9 /*TAB*/, 'Source' ] ] ; FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form'] ; FCKConfig.BrowserContextMenuOnCtrl = false ; FCKConfig.EnableMoreFontColors = true ; FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ; FCKConfig.FontFormats = 'p;div;pre;address;h1;h2;h3;h4;h5;h6' ; FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ; FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ; FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages' FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl FCKConfig.FirefoxSpellChecker = false ; FCKConfig.MaxUndoLevels = 15 ; FCKConfig.DisableObjectResizing = false ; FCKConfig.DisableFFTableHandles = true ; FCKConfig.LinkDlgHideTarget = false ; FCKConfig.LinkDlgHideAdvanced = false ; FCKConfig.ImageDlgHideLink = false ; FCKConfig.ImageDlgHideAdvanced = false ; FCKConfig.FlashDlgHideAdvanced = false ; FCKConfig.ProtectedTags = '' ; // This will be applied to the body element of the editor FCKConfig.BodyId = '' ; FCKConfig.BodyClass = '' ; FCKConfig.DefaultStyleLabel = '' ; FCKConfig.DefaultFontFormatLabel = '' ; FCKConfig.DefaultFontLabel = '' ; FCKConfig.DefaultFontSizeLabel = '' ; FCKConfig.DefaultLinkTarget = '' ; // The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word FCKConfig.CleanWordKeepsStructure = false ; // Only inline elements are valid. FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ; FCKConfig.CustomStyles = { 'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } } }; // Do not add, rename or remove styles here. Only apply definition changes. FCKConfig.CoreStyles = { // Basic Inline Styles. 'Bold' : { Element : 'b', Overrides : 'strong' }, 'Italic' : { Element : 'i', Overrides : 'em' }, 'Underline' : { Element : 'u' }, 'StrikeThrough' : { Element : 'strike' }, 'Subscript' : { Element : 'sub' }, 'Superscript' : { Element : 'sup' }, // Basic Block Styles (Font Format Combo). 'p' : { Element : 'p' }, 'div' : { Element : 'div' }, 'pre' : { Element : 'pre' }, 'address' : { Element : 'address' }, 'h1' : { Element : 'h1' }, 'h2' : { Element : 'h2' }, 'h3' : { Element : 'h3' }, 'h4' : { Element : 'h4' }, 'h5' : { Element : 'h5' }, 'h6' : { Element : 'h6' }, // Other formatting features. 'FontFace' : { Element : 'span', Styles : { 'font-family' : '#("Font")' }, Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ] }, 'Size' : { Element : 'span', Styles : { 'font-size' : '#("Size","fontSize")' }, Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ] }, 'Color' : { Element : 'span', Styles : { 'color' : '#("Color","color")' }, Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ] }, 'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } } }; // The distance of an indentation step. FCKConfig.IndentLength = 40 ; FCKConfig.IndentUnit = 'px' ; // Alternatively, FCKeditor allows the use of CSS classes for block indentation. // This overrides the IndentLength/IndentUnit settings. FCKConfig.IndentClasses = [] ; // [ Left, Center, Right, Justified ] FCKConfig.JustifyClasses = [] ; // The following value defines which File Browser connector and Quick Upload // "uploader" to use. It is valid for the default implementaion and it is here // just to make this configuration file cleaner. // It is not possible to change this value using an external file or even // inline when creating the editor instance. In that cases you must set the // values of LinkBrowserURL, ImageBrowserURL and so on. // Custom implementations should just ignore it. var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py // Don't care about the following line. It just calculates the correct connector // extension to use for the default File Browser (Perl uses "cgi"). var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ; FCKConfig.LinkBrowser = true ; FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ; FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% FCKConfig.ImageBrowser = true ; FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ; FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ; FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ; FCKConfig.FlashBrowser = true ; FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ; FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ; FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ; FCKConfig.LinkUpload = true ; FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage ; FCKConfig.LinkUploadAllowedExtensions = "" ; // empty for all FCKConfig.LinkUploadDeniedExtensions = ".(html|htm|php|php2|php3|php4|php5|phtml|pwml|inc|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|com|dll|vbs|js|reg|cgi|htaccess|asis|sh|shtml|shtm|phtm)$" ; // empty for no one FCKConfig.ImageUpload = true ; FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage + '?Type=Image' ; FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one FCKConfig.FlashUpload = true ; FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage + '?Type=Flash' ; FCKConfig.FlashUploadAllowedExtensions = ".(swf|fla)$" ; // empty for all FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ; FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ; FCKConfig.SmileyColumns = 8 ; FCKConfig.SmileyWindowWidth = 320 ; FCKConfig.SmileyWindowHeight = 240 ;
Copix/Copix3
www/js/FCKeditor/fckconfig.js
JavaScript
lgpl-2.1
13,198
export function convertRawMessage(rawMessage, currentThreadID) { return { ...rawMessage, date: new Date(rawMessage.timestamp), isRead: rawMessage.threadID === currentThreadID }; }; export function getCreatedMessageData(text, currentThreadID) { var timestamp = Date.now(); return { id: 'm_' + timestamp, threadID: currentThreadID, authorName: 'You', date: new Date(timestamp), text: text, isRead: true, type: 'message' }; }; export function getSUSIMessageData(message, currentThreadID) { var timestamp = Date.now(); let receivedMessage = { id: 'm_' + timestamp, threadID: currentThreadID, authorName: 'SUSI', // hard coded for the example text: message.text, response: message.response, actions: message.actions, websearchresults: message.websearchresults, date: new Date(timestamp), isRead: true, responseTime: message.responseTime, type: 'message' }; return receivedMessage; }
DravitLochan/accounts.susi.ai
src/utils/ChatMessageUtils.js
JavaScript
lgpl-2.1
986
import {Inject, Injectable} from 'app/app'; import {BootstrapService} from 'services/bootstrap-service'; import {UserService} from 'security/user-service'; import {Eventbus} from 'services/eventbus/eventbus'; import {PersonalMailboxUpdatedEvent} from 'idoc/system-tabs/mailbox/events/personal-mailbox-updated-event'; import {MailboxInfoService} from 'services/rest/mailbox-info-service'; import {PollingUtils} from 'common/polling-utils'; import {Configuration} from 'common/application-config'; @Injectable() @Inject(Eventbus, MailboxInfoService, UserService, PollingUtils, Configuration) export class PersonalMailboxInfoObserver extends BootstrapService { constructor(eventbus, mailboxInfoService, userService, pollingUtils, configuration) { super(); this.eventbus = eventbus; this.mailboxInfoService = mailboxInfoService; this.userService = userService; this.pollingUtils = pollingUtils; this.pollingInterval = configuration.get(Configuration.MAILBOX_STATUS_POLL_INTERVAL); } initialize() { this.userService.getCurrentUser().then((response) => { if (response.mailboxSupportable) { this.pollingUtils.pollInfinite('personal_mailbox_unread_messages_count', this.handleMessagesStatusUpdate.bind(this), this.pollingInterval, false); } }); } handleMessagesStatusUpdate() { this.userService.getCurrentUser().then((response) => { return this.mailboxInfoService.getUnreadMessagesCount(response.emailAddress, {skipInterceptor: true}); }).then((response) => { this.eventbus.publish(new PersonalMailboxUpdatedEvent(response.data)); }); } }
SirmaITT/conservation-space-1.7.0
docker/sep-ui/src/idoc/system-tabs/mailbox/services/personal-mailbox-info-observer/personal-mailbox-info-observer.js
JavaScript
lgpl-3.0
1,622
<import resource="classpath:/alfresco/templates/org/alfresco/import/alfresco-util.js"> /** * Cloud Sync Status Information * */ function main() { AlfrescoUtil.param("nodeRef"); AlfrescoUtil.param("site", "defaultSite"); AlfrescoUtil.param("rootPage", "documentlibrary"); AlfrescoUtil.param("rootLabelId", "path.documents"); var nodeDetails = AlfrescoUtil.getNodeDetails(model.nodeRef, model.site); if (nodeDetails) { model.item = nodeDetails.item; model.node = nodeDetails.item.node; model.paths = AlfrescoUtil.getPaths(nodeDetails, model.rootPage, model.rootLabelId); } } main();
loftuxab/community-edition-old
projects/slingshot/config/alfresco/site-webscripts/org/alfresco/components/node-details/node-path.get.js
JavaScript
lgpl-3.0
650
/* global shoproot */ /** * 编辑分类 * @description Hope You Do Good But Not Evil * @copyright Copyright 2014-2015 <[email protected]> * @license LGPL (http://www.gnu.org/licenses/lgpl.html) * @author Chenyong Cai <[email protected]> * @package Wshop * @link http://www.iwshop.cn */ requirejs(['jquery', 'util', 'fancyBox', 'jUploader'], function ($, Util, fancyBox, jUploader) { $(function () { $("#pd-cat-select").find("option[value='" + $('#cat_parent').val() + "']").get(0).selected = true; $('#del-cate').click(function () { if (confirm('你确定要删除这个分类吗')) { $.post('?/wProduct/ajaxDelCategroy/', { id: $('#cat_id').val() }, function (r) { r = parseInt(r); if (r > 0) { alert('删除成功'); window.parent.fnDelSelectCat(); window.parent.location.reload(); } }); } }); // alter $('#save-cate').click(function () { var data = $('#catForm').serializeArray(); $.post('?/wProduct/ajaxAlterCategroy/', { id: $('#cat_id').val(), data: data }, function (r) { r = parseInt(r); if (r > 0) { Util.Alert('保存成功'); window.parent.fnReloadTree(); } else { Util.Alert('保存失败'); } }); }); $.jUploader({ button: 'alter_categroy_image', action: '?/wImages/ImageUpload/', onComplete: function (fileName, response) { if (response.ret_code == 0) { $('#cat_image_src').val(response.ret_msg); $('#catimage').attr('src', response.ret_msg).show(); $('#cat_none_pic').hide(); Util.Alert('上传图片成功'); } else { Util.Alert('上传图片失败'); } } }); }); });
mentallxm/iwshop
static/script/Wdmin/products/alter_categroy.js
JavaScript
lgpl-3.0
2,214
module.exports = require("protobufjs").newBuilder({})["import"]({ "package": "textsecure", "messages": [ { "name": "IncomingPushMessageSignal", "fields": [ { "rule": "optional", "options": {}, "type": "Type", "name": "type", "id": 1 }, { "rule": "optional", "options": {}, "type": "string", "name": "source", "id": 2 }, { "rule": "optional", "options": {}, "type": "uint32", "name": "sourceDevice", "id": 7 }, { "rule": "optional", "options": {}, "type": "string", "name": "relay", "id": 3 }, { "rule": "optional", "options": {}, "type": "uint64", "name": "timestamp", "id": 5 }, { "rule": "optional", "options": {}, "type": "bytes", "name": "message", "id": 6 } ], "enums": [ { "name": "Type", "values": [ { "name": "UNKNOWN", "id": 0 }, { "name": "CIPHERTEXT", "id": 1 }, { "name": "KEY_EXCHANGE", "id": 2 }, { "name": "PREKEY_BUNDLE", "id": 3 }, { "name": "PLAINTEXT", "id": 4 }, { "name": "RECEIPT", "id": 5 } ], "options": {} } ], "messages": [], "options": {}, "oneofs": {} }, { "name": "PushMessageContent", "fields": [ { "rule": "optional", "options": {}, "type": "string", "name": "body", "id": 1 }, { "rule": "repeated", "options": {}, "type": "AttachmentPointer", "name": "attachments", "id": 2 }, { "rule": "optional", "options": {}, "type": "GroupContext", "name": "group", "id": 3 }, { "rule": "optional", "options": {}, "type": "uint32", "name": "flags", "id": 4 } ], "enums": [ { "name": "Flags", "values": [ { "name": "END_SESSION", "id": 1 } ], "options": {} } ], "messages": [ { "name": "AttachmentPointer", "fields": [ { "rule": "optional", "options": {}, "type": "fixed64", "name": "id", "id": 1 }, { "rule": "optional", "options": {}, "type": "string", "name": "contentType", "id": 2 }, { "rule": "optional", "options": {}, "type": "bytes", "name": "key", "id": 3 } ], "enums": [], "messages": [], "options": {}, "oneofs": {} }, { "name": "GroupContext", "fields": [ { "rule": "optional", "options": {}, "type": "bytes", "name": "id", "id": 1 }, { "rule": "optional", "options": {}, "type": "Type", "name": "type", "id": 2 }, { "rule": "optional", "options": {}, "type": "string", "name": "name", "id": 3 }, { "rule": "repeated", "options": {}, "type": "string", "name": "members", "id": 4 }, { "rule": "optional", "options": {}, "type": "AttachmentPointer", "name": "avatar", "id": 5 } ], "enums": [ { "name": "Type", "values": [ { "name": "UNKNOWN", "id": 0 }, { "name": "UPDATE", "id": 1 }, { "name": "DELIVER", "id": 2 }, { "name": "QUIT", "id": 3 } ], "options": {} } ], "messages": [], "options": {}, "oneofs": {} } ], "options": {}, "oneofs": {} } ], "enums": [], "imports": [], "options": { "java_package": "org.whispersystems.textsecure.push", "java_outer_classname": "PushMessageProtos" }, "services": [] }).build("textsecure");
joebandenburg/textsecure-server-node
lib/IncomingPushMessageSignalProtos.js
JavaScript
lgpl-3.0
7,889
var class_catharsis_1_1_domain_1_1_web_link_1_1_schema = [ [ "ColumnCommentCreatedOn", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#acf10a3ba60a74862f0f6c5693d4274b1", null ], [ "ColumnCommentDescription", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a253b5a08698b9031bad6693e58d70276", null ], [ "ColumnCommentId", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a62a44fbade52666afecb722b3cc0002c", null ], [ "ColumnCommentImage", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a5209aed87483c60a6d60c77e0ab33ac2", null ], [ "ColumnCommentName", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#aff737033215d67eb5727a33d09abb655", null ], [ "ColumnCommentUpdatedOn", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#af1000ca8cfc7c0a7f9d06571659c6699", null ], [ "ColumnCommentUri", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a074316460dc9e10ccf615ad67ddcfae1", null ], [ "ColumnNameCreatedOn", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#ab40431c7dbc082df339dc71151fcff32", null ], [ "ColumnNameDescription", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a9031ad7955bbc0fad88d60dbceac977d", null ], [ "ColumnNameId", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a2c5f800e0f2eee1fcebe43a1cbab6d50", null ], [ "ColumnNameImage", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a6d6e17b4d40fe663a922337b471f406f", null ], [ "ColumnNameName", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a24f0c4399f4bbb5fdcb3f8892bb5c2d2", null ], [ "ColumnNameUpdatedOn", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#ac1ff984be705dacb3cb0f3cfca73d6c9", null ], [ "ColumnNameUri", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a607055be01cf88d11d958216e5bdd583", null ], [ "TableComment", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#ad69651422e540bc44ee5131cbae72039", null ], [ "TableName", "class_catharsis_1_1_domain_1_1_web_link_1_1_schema.html#a41c22ffc0b4eec63865355616bd39690", null ] ];
prokhor-ozornin/Catharsis.NET.Domain
doc/html/class_catharsis_1_1_domain_1_1_web_link_1_1_schema.js
JavaScript
lgpl-3.0
2,104
var class_hydro_couple_1_1_spatial_1_1_i_raster = [ [ "RasterDataType", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57", [ [ "Unknown", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a6b6a05fc6ca4f23a7946b2a71e6745a2", null ], [ "Byte", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a153211909d8759eba4752fc8f3251ca2", null ], [ "UInt16", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a266985b8569588028028a205c37798a4", null ], [ "Int16", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a733049b137b5d4312a2b1f4a8dbf3e14", null ], [ "UInt32", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a525c93df497c1cc30532a19e0ed566d2", null ], [ "Int32", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a9ba52e58957de9cccbfc1dd39c09b303", null ], [ "Float32", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a652f7cca2f5d1895bd4313fd6bad9562", null ], [ "Float64", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a7f8c473bcbc860a342fe2fb15d2b9203", null ], [ "CInt16", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57ac7cccfaf04621a83331493abe221d107", null ], [ "CInt32", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a8db4ee278f075285ddc0423411c5d6b1", null ], [ "CFloat32", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a2bc275cf234741f12a6fbe02bfb7798c", null ], [ "CFloat64", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ae3ea6483d22355c7d6b8aaa268359d57a5c2b567403b2a5dea831822adc20c91e", null ] ] ], [ "~IRaster", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#a13282336b47f8feab0b58deb7d62e524", null ], [ "addRasterBand", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ad62fe6aa4649f4b58cb28ebc50cd53e9", null ], [ "geoTransformation", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#a0f918dd8435650934c15042844ec3045", null ], [ "getRasterBand", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#a2fb7cee15d778f6b2a7c608355ee1031", null ], [ "rasterBandCount", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#ab2e66474205ae38839014c875a804373", null ], [ "spatialReferenceSystem", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#a57978d6397548c02e566d735386eff80", null ], [ "xSize", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#a230349770291b0b61459a72c357b9adc", null ], [ "ySize", "d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.html#a0e7ea53d6a681f0ac66f52c4d32632c1", null ] ];
HydroCouple/hydrocouple.github.io
hydrocoupledocs/html/d8/d5b/class_hydro_couple_1_1_spatial_1_1_i_raster.js
JavaScript
lgpl-3.0
2,993
(function (window, $, undefined) { $.infinitescroll = function infscr(options, callback, element) { this.element = $(element); this._create(options, callback); }; $.infinitescroll.defaults = { loading: { finished: undefined, finishedMsg: "", img: "http://www.infinite-scroll.com/loading.gif", msg: null, msgText: "<em>Loading the next set of posts...</em>", selector: null, speed: 'fast', start: undefined }, state: { isDuringAjax: false, isInvalidPage: false, isDestroyed: false, isDone: false, isPaused: false, currPage: 1 }, callback: undefined, debug: false, behavior: undefined, binder: $(window), nextSelector: "div.navigation a:first", navSelector: "div.navigation", contentSelector: null, extraScrollPx: 150, itemSelector: "div.post", animate: false, pathParse: undefined, dataType: 'html', appendCallback: true, bufferPx: 40, errorCallback: function () { }, infid: 0, pixelsFromNavToBottom: undefined, path: undefined }; $.infinitescroll.prototype = { _binding: function infscr_binding(binding) { var instance = this, opts = instance.options; if (!!opts.behavior && this['_binding_' + opts.behavior] !== undefined) { this['_binding_' + opts.behavior].call(this); return; } if (binding !== 'bind' && binding !== 'unbind') { this._debug('Binding value ' + binding + ' not valid') return false; } if (binding == 'unbind') { (this.options.binder).unbind('smartscroll.infscr.' + instance.options.infid); } else { (this.options.binder)[binding]('smartscroll.infscr.' + instance.options.infid, function () { instance.scroll(); }); }; this._debug('Binding', binding); }, //2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔصÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö loadDataOnCreat: function () { var _this = this; setTimeout(function () { if ($(document).height() - $(window).height() < 20) { _this.scroll(); _this.loadDataOnCreat(); } }, 3000); }, _create: function infscr_create(options, callback) { if (!this._validate(options)) { return false; } var opts = this.options = $.extend(true, {}, $.infinitescroll.defaults, options), relurl = /(.*?\/\/).*?(\/.*)/, path = $(opts.nextSelector).attr('href'); opts.contentSelector = opts.contentSelector || this.element; opts.loading.selector = opts.loading.selector || opts.contentSelector; if (!path) { this._debug('Navigation selector not found'); return; } opts.path = this._determinepath(path); opts.loading.msg = $('<div id="infscr-loading" class="tn-loading"></div>'); (new Image()).src = opts.loading.img; opts.pixelsFromNavToBottom = $(document).height() - $(opts.navSelector).offset().top; opts.loading.start = opts.loading.start || function () { $(opts.navSelector).hide(); opts.loading.msg.appendTo(opts.loading.selector).show(opts.loading.speed, function () { beginAjax(opts); }); }; opts.loading.finished = opts.loading.finished || function () { opts.loading.msg.fadeOut('normal'); }; opts.callback = function (instance, data) { if (!!opts.behavior && instance['_callback_' + opts.behavior] !== undefined) { instance['_callback_' + opts.behavior].call($(opts.contentSelector)[0], data); } if (callback) { callback.call($(opts.contentSelector)[0], data); } }; this._setup(); //2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔصÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö this.loadDataOnCreat(); }, _debug: function infscr_debug() { if (this.options.debug) { return window.console && console.log.call(console, arguments); } }, _determinepath: function infscr_determinepath(path) { var opts = this.options; if (!!opts.behavior && this['_determinepath_' + opts.behavior] !== undefined) { this['_determinepath_' + opts.behavior].call(this, path); return; } if (!!opts.pathParse) { this._debug('pathParse manual'); return opts.pathParse; } else if (path.match(/^(.*?)\b2\b(.*?$)/)) { path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1); } else if (path.match(/^(.*?)2(.*?$)/)) { if (path.match(/^(.*?page=)2(\/.*|$)/)) { path = path.match(/^(.*?page=)2(\/.*|$)/).slice(1); return path; } path = path.match(/^(.*?)2(.*?$)/).slice(1); } else { if (path.match(/^(.*?page=)1(\/.*|$)/)) { path = path.match(/^(.*?page=)1(\/.*|$)/).slice(1); return path; } else { this._debug('Sorry, we couldn\'t parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.'); opts.state.isInvalidPage = true; } } this._debug('determinePath', path); return path; }, _error: function infscr_error(xhr) { var opts = this.options; if (!!opts.behavior && this['_error_' + opts.behavior] !== undefined) { this['_error_' + opts.behavior].call(this, xhr); return; } if (xhr !== 'destroy' && xhr !== 'end') { xhr = 'unknown'; } this._debug('Error', xhr); if (xhr == 'end') { this._showdonemsg(); } opts.state.isDone = true; opts.state.currPage = 1; opts.state.isPaused = false; this._binding('unbind'); }, _loadcallback: function infscr_loadcallback(box, data) { var opts = this.options, callback = this.options.callback, result = (opts.state.isDone) ? 'done' : (!opts.appendCallback) ? 'no-append' : 'append', frag; if (!!opts.behavior && this['_loadcallback_' + opts.behavior] !== undefined) { this['_loadcallback_' + opts.behavior].call(this, box, data); return; } switch (result) { case 'done': this._showdonemsg(); return false; break; case 'no-append': if (opts.dataType == 'html') { data = '<div>' + data + '</div>'; data = $(data).find(opts.itemSelector); }; break; case 'append': var children = box.children(); if (children.length == 0) { return this._error('end'); } frag = document.createDocumentFragment(); while (box[0].firstChild) { frag.appendChild(box[0].firstChild); } this._debug('contentSelector', $(opts.contentSelector)[0]) $(opts.contentSelector)[0].appendChild(frag); data = children.get(); break; } opts.loading.finished.call($(opts.contentSelector)[0], opts) if (opts.animate) { var scrollTo = $(window).scrollTop() + $('#infscr-loading').height() + opts.extraScrollPx + 'px'; $('html,body').animate({ scrollTop: scrollTo }, 800, function () { opts.state.isDuringAjax = false; }); } if (!opts.animate) opts.state.isDuringAjax = false; callback(this, data); }, _nearbottom: function infscr_nearbottom() { var opts = this.options, pixelsFromWindowBottomToBottom = 0 + $(document).height() - (opts.binder.scrollTop()) - $(window).height(); if (!!opts.behavior && this['_nearbottom_' + opts.behavior] !== undefined) { this['_nearbottom_' + opts.behavior].call(this); return; } this._debug('math:', pixelsFromWindowBottomToBottom, opts.pixelsFromNavToBottom); return (pixelsFromWindowBottomToBottom - opts.bufferPx < opts.pixelsFromNavToBottom); }, _pausing: function infscr_pausing(pause) { var opts = this.options; if (!!opts.behavior && this['_pausing_' + opts.behavior] !== undefined) { this['_pausing_' + opts.behavior].call(this, pause); return; } if (pause !== 'pause' && pause !== 'resume' && pause !== null) { this._debug('Invalid argument. Toggling pause value instead'); }; pause = (pause && (pause == 'pause' || pause == 'resume')) ? pause : 'toggle'; switch (pause) { case 'pause': opts.state.isPaused = true; break; case 'resume': opts.state.isPaused = false; break; case 'toggle': opts.state.isPaused = !opts.state.isPaused; break; } this._debug('Paused', opts.state.isPaused); return false; }, _setup: function infscr_setup() { var opts = this.options; if (!!opts.behavior && this['_setup_' + opts.behavior] !== undefined) { this['_setup_' + opts.behavior].call(this); return; } this._binding('bind'); return false; }, _showdonemsg: function infscr_showdonemsg() { var opts = this.options; if (!!opts.behavior && this['_showdonemsg_' + opts.behavior] !== undefined) { this['_showdonemsg_' + opts.behavior].call(this); return; } opts.loading.msg.find('img').hide().parent().find('div').html(opts.loading.finishedMsg).animate({ opacity: 1 }, 2000, function () { $(this).parent().fadeOut('normal'); }); $('#infscr-loading').hide(); opts.errorCallback.call($(opts.contentSelector)[0], 'done'); }, _validate: function infscr_validate(opts) { for (var key in opts) { if (key.indexOf && key.indexOf('Selector') > -1 && $(opts[key]).length === 0) { this._debug('Your ' + key + ' found no elements.'); return false; } return true; } }, bind: function infscr_bind() { this._binding('bind'); }, destroy: function infscr_destroy() { this.options.state.isDestroyed = true; return this._error('destroy'); }, pause: function infscr_pause() { this._pausing('pause'); }, resume: function infscr_resume() { this._pausing('resume'); }, retrieve: function infscr_retrieve(pageNum) { var instance = this, opts = instance.options, path = opts.path, box, frag, desturl, method, condition, pageNum = pageNum || null, getPage = (!!pageNum) ? pageNum : opts.state.currPage; beginAjax = function infscr_ajax(opts) { opts.state.currPage++; instance._debug('heading into ajax', path); box = $(opts.contentSelector).is('table') ? $('<tbody/>') : $('<div/>'); desturl = path.join(opts.state.currPage); method = (opts.dataType == 'html' || opts.dataType == 'json') ? opts.dataType : 'html+callback'; if (opts.appendCallback && opts.dataType == 'html') method += '+callback' switch (method) { case 'html+callback': instance._debug('Using HTML via .load() method'); box.load(desturl + ' ' + opts.itemSelector, null, function infscr_ajax_callback(responseText) { instance._loadcallback(box, responseText); }); break; case 'html': case 'json': instance._debug('Using ' + (method.toUpperCase()) + ' via $.ajax() method'); $.ajax({ url: desturl, dataType: opts.dataType, complete: function infscr_ajax_callback(jqXHR, textStatus) { condition = (typeof (jqXHR.isResolved) !== 'undefined') ? (jqXHR.isResolved()) : (textStatus === "success" || textStatus === "notmodified"); (condition) ? instance._loadcallback(box, jqXHR.responseText) : instance._error('end'); } }); break; } }; if (!!opts.behavior && this['retrieve_' + opts.behavior] !== undefined) { this['retrieve_' + opts.behavior].call(this, pageNum); return; } if (opts.state.isDestroyed) { this._debug('Instance is destroyed'); return false; }; opts.state.isDuringAjax = true; opts.loading.start.call($(opts.contentSelector)[0], opts); }, scroll: function infscr_scroll() { var opts = this.options, state = opts.state; if (!!opts.behavior && this['scroll_' + opts.behavior] !== undefined) { this['scroll_' + opts.behavior].call(this); return; } if (state.isDuringAjax || state.isInvalidPage || state.isDone || state.isDestroyed || state.isPaused) return; if (!this._nearbottom()) return; this.retrieve(); }, toggle: function infscr_toggle() { this._pausing(); }, unbind: function infscr_unbind() { this._binding('unbind'); }, update: function infscr_options(key) { if ($.isPlainObject(key)) { this.options = $.extend(true, this.options, key); } } } $.fn.infinitescroll = function infscr_init(options, callback) { var thisCall = typeof options; switch (thisCall) { case 'string': var args = Array.prototype.slice.call(arguments, 1); this.each(function () { var instance = $.data(this, 'infinitescroll'); if (!instance) { return false; } if (!$.isFunction(instance[options]) || options.charAt(0) === "_") { return false; } instance[options].apply(instance, args); }); break; case 'object': this.each(function () { var instance = $.data(this, 'infinitescroll'); if (instance) { instance.update(options); } else { $.data(this, 'infinitescroll', new $.infinitescroll(options, callback, this)); } }); break; } return this; }; var event = $.event, scrollTimeout; event.special.smartscroll = { setup: function () { $(this).bind("scroll", event.special.smartscroll.handler); }, teardown: function () { $(this).unbind("scroll", event.special.smartscroll.handler); }, handler: function (event, execAsap) { var context = this, args = arguments; event.type = "smartscroll"; if (scrollTimeout) { clearTimeout(scrollTimeout); } scrollTimeout = setTimeout(function () { $.event.handle.apply(context, args); }, execAsap === "execAsap" ? 0 : 100); } }; $.fn.smartscroll = function (fn) { return fn ? this.bind("smartscroll", fn) : this.trigger("smartscroll", ["execAsap"]); }; })(window, jQuery);
yesan/Spacebuilder
Web/Scripts/jquery/masonry/jquery.infinitescroll.js
JavaScript
lgpl-3.0
17,301
/* Copyright 2007-2011 B3Partners BV. This program is distributed under the terms of the GNU General Public License. You should have received a copy of the GNU General Public License along with this software. If not, see http://www.gnu.org/licenses/gpl.html This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /*Hulp functions*/ //contains on array function function arrayContains(array,element) { for (var i = 0; i < array.length; i++) { if (array[i] == element) { return true; } } return false; } // jQuery gives problems with DWR - util.js, so noConflict mode. Usage for jQuery selecter becomes $j() instead of $() $j = jQuery.noConflict(); // Trim polyfill if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } attachOnload = function(onloadfunction) { if(typeof(onloadfunction) == 'function') { var oldonload=window.onload; if(typeof(oldonload) == 'function') { window.onload = function() { oldonload(); onloadfunction(); } } else { window.onload = function() { onloadfunction(); } } } } var resizeFunctions = new Array(); resizeFunction = function() { for(i in resizeFunctions) { resizeFunctions[i](); } } window.onresize = resizeFunction; attachOnresize = function(onresizefunction) { if(typeof(onresizefunction) == 'function') { resizeFunctions[resizeFunctions.length] = onresizefunction; } } checkLocation = function() { if (top.location != self.location) top.location = self.location; } checkLocationPopup = function() { if(!usePopup) { if (top.location == self.location) { top.location = '/gisviewerconfig/index.do'; } } } getIEVersionNumber = function() { var ua = navigator.userAgent; var MSIEOffset = ua.indexOf("MSIE "); if (MSIEOffset == -1) { return -1; } else { return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset))); } } var ieVersion = getIEVersionNumber(); function findPos(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft,curtop]; } function showHelpDialog(divid) { $j("#" + divid).dialog({ resizable: true, draggable: true, show: 'slide', hide: 'slide', autoOpen: false }); $j("#" + divid).dialog('open'); return false; } (function(B3PConfig) { B3PConfig.cookie = { createCookie: function(name,value,days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } else expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }, readCookie: function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length); } return null; }, eraseCookie: function(name) { this.createCookie(name,"",-1); } }; })(window.B3PConfig || (window.B3PConfig = {})); (function(B3PConfig, $) { B3PConfig.advancedToggle = { config: { advancedclass: '.configadvanced', advancedtoggle: '#advancedToggle', cookiename: 'advancedtoggle' }, advancedToggle: null, advancedItems: [], init: function() { var me = this, useAdvancedToggle = false; me.advancedToggle = $(me.config.advancedtoggle); me.advancedItems = $(me.config.advancedclass); me.advancedItems.each(function() { if($(this).html().trim() !== '') useAdvancedToggle = true; }); if(B3PConfig.cookie.readCookie(me.getCookiename()) !== null) { me.advancedToggle[0].checked = B3PConfig.cookie.readCookie(me.getCookiename()) === 'on'; } if(useAdvancedToggle) { me.advancedToggle.click(function(){ me.showHideAdvanced(); }); me.showHideAdvanced(); } else { me.advancedToggle.parent().hide(); } }, showHideAdvanced: function () { var showAdvancedOptions = this.advancedToggle.is(':checked'); B3PConfig.cookie.createCookie(this.getCookiename(), showAdvancedOptions ? 'on' : 'off', 7); showAdvancedOptions ? this.advancedItems.show() : this.advancedItems.hide(); }, getCookiename: function() { return this.config.cookiename + (this.advancedToggle.data('cookie-key') ? '-' + this.advancedToggle.data('cookie-key') : ''); } }; })(window.B3PConfig || (window.B3PConfig = {}), jQuery); var prevTab = null; var fbLbl; function labelClick($lbl) { if(prevTab != null) prevTab.hide(); prevTab = $j(".content_"+$lbl.attr("id").replace("label_", "")); prevTab.show(); $j(".tablabel").removeClass("active"); $lbl.addClass("active"); } var showAdvancedOptions = false; var contentMinHeight = 300; $j(document).ready(function() { contentMinHeight = $j(".tablabels").outerHeight(true)+20; if($j("#treedivContainer").length > 0) contentMinHeight = $j("#treedivContainer").outerHeight(true)+20; $j(".tabcontent").each(function (){ var counter = 0; $j(this).find(".configrow").each(function() { var $this = $j(this); if(counter%2==1) $this.addClass("odd"); counter++; $this.find(".helpLink").each(function (){ if($j(this).attr("id") && $j(this).attr("id") != 'undefined') { var $helpContentDiv = $j("#" + $j(this).attr("id").replace("helpLink_", "")); var helpContent = $helpContentDiv.html(); var helpTitle = $helpContentDiv.attr("title"); $j(this).qtip({ content: { text: helpContent, title: helpTitle }, hide: { event: 'mouseout' }, show: { event: 'click mouseenter' }, position: { my: 'right top', at: 'left middle', target: $j(this), viewport: $j(window), adjust: { x: -10 } } }); } }); }); if(!$j(this).hasClass("defaulttab")) $j(this).hide(); }); $j(".tablabel").each(function() { $j(this).click(function() { labelClick($j(this)); }); }); B3PConfig.advancedToggle.init(); $j(".tabcontent").css("min-height", contentMinHeight); if($j(".tablabel").length != 0) labelClick($j(".tablabel").first()); // Datatables var tables = []; jQuery('.dataTable').each(function() { tables.push(new B3PDataTable(this)); }); jQuery('.postCheckboxTable').click(function() { for(var x in tables) { tables[x].showAllRows(); } }); }); /** * B3P wrapper for the jQuery DataTables plugin * @requires jQuery * @requires jQuery.dataTables * @param {HTMLElement} table * @returns {B3PDataTable} */ function B3PDataTable(table) { /** * Setting to preserve table height even when there are less items * @type boolean */ this.preserveHeight = true; /** * The jQuery object of the table * @type jQuery */ this.table = jQuery(table); /** * Container for the creation of the DataTable object * @type DataTable */ this.dataTableObj = null; /** * Container for the column settings * @type Array */ this.columnSettings = []; /** * Widths for each column * @type Array */ this.columnWidths = []; /** * Header row to hold the filters * @type jQuery */ this.filters = jQuery('<tr class="filter"></tr>'); /** * The selected row object * @type jQuery */ this.selectedRow = this.table.find('.row_selected'); /** * Container for the DataTable settings * @type Object */ this.tableSettings = null; /** * Initializes a B3PDataTable object to create a sortable, filterable DataTable * @returns {Boolean} */ this.init = function() { // We compute the column widths as soon as possible this.columnWidths = this.getColumnWidths(); var filterCount = this.initHeaders(); if(this.preserveHeight) var tableHeight = this.calculatePageHeight(filterCount); var tableSettings = this.initDataTable(); // If there is no saved state (first time view) go to selected row if(tableSettings.oLoadedState === null) { this.showSelectedRow(); } this.appendSelectedRowButton(); if(filterCount !== 0) { this.appendFilters(); } this.initRowClick(); if(this.preserveHeight) this.setWrapperHeight(tableHeight); this.showTable(); return true; }; /** * Calculate the height of the table header and first 10 rows (first page) * @param {int} number of filters * @returns {int} */ this.calculatePageHeight = function(filterCount) { // Border margin of table var borderMargin = 2; // Calc header height var headerHeight = this.table.find('thead').outerHeight(true) + borderMargin; // If there are filters, multiply headerheight by 2 if(filterCount !== 0) headerHeight = headerHeight * 2; // Calc content height var contentHeight = 0; // Use first 10 rows var count = 1; this.table.find('tbody').children().slice(0, 10).each(function() { contentHeight += jQuery(this).outerHeight(true) + borderMargin; }); var tableHeight = headerHeight + contentHeight + 16; // margin; return tableHeight; }; /** * Sets the minimum height of the wrapper, causing the table to preserve height * @param {int} tableHeight * @returns {Boolean} */ this.setWrapperHeight = function(tableHeight) { var wrapper = this.table.parent(); // Calculate height of search box and pagination var childHeight = 0; wrapper.find('.dataTables_filter, .dataTables_paginate').each(function() { childHeight += jQuery(this).outerHeight(true); }); // Move info and pagination to the bottom jQuery('.dataTables_info, .dataTables_paginate').each(function() { var obj = jQuery(this); obj.css({ 'position': 'absolute', 'bottom': '0px' }); if(obj.hasClass('dataTables_paginate')) obj.css('right', '15px'); }); // Set wrapper min-height wrapper.css({ 'min-height': (childHeight + tableHeight - 19 + 'px') // Subtract 19 pixels for wrapper margin }); return true; }; /** * Initializes the headers: create column settings and append a filter. * Returns the amount of filters created. * @returns {int} */ this.initHeaders = function() { var me = this, filterCount = 0; this.table.find('thead tr').first().find('th').each(function(index) { me.columnSettings.push(me.getColumnSettings(this)); var hasFilter = me.createFilter(this, index); if(hasFilter) filterCount++; }); return filterCount; }; /** * Creates a DataTables column settings object based on some options * @param {type} the table header object * @returns {Object} */ this.getColumnSettings = function(column) { var colSetting = {}; var sortType = "string"; if(column.className.match(/sorter\:[ ]?[']?digit[']?/)) { sortType = "numeric"; } if(column.className.match(/sorter\:[ ]?[']?dutchdates[']?/)) { sortType = "dutchdates"; } if(column.className.match(/sorter\:[ ]?[']?false[']?/)) { colSetting.bSortable = false; } colSetting.sType = sortType; colSetting.mRender = function(content, type) { if(type === 'filter') { // Remove all HTML tags from content to improve filtering return content.replace(/<\/?[^>]+>/g, '').trim(); } return content; }; return colSetting; }; /** * Compute the default width of all columns in the table * @returns {Object} */ this.getColumnWidths = function() { var i = 0, me = this, columnWidths = []; // Wrap all td's in the body in a .tablespan class (taking care of text-overflow and set width to 1px) // So we can use the percentages set for the columns as widths this.table.find('tbody td').wrapInner(jQuery('<span class="tablespan" style="width: 1px;"></span>')); // Set the table to the maximum width (wrapper - 30px padding) this.table.css('width', this.table.parent().width() - 30); // Loop over first row and add width of each td to array this.table.find('tbody tr:first-child td').each(function() { columnWidths[i++] = jQuery(this).width(); }); // Reset width of table this.table.css('width', 'auto'); // Return array with column widths return columnWidths; }; /** * Sets width on each column to prevent large texts from pushing table off screen * @returns {Boolean} */ this.setTablecellWidth = function() { var me = this; // Loop over all rows this.table.find('tbody tr').each(function() { // Set index var var i = 0; // Loop over all cells jQuery(this).find('td').each(function() { var td = jQuery(this); // Add tablespan container when td is empty so widths are consistant if(td.is(':empty')) { td.append('<span class="tablespan"></span>'); } // Set the max width td.find('.tablespan').css('width', me.columnWidths[i++]); }); }); return true; }; /** * Creates a filter box for a column. Returns true if a filter is created * @param {type} the table header object * @param {type} the column index * @returns {Boolean} */ this.createFilter = function(column, index) { var me = this, col = jQuery(column); if(col.hasClass('no-filter')) { // Column has no-filter class, so create empty header this.filters.append('<th>&nbsp;</th>'); return false; } else { var filter = jQuery('<input type="text" name="filter" title="' + col.text() + '" value="" />').keyup(function(e) { me.filterColumn(this.value, index); }); var header = jQuery('<th></th>').append(filter); this.filters.append(header); } return true; }; /** * Initializes the DataTables plugin and returns the creation settings * @returns {Object} */ this.initDataTable = function() { var me = this; this.dataTableObj = this.table.dataTable({ "iDisplayLength": 10, "bSortClasses": false, "aoColumns": this.columnSettings, "aaSorting": [], "bStateSave": true, "sPaginationType": "full_numbers", "oLanguage": { "sLengthMenu": "_MENU_ items per pagina", "sSearch": "Zoeken:", "oPaginate": { "sFirst": "Begin", "sNext": "Volgende", "sPrevious": "Vorige", "sLast": "Einde" }, "sInfo": "Items _START_ tot _END_ van _TOTAL_ getoond", "sInfoEmpty": "Geen items gevonden", "sInfoFiltered": " - gefilterd (in totaal _MAX_ items)", "sEmptyTable": "Geen items gevonden", "sZeroRecords": "Geen items gevonden" }, "fnDrawCallback": function() { me.setTablecellWidth(); } }); this.tableSettings = this.dataTableObj.fnSettings(); return this.tableSettings; }; /** * Append the button to go to the selected row to the paginiation * @returns {Boolean} */ this.appendSelectedRowButton = function() { var me = this; me.table.parent().find('.dataTables_paginate').append(jQuery('<a>Geselecteerd</a>').addClass('paginate_button').click(function(e){ e.preventDefault(); me.showSelectedRow(); })); return true; }; /** * Append the filter boxes to the table header * @returns {Boolean} */ this.appendFilters = function() { var me = this; // Get saved searches to repopulate field with search value me.filters.find('th').each(function(index) { var searchCol = me.tableSettings.aoPreSearchCols[index]; if(searchCol.hasOwnProperty('sSearch') && searchCol.sSearch.length !== 0) { jQuery('input', this).val(searchCol.sSearch); } }); // Add filters to table me.table.find('thead').append(me.filters); return true; }; /** * Attach handlers for clicking a row in the table * @returns {Boolean} */ this.initRowClick = function() { this.table.find('tbody').delegate("td", "click", function() { var row = jQuery(this); // Check if there is a link or input (button, checkbox, etc.) present if(row.find('a, input').length === 0) { // No link or input so navigate to the attached URL var link = row.parent().attr('data-link'); if(link) window.location.href = link; } }); return true; }; /** * Search a single column for a string * @param {String} the string to search on * @param {int} the index of the columns that needs to be filtered * @returns {Boolean} */ this.filterColumn = function(filter, colindex) { if(this.dataTableObj === null) return; this.dataTableObj.fnFilter( filter, colindex ); return true; }; /** * Shows the currently selected row * @returns {Boolean} */ this.showSelectedRow = function() { if(this.dataTableObj === null) return false; this.dataTableObj.fnDisplayRow( this.selectedRow[0] ); return true; }; /** * Makes the table visible (table is hidden using CSS and positioning to prevent flicker) * @returns {Boolean} */ this.showTable = function() { this.table.css({ 'position': 'static', 'left': '0px' }); return true; }; /** * Function to show all rows (remove pagination). * This is mainly used to post all input fields in a tables * @returns {Boolean} */ this.showAllRows = function() { var wrapper = this.table.parent(), wrapperHeight = wrapper.height(); wrapper.css({ 'height': wrapperHeight + 'px', 'overflow': 'hidden' }); this.table.css({ 'position': 'absolute', 'left': '-99999px' }); jQuery('<div>Bezig met opslaan...</div>') .css({ 'clear': 'both', 'margin-top': '15px;' }) .insertAfter(jQuery('.dataTables_filter', wrapper)); jQuery('tbody', this.table).append( this.dataTableObj.fnGetHiddenNodes() ); }; /** * Install dataTable extensions, needed for some functionality */ (function() { if(typeof jQuery.fn.dataTableExt.oSort['dutchdates-asc'] === "undefined") { /** * Extension to support sorting of dutch formatted dates (dd-mm-yyyy) */ jQuery.fn.dataTableExt.oSort['dutchdates-asc'] = function(a,b) { var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b)); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; jQuery.fn.dataTableExt.oSort['dutchdates-desc'] = function(a,b) { var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b)); return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }; var parseDutchDate = function(obj) { var s = obj.text(); var hit = s.match(/(\d{2})-(\d{2})-(\d{4})/); if (hit && hit.length === 4) return new Date(hit[3], hit[2], hit[1]); return new Date(s); }; } if(typeof jQuery.fn.dataTableExt.oApi.fnDisplayRow === "undefined") { /** * Extension to go to the page containing a specific row * We use this extension to go to the selected row */ jQuery.fn.dataTableExt.oApi.fnDisplayRow = function ( oSettings, nRow ) { // Account for the "display" all case - row is already displayed if ( oSettings._iDisplayLength === -1 ) return; // Find the node in the table var iPos = -1, iLen=oSettings.aiDisplay.length; for( var i=0; i < iLen; i++ ) { if( oSettings.aoData[ oSettings.aiDisplay[i] ].nTr === nRow ) { iPos = i; break; } } // Alter the start point of the paging display if( iPos >= 0 ) { oSettings._iDisplayStart = ( Math.floor(i / oSettings._iDisplayLength) ) * oSettings._iDisplayLength; this.oApi._fnCalculateEnd( oSettings ); } this.oApi._fnDraw( oSettings ); }; } if(typeof jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes === "undefined") { jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes = function ( oSettings ) { /* Note the use of a DataTables 'private' function thought the 'oApi' object */ var anNodes = this.oApi._fnGetTrNodes( oSettings ); var anDisplay = jQuery('tbody tr', oSettings.nTable); /* Remove nodes which are being displayed */ for ( var i=0 ; i<anDisplay.length ; i++ ) { var iIndex = jQuery.inArray( anDisplay[i], anNodes ); if ( iIndex != -1 ) { anNodes.splice( iIndex, 1 ); } } /* Fire back the array to the caller */ return anNodes; }; } })(); /** * Execute initialize function */ this.init(); }
B3Partners/gisviewerConfig
src/main/webapp/scripts/commonfunctions.js
JavaScript
lgpl-3.0
24,486
if (typeof ui == 'undefined') var ui = {}; ui.Template = { reg_vaild_preceding_chars: '(?:[^-\\/"\':!=a-zA-Z0-9_]|^)', reg_url_path_chars_1: '[a-zA-Z0-9!\\*\';:=\\+\\$/%#\\[\\]\\?\\-_,~\\(\\)&\\.`@]', reg_url_path_chars_2: '[a-zA-Z0-9!\':=\\+\\$/%#~\\(\\)&`@]', reg_url_proto_chars: '([a-zA-Z]+:\\/\\/|www\\.)', reg_user_name_chars: '[@@]([a-zA-Z0-9_]{1,20})', reg_list_name_template: '[@@]([a-zA-Z0-9_]{1,20}/[a-zA-Z][a-zA-Z0-9_\\-\u0080-\u00ff]{0,24})', // from https://si0.twimg.com/c/phoenix/en/bundle/t1-hogan-core.f760c184d1eaaf1cf27535473a7306ef.js reg_hash_tag_latin_chars: '\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u024f\u0253-\u0254\u0256-\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u1e00-\u1eff', reg_hash_tag_nonlatin_chars: '\u0400-\u04ff\u0500-\u0527\u2de0-\u2dff\ua640-\ua69f\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\ufb12-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4f\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06de-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u06ff\u0750-\u077f\u08a0\u08a2-\u08ac\u08e4-\u08fe\ufb50-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\u200c\u0e01-\u0e3a\u0e40-\u0e4e\u1100-\u11ff\u3130-\u3185\ua960-\ua97f\uac00-\ud7af\ud7b0-\ud7ff\uffa1-\uffdc\u30a1-\u30fa\u30fc-\u30fe\uff66-\uff9f\uff70\uff10-\uff19\uff21-\uff3a\uff41-\uff5a\u3041-\u3096\u3099-\u309e\u3400-\u4dbf\u4e00-\u9fff\ua700-\ub73f\ub740-\ub81f\uf800-\ufa1f\u3003\u3005\u303b', reg_hash_tag_template: '(^|\\s)[##]([a-z0-9_{%LATIN_CHARS%}{%NONLATIN_CHARS%}]*)', reg_hash_tag: null, reg_is_rtl: new RegExp('[\u0600-\u06ff]|[\ufe70-\ufeff]|[\ufb50-\ufdff]|[\u0590-\u05ff]'), tweet_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" in_thread="{%IN_THREAD%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_color_label" style="background-color:{%COLOR_LABEL%}"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="tweet_fav_indicator"></div>\ <div class="deleted_mark"></div>\ <div class="tweet_retweet_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who {%RETWEET_MARK%}">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_thread_info" style="display:{%IN_REPLY%}">\ <a class="btn_tweet_thread" href="#"></a>\ {%REPLY_TEXT%}\ </div>\ <div class="tweet_source"> \ {%RETWEET_TEXT%} \ <span class="tweet_timestamp">\ <a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\ </span>\ {%TRANS_via%}: {%SOURCE%}</div>\ <div class="status_bar">{%STATUS_INDICATOR%}</div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ <div class="tweet_thread_wrapper">\ <div class="tweet_thread_hint">{%TRANS_Loading%}</div>\ <ul class="tweet_thread"></ul>\ <a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\ </div>\ </li>', trending_topic_t: '<li id="{%ID%}" class="card" type="trending_topic">\ <div class="profile_img_wrapper trend_topic_number">#{%ID%}</div>\ <div class="card_body keep_height">\ <a class="hash_href trending_topic" href="{%NAME%}">{%NAME%}</a>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', retweeted_by_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="deleted_mark"></div>\ <div class="tweet_fav_indicator"></div>\ <div class="tweet_retweet_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who {%RETWEET_MARK%}">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_thread_info" style="display:{%IN_REPLY%}">\ <a class="btn_tweet_thread" href="#"></a>\ {%REPLY_TEXT%}\ </div>\ <div class="tweet_source"> \ {%RETWEET_TEXT%} \ <span class="tweet_timestamp">\ <a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\ </span>\ {%TRANS_via%}: {%SOURCE%}\ {%TRANS_Retweeted_by%}: <a class="show" href="#" title="{%TRANS_Click_to_show_retweeters%}" tweet_id="{%TWEET_ID%}">{%TRANS_Show_retweeters%}</a>\ </div>\ <div class="tweet_retweeters" tweet_id="{%TWEET_ID%}"></div>\ <div class="status_bar">{%STATUS_INDICATOR%}</div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ <div class="tweet_thread_wrapper">\ <div class="tweet_thread_hint">{%TRANS_Loading%}</div>\ <ul class="tweet_thread"></ul>\ <a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\ </div>\ </li>', message_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="message" sender_screen_name="{%SCREEN_NAME%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_dm_reply_btn" title="Reply them" href="#reply_dm" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">@<a class="who_href" href="#{%RECIPIENT_SCREEN_NAME%}">{%RECIPIENT_SCREEN_NAME%}</a> {%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_source"> \ <span class="tweet_timestamp tweet_update_timestamp" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</span>\ </div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', search_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="search" screen_name="{%SCREEN_NAME%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="deleted_mark"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_source"> \ <span class="tweet_timestamp">\ <a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\ </span>\ {%TRANS_via%}: {%SOURCE%}</div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', people_t: '<li id="{%USER_ID%}" class="people_card card normal" type="people" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li style="display:none;">\ <a class="tweet_bar_btn add_to_list_btn" title="Add to list" href="#follow" data-i18n-title="add_to_list"></a>\ </li><li>\ <a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\ </li><li>\ <a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\ </li>\ </ul>\ <div class="card_body">\ <div id="{%USER_ID%}" class="who">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', people_vcard_t_orig: '<div class="header_frame">\ <div class="people_vcard vcard">\ <a target="_blank" class="profile_img_wrapper"></a>\ <div class="vcard_body">\ <center>\ <ul class="people_vcard_radio_group mochi_button_group"> \ <li><a class="mochi_button_group_item selected" href="#people_vcard_info_page" name="">{%TRANS_info%}</a> \ </li><li><a class="mochi_button_group_item" href="#people_vcard_stat_page">{%TRANS_stat%}</a> \ </li></ul>\ </center>\ <div class="vcard_tabs_pages">\ <table class="people_vcard_info_page vcard_tabs_page radio_group_page" border="0" cellpadding="0" cellspacing="0"> \ <tr><td>{%TRANS_name%}: </td><td> \ <a class="screen_name" target="_blank" href="#"></a> \ (<span class="name"></span>) </td> \ </tr> \ <tr><td>{%TRANS_bio%}: </td> \ <td><span class="bio"></span></td> \ </tr> \ <tr><td>{%TRANS_web%}: </td> \ <td><a class="web" target="_blank" href="#" class="link"></a></td> \ </tr> \ <tr><td>{%TRANS_location%}: </td> \ <td><span class="location"></span></td> \ </tr> \ </table> \ <table class="people_vcard_stat_page vcard_tabs_page radio_group_page"> \ <tr><td>{%TRANS_join%}: </td> \ <td><span class="join"></span></td> \ </tr> \ <tr><td>{%TRANS_tweet_cnt%}: </td> \ <td><span class="tweet_cnt"></span> \ (<span class="tweet_per_day_cnt"></span> per day)</td> \ </tr> \ <tr><td>{%TRANS_follower_cnt%}: </td> \ <td><span class="follower_cnt"></span></td> \ </tr> \ <tr><td>{%TRANS_friend_cnt%}: </td> \ <td><span class="friend_cnt"></span></td> \ </tr> \ <tr><td>{%TRANS_listed_cnt%}: </td> \ <td><span class="listed_cnt"></span></td> \ </tr> \ <tr><td>{%TRANS_relation%}: </td> \ <td><span class="relation"></span></td> \ </tr> \ </table> \ </div><!-- vcard tabs pages --> \ </div> <!-- vcard body --> \ <div class="vcard_ctrl"> \ <ul class="vcard_action_btns"> \ <li><a class="vcard_follow mochi_button blue" \ href="#" >{%TRANS_follow%}</a> \ </li><li> \ <a class="vcard_edit mochi_button" \ href="#" style="display:none;">{%TRANS_edit%}</a>\ </li><li class="people_action_more_trigger"> \ <a class="vcard_more mochi_button" \ href="#">{%TRANS_more_actions%} &#x25BE;</a> \ <ul class="people_action_more_memu hotot_menu">\ <li><a class="mention_menu_item" \ title="Mention them"\ href="#">{%TRANS_mention_them%}</a>\ </li><li><a class="message_menu_item" \ title="Send Message to them"\ href="#">{%TRANS_message_them%}</a>\ </li><li><a class="add_to_list_menu_item" \ title="Add them to a list"\ href="#">{%TRANS_add_to_list%}</a>\ </li><li class="separator"><span></span>\ </li><li><a class="block_menu_item" \ title="Block"\ href="#">{%TRANS_block%}</a>\ </li><li><a class="unblock_menu_item"\ href="#" \ title="Unblock">{%TRANS_unblock%}</a>\ </li><li><a class="report_spam_menu_item" \ href="#" \ title="Report Spam">{%TRANS_report_spam%}</a>\ </li>\ </ul>\ </li> \ </ul> \ </div><!-- #people_vcard_ctrl --> \ </div> <!-- vcard --> \ <div class="expand_wrapper"><a href="#" class="expand">…</a></div>\ <div class="people_view_toggle"> \ <ol class="people_view_toggle_btns mochi_button_group"> \ <li><a class="people_view_tweet_btn mochi_button_group_item selected" href="#tweet">{%TRANS_tweets%}</a> \ </li><li> \ <a class="people_view_fav_btn mochi_button_group_item" href="#fav">{%TRANS_favs%}</a> \ </li><li class="people_view_people_trigger"> \ <a class="people_view_people_btn mochi_button_group_item" href="#people">{%TRANS_fellowship%} &#x25BE;</a> \ <ul class="people_menu hotot_menu">\ <li><a class="followers_menu_item" \ title="People who follow them."\ href="#">{%TRANS_followers%}</a>\ </li><li><a class="friends_menu_item"\ href="People them is following" \ title="All Lists following Them">{%TRANS_friends%}</a>\ </li>\ </ul>\ </li><li class="people_view_list_trigger"> \ <a class="people_view_list_btn mochi_button_group_item" href="#list">{%TRANS_lists%} &#x25BE;\ </a> \ <ul class="lists_menu hotot_menu">\ <li><a class="user_lists_menu_item" \ title="Lists of Them"\ href="#">{%TRANS_lists_of_them%}</a>\ </li><li><a class="listed_lists_menu_item"\ href="#" \ title="All Lists following Them">{%TRANS_lists_following_them%}</a>\ </li><li><a class="create_list_menu_item" \ href="#" \ title="Create A List">{%TRANS_create_a_list%}</a>\ </li>\ </ul>\ </li> \ </ol> \ </div> \ <div class="people_request_hint"> \ <h1 data-i18n-text="he_she_has_protexted_his_her_tweets">He/She has protected his/her tweets.</span></h1> \ <p data-i18n-text="you_need_to_go_to_twitter_com_to_send_a_request_before_you_can_start_following_this_persion">You need to go to twitter.com to send a request before you can start following this person...</p> \ <div style="text-align:center;"> \ <a class="people_request_btn mochi_button" href="#" target="_blank" data-i18n-text="send_request">Send Request</a> \ </div> \ </div></div>', list_t: '<li id="{%LIST_ID%}" class="list_card card normal" type="list" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} slug={%SLUG%} style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="profile_img_wrapper" title="@{%USER_NAME%}/{%SLUG%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\ </li><li>\ <a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\ </li>\ </ul>\ <div class="card_body">\ <div id="{%USER_ID%}" class="who">\ <a class="list_href" href="#{%SCREEN_NAME%}/{%SLUG%}" title="{%USER_NAME%}/{%SLUG%}">\ @{%SCREEN_NAME%}/{%SLUG%}\ </a>\ </div>\ <div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', list_vcard_t: '<div class="header_frame"><div class="list_vcard vcard">\ <a target="_blank" class="profile_img_wrapper"></a>\ <div class="vcard_body">\ <div class="vcard_tabs_pages">\ <table border="0" cellpadding="0" cellspacing="0" class="vcard_tabs_page" style="display:block;"> \ <tr><td data-i18n-text="name">Name: </td><td> \ <a class="name" target="_blank" href="#"></a></td> \ </tr> \ <tr><td>Owner: </td> \ <td><a class="owner" target="_blank" href="#" data-i18n-text="owner"></a></td> \ </tr> \ <tr><td data-i18n-text="description">Description: </td> \ <td><span class="description"></span></td> \ </tr> \ </table> \ </div>\ </div> <!-- vcard body --> \ <div class="vcard_ctrl"> \ <ul class="vcard_action_btns"> \ <li><a class="vcard_follow mochi_button blue" \ href="#" data-i18n-text="follow">Follow</a> \ </li><li> \ <a class="vcard_delete mochi_button red" \ href="#" data-i18n-text="delete">Delete</a> \ </li><li> \ <a class="vcard_edit mochi_button" \ href="#" style="display:none;" data-i18n-text="edit">Edit</a>\ </li> \ </ul> \ </div><!-- #list_vcard_ctrl --> \ </div> <!-- vcard --> \ <div class="expand_wrapper"><a href="#" class="expand">…</a></div>\ <div class="list_view_toggle"> \ <ol class="list_view_toggle_btns mochi_button_group"> \ <li><a class="list_view_tweet_btn mochi_button_group_item selected" href="#tweet" data-i18n-text="tweets">Tweets</a> \ </li><li> \ <a class="list_view_follower_btn mochi_button_group_item" href="#follower" data-i18n-text="followers">Followers</a> \ </li><li> \ <a class="list_view_following_btn mochi_button_group_item" href="#following" data-i18n-text="following">Following</a> \ </li> \ </ol> \ </div> \ <div class="list_lock_hint"> \ <h1 data-i18n-text="he_she_has_protected_his_her_list">He/She has protected his/her list.</span></h1> \ <p data-i18n-text="only_the_owner_can_access_this_list">Only the owner can access this list.</p> \ </div></div>', search_header_t: '<div class="header_frame"> \ <div class="search_box"> \ <input class="search_entry mochi_entry" type="text" placeholder="Type and press enter to search." data-i18n-placeholder="type_and_press_enter_to_search"/> \ <a href="#" class="search_entry_clear_btn"></a>\ <div class="search_people_result"> \ <span data-i18n-text="one_user_matched">One user matched: </span> <span class="search_people_inner"></span>\ </div>\ <div class="saved_searches">\ <a id="create_saved_search_btn" class="mochi_button" \ href="#" title="Detach" data-i18n-title="detach"> +\ </a>\ <div id="saved_searches_more_trigger" style="display:none;">\ <a id="saved_searches_btn" class="vcard_more mochi_button" \ href="#"> &#x25BE;</a> \ <ul id="saved_searches_more_menu" class="hotot_menu">\ <li><a class="" \ title="Clear ALL"\ href="#" data-i18n-title="clear_all" data-i18n-text="clear_all">Clear All</a>\ </li><li class="separator"><span></span>\ </li><li>\ <a class="saved_search_item" href="#">a</a>\ </li>\ </ul>\ </div>\ </div>\ <div class="search_view_toggle">\ <ol class="search_view_toggle_btns mochi_button_group">\ <li><a class="search_tweet mochi_button_group_item selected" \ href="#tweet" data-i18n-text="tweets">Tweet</a>\ </li><li> \ <a class="search_people mochi_button_group_item"\ href="#people" data-i18n-text="people">People</a>\ </li> \ </ol> \ </div> \ <div class="search_no_result_hint"> \ <p><span data-i18n-text="your_search">Your search</span> - <label class="keywords"></label> - <span data-i18n-text="did_not_match_any_result">did not match any result.</span></p> \ <p><span data-i18n-text="suggestions">Suggestions</span>: <br/> \ - <span data-i18n-text="make_sure_all_words_are_spelled_correctly">Make sure all words are spelled correctly.</span><br/> \ - <span data-i18n-text="try_different_keywords">Try different keywords.</span><br/> \ - <span data-i18n-text="try_more_general_keywords">Try more general keywords.</span><br/></p> \ </div> \ </div> \ </div>', retweets_header_t: '<div class="header_frame"><div class="retweets_view_toggle"> \ <ol class="retweets_view_toggle_btns radio_group">\ <li><a class="btn_retweeted_to_me radio_group_btn selected" \ href="#retweeted_to_me" data-i18n-text="by_others">By Others</a>\ </li><li> \ <a class="btn_retweeted_by_me radio_group_btn"\ href="#retweeted_by_me" data-i18n-text="by_me">By Me</a>\ </li><li> \ <a class="btn_retweets_of_me radio_group_btn" \ href="#retweets_of_me" data-i18n-text="my_tweets_retweeted">My Tweets, Retweeted</a> \ </li> \ </ol> \ </div></div>', common_column_header_t: '<div class="column_settings"> \ <ul class="mochi_list dark">\ <li class="mochi_list_item dark"> \ <input type="checkbox" href="#use_auto_update" class="mochi_toggle dark widget"/>\ <label class="label" data-i18n-text="auto_update">Auto Update</label>\ </li>\ <li class="mochi_list_item dark"> \ <input type="checkbox" href="#use_notify" class="mochi_toggle dark widget"/>\ <label class="label" data-i18n-text="notify">Notify</label>\ </li>\ <li class="mochi_list_item dark"> \ <input type="checkbox" href="#use_notify_sound" class="mochi_toggle dark widget"/>\ <label class="label" data-i18n-text="sound">Sound</label>\ </li>\ </ul>\ </div>\ ', view_t: '<div id="{%ID%}" \ name="{%NAME%}" class="listview scrollbar_container {%CLASS%} {%ROLE%}"> \ <div class="scrollbar_track">\ <div class="scrollbar_slot">\ <div class="scrollbar_handle"></div>\ </div>\ </div>\ <div class="scrollbar_content listview_content">\ <div class="listview_header"><div class="header_content">{%HEADER%}</div></div> \ <ul class="listview_body"></ul> \ <div class="listview_footer"> \ <div class="load_more_info"><img src="image/ani_loading_bar.gif"/></div> \ </div> \ </div> \ </div>', indicator_t: '<div class="{%STICK%} {%ROLE%}" name="{%TARGET%}" draggable="true"><a class="indicator_btn" href="#{%TARGET%}" title="{%TITLE%}"><img class="icon" src="{%ICON%}"/><div class="icon_alt" style="background-image: url({%ICON%})"></div></a><span class="shape"></span></div>', kismet_rule_t: '<li><a class="kismet_rule" name="{%NAME%}" type="{%TYPE%}" method="{%METHOD%}"\ disabled="{%DISABLED%}" field="{%FIELD%}" pattern="{%PATTERN%}" \ actions="{%ACTIONS%}" {%ADDITION%} href="#">{%NAME%}</a></li>', status_draft_t: '<li mode="{%MODE%}" reply_to_id="{%REPLY_TO_ID%}" reply_text="{%REPLY_TEXT%}" recipient="{%RECIPIENT%}"><a class="text">{%TEXT%}</a><a class="btn_draft_clear" href="#"></a></li>', preview_link_reg: { 'img.ly': { reg: new RegExp('http:\\/\\/img.ly\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://img.ly/show/thumb/', direct_base: 'http://img.ly/show/full/' }, 'twitpic.com': { reg: new RegExp('http:\\/\\/twitpic.com\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://twitpic.com/show/thumb/' }, 'twitgoo.com': { reg: new RegExp('http:\\/\\/twitgoo.com\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://twitgoo.com/show/thumb/', direct_base: 'http://twitgoo.com/show/img/' }, 'yfrog.com': { reg: new RegExp('http:\\/\\/yfrog.com\\/([a-zA-Z0-9_\\-]+)','g'), tail: '.th.jpg' }, 'moby.to': { reg: new RegExp('http:\\/\\/moby.to\\/([a-zA-Z0-9_\\-]+)','g'), tail: ':thumbnail' }, 'instagr.am': { reg: new RegExp('http:\\/\\/instagr.am\\/p\\/([a-zA-Z0-9_\\-]+)\\/?','g'), tail: 'media?size=m', direct_tail: 'media?size=l' }, 'plixi.com': { reg: new RegExp('http:\\/\\/plixi.com\\/p\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://api.plixi.com/api/tpapi.svc/imagefromurl?size=thumbnail&url=' }, 'picplz.com': { reg: new RegExp('http:\\/\\/picplz.com\\/([a-zA-Z0-9_\\-]+)','g'), tail: '/thumb/' }, 'raw': { reg: new RegExp('[a-zA-Z0-9]+:\\/\\/.+\\/.+\\.(jpg|jpeg|jpe|png|gif)', 'gi') }, 'youtube.com': { reg: new RegExp('href="(http:\\/\\/(www.)?youtube.com\\/watch\\?v\\=([A-Za-z0-9_\\-]+))','g'), base: 'http://img.youtube.com/vi/', tail: '/default.jpg', } }, init: function init() { ui.Template.reg_url = ''//ui.Template.reg_vaild_preceding_chars + '(' + ui.Template.reg_url_proto_chars + ui.Template.reg_url_path_chars_1 + '*' + ui.Template.reg_url_path_chars_2 + '+)'; ui.Template.reg_user = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])' + ui.Template.reg_user_name_chars, 'g'); ui.Template.reg_list = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])' + ui.Template.reg_list_name_template, 'ig'); ui.Template.reg_link = new RegExp(ui.Template.reg_url); ui.Template.reg_link_g = new RegExp(ui.Template.reg_url, 'g'); ui.Template.reg_hash_tag = new RegExp(ui.Template.reg_hash_tag_template .replace(new RegExp('{%LATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_latin_chars) .replace(new RegExp('{%NONLATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_nonlatin_chars) , 'ig'); ui.Template.tweet_m = { ID:'', TWEET_ID:'', RETWEET_ID:'' , REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:'' , PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:'' , IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:'' , RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:'' , DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT: '' , TWEET_LINE_HEIGHT:'' , STATUS_INDICATOR:'', TRANS_Delete:'' , TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:'' , TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:'' , TRANS_Send_Message:'', TRANS_Send_Message_to_them:'' , TRANS_via:'', TRANS_View_more_conversation:'' , TWEET_BASE_URL: '', IN_THREAD: '' , COLOR_LABEL: '' }; ui.Template.trending_topic_m = { ID:'', NAME:'' }; ui.Template.retweeted_by_m = { ID:'', TWEET_ID:'', RETWEET_ID:'' , REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:'' , PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:'' , IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:'' , RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:'' , DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' , STATUS_INDICATOR:'', TRANS_Delete:'' , TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:'' , TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:'' , TRANS_Send_Message:'', TRANS_Send_Message_to_them:'' , TRANS_via:'', TRANS_View_more_conversation:'' , TRANS_retweeted_by:'', TRANS_Show_retweeters:'' , TRANS_Click_to_show_retweeters:'' , TWEET_BASE_URL: '' }; ui.Template.message_m = { ID:'', TWEET_ID:'', SCREEN_NAME:'', RECIPIENT_SCREEN_NAME:'' , USER_NAME:'', PROFILE_IMG:'', TEXT:'' , SCHEME:'', TIMESTAMP:'' , TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' , TRANS_Reply_Them:'' }; ui.Template.search_m = { ID:'', TWEET_ID:'', SCREEN_NAME:'' , USER_NAME:'', PROFILE_IMG:'', TEXT:'', SOURCE:'' , SCHEME:'', SHORT_TIMESTAMP:'', TIMESTAMP:'' , TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' , TRANS_via:'' , TWEET_BASE_URL: '' }; ui.Template.people_m = { USER_ID:'', SCREEN_NAME:'', USER_NAME:'', DESCRIPTION:'' , PROFILE_IMG:'', FOLLOWING:'', TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' }; ui.Template.list_m = { LIST_ID:'', SCREEN_NAME:'', SLUG:'', NAME:'', MODE:'' , DESCRIPTION:'', PROFILE_IMG:'', FOLLOWING:'' , TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' }; ui.Template.view_m = { ID:'', CLASS:'tweetview', NAME: '', CAN_CLOSE: '', ROLE: '' }; ui.Template.indicator_m = { TARGET: '', TITLE: '', ICON: '', ROLE: '' }; ui.Template.kismet_rule_m = { TYPE:'', DISABLED:'', FIELD:'', PATTERN:'' , METHOD:'', ACTIONS: '', ADDITION: '', NAME: '' }; ui.Template.status_draft_m = { MODE:'', TEXT:'', REPLY_TO_ID: '', REPLY_TEXT: '' , RECIPIENT: '' }; ui.Template.update_trans(); }, update_trans: function update_trans() { ui.Template.people_vcard_m = { TRANS_info: _('info'), TRANS_stat: _('stat') , TRANS_name: _('name'), TRANS_bio: _('bio') , TRANS_web: _('web'), TRANS_location: _('location') , TRANS_join: _('join'), TRANS_tweet_cnt: _('tweet_cnt') , TRANS_tweet_cnt: _('tweet_cnt') , TRANS_follower_cnt: _('follower_cnt') , TRANS_friend_cnt: _('friend_cnt') , TRANS_listed_cnt: _('listed_cnt') , TRANS_relation: _('relation') , TRANS_edit: _('edit') , TRANS_follow: _('follow'), TRANS_more_actions: _('more_actions') , TRANS_mention_them: _('mention_them') , TRANS_message_them: _('send_message_to_them') , TRANS_add_to_list: _('add_to_list') , TRANS_block: _('block') , TRANS_unblock: _('unblock') , TRANS_report_spam: _('report_spam') , TRANS_tweets: _('tweets'), TRANS_favs: _('favs') , TRANS_followers: _('followers'), TRANS_friends: _('friends') , TRANS_fellowship: _('fellowship') , TRANS_lists: _('lists'), TRANS_lists_of_them: _('lists_of_them') , TRANS_lists_following_them: _('lists_following_them') , TRANS_create_a_list: _('create_a_list') } ui.Template.people_vcard_t = ui.Template.render(ui.Template.people_vcard_t_orig, ui.Template.people_vcard_m); }, form_dm: function form_dm(dm_obj, pagename) { var timestamp = Date.parse(dm_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); var text = ui.Template.form_text(dm_obj); var m = ui.Template.message_m; m.ID = pagename + '-' + dm_obj.id_str; m.TWEET_ID = dm_obj.id_str; m.SCREEN_NAME = dm_obj.sender.screen_name; m.RECIPIENT_SCREEN_NAME = dm_obj.recipient.screen_name; m.USER_NAME = dm_obj.sender.name; m.DESCRIPTION = dm_obj.sender.description; m.PROFILE_IMG = util.big_avatar(dm_obj.sender.profile_image_url_https); m.TEXT = text; m.SCHEME = 'message'; m.TIMESTAMP = created_at_str; m.SHORT_TIMESTAMP = created_at_short_str; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.TWEET_FONT = globals.tweet_font; m.TRANS_Reply_Them = "Reply Them"; return ui.Template.render(ui.Template.message_t, m); }, // This function returns the html for the given tweet_obj. form_tweet: function form_tweet (tweet_obj, pagename, in_thread) { var retweet_name = ''; var retweet_str = ''; var retweet_id = ''; var id = tweet_obj.id_str; if (tweet_obj.hasOwnProperty('retweeted_status')) { retweet_name = tweet_obj['user']['screen_name']; tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one. tweet_obj = tweet_obj['retweeted_status']; retweet_id = tweet_obj.id_str; } var reply_name = tweet_obj.in_reply_to_screen_name; var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str') ? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id; var reply_str = (reply_id != null) ? _('reply_to') + ' <a class="who_href" href="#' + reply_name + '">' + reply_name + '</a>' : ''; var in_thread = in_thread == true ? true: false; var timestamp = Date.parse(tweet_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); // choose color scheme var scheme = 'normal'; if (tweet_obj.entities && tweet_obj.entities.user_mentions) { for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1) { if (tweet_obj.entities.user_mentions[i].screen_name == globals.myself.screen_name) { scheme = 'mention'; } } } if (tweet_obj.user.screen_name == globals.myself.screen_name) { scheme = 'me'; } if (retweet_name != '') { retweet_str = _('retweeted_by') + ' <a class="who_href" href="#' + retweet_name + '">' + retweet_name + '</a>, '; } var alt_text = tweet_obj.text; var link = ''; if (tweet_obj.entities && tweet_obj.entities.urls) { var urls = null; if (tweet_obj.entities.media) { urls = tweet_obj.entities.urls.concat(tweet_obj.entities.media); } else { urls = tweet_obj.entities.urls; } for (var i = 0, l = urls.length; i < l; i += 1) { var url = urls[i]; if (url.url && url.expanded_url) { tweet_obj.text = tweet_obj.text.replace(url.url, url.expanded_url); } } if (tweet_obj.entities.urls.length > 0) { link = tweet_obj.entities.urls[0].expanded_url; } } var text = ui.Template.form_text(tweet_obj); // if the tweet contains user_mentions (which are provided by the Twitter // API, not by the StatusNet API), it will here replace the // contents of the 'who_ref'-a-tag by the full name of this user. if (tweet_obj.entities && tweet_obj.entities.user_mentions) { for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1) { // hotot_log('form_tweet', 'user mention: ' + tweet_obj.entities.user_mentions[i].screen_name); var screen_name = tweet_obj.entities.user_mentions[i].screen_name; var name = tweet_obj.entities.user_mentions[i].name.replace(/"/g, '&quot;'); var reg_ulink = new RegExp('>(' + screen_name + ')<', 'ig'); text = text.replace(reg_ulink, ' title="' + name + '">$1<') } // If we get here, and there are still <a who_href="...">-tags // without title attribute, the user name was probably misspelled. // If I then remove the tag, the incorrect user name is not // highlighted any more, which fixes #415 for twitter. // (It does not work for identi.ca, because the identi.ca API // does not provide user_mentions.) var re = /\<a class=\"who_href\" href=\"[^"]*\"\>([^<]*)\<\/a\>/gi text = text.replace(re, '$1'); // hotot_log('form_tweet', 'resulting text: ' + text); } var m = ui.Template.tweet_m; m.ID = pagename+'-'+id; m.TWEET_ID = id; m.RETWEET_ID = retweet_id; m.REPLY_ID = reply_id != null? reply_id:''; m.IN_THREAD = in_thread; m.SCREEN_NAME = tweet_obj.user.screen_name; m.REPLY_NAME = reply_id != null? reply_name: ''; m.USER_NAME = tweet_obj.user.name; m.DESCRIPTION = tweet_obj.user.description; m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https); m.TEXT = text; m.ALT = ui.Template.convert_chars(alt_text); m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href'); m.SCHEME = scheme; m.IN_REPLY = (reply_id != null && !in_thread) ? 'block' : 'none'; m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true'; m.COLOR_LABEL = kismet.get_user_color(tweet_obj.user.screen_name); m.REPLY_TEXT = reply_str; m.RETWEET_TEXT = retweet_str; m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': ''; m.SHORT_TIMESTAMP = created_at_short_str; m.TIMESTAMP = created_at_str; m.FAV_CLASS = tweet_obj.favorited? 'faved': ''; m.DELETABLE = scheme == 'me'? 'true': 'false'; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj); m.TRANS_Delete = _('delete'); m.TRANS_Delete_this_tweet = _('delete_this_tweet'); m.TRANS_Loading = _('loading_dots'); m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet'); m.TRANS_Reply_All = _('reply_all'); m.TRANS_Reply_this_tweet = _('reply_this_tweet'); m.TRANS_RT_this_tweet = _('rt_this_tweet'); m.TRANS_Send_Message = _('send_message'); m.TRANS_Send_Message_to_them = _('send_message_to_them'); m.TRANS_via = _('via'); m.TRANS_View_more_conversation = _('view_more_conversation'); m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice'; m.LINK = link; return ui.Template.render(ui.Template.tweet_t, m); }, form_retweeted_by: function form_retweeted_by(tweet_obj, pagename) { var retweet_name = ''; var retweet_str = ''; var retweet_id = ''; var id = tweet_obj.id_str; if (tweet_obj.hasOwnProperty('retweeted_status')) { retweet_name = tweet_obj['user']['screen_name']; tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one. tweet_obj = tweet_obj['retweeted_status']; retweet_id = tweet_obj.id_str; } var reply_name = tweet_obj.in_reply_to_screen_name; var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str') ? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id; var reply_str = (reply_id != null) ? _('Reply to @') + ' <a class="who_href" href="#' + reply_name + '">' + reply_name + '</a>: ' : ''; var timestamp = Date.parse(tweet_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); // choose color scheme var scheme = 'normal'; if (tweet_obj.entities && tweet_obj.entities.user_mentions) { for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1) { if (tweet_obj.entities.user_mentions[i].screen_name == globals.myself.screen_name) { scheme = 'mention'; } } } if (tweet_obj.user.screen_name == globals.myself.screen_name) { scheme = 'me'; } if (retweet_name != '') { retweet_str = _('retweeted_by') + ' <a class="who_href" href="#' + retweet_name + '">' + retweet_name + '</a>, '; } var m = ui.Template.retweeted_by_m; m.ID = pagename+'-'+id; m.TWEET_ID = id; m.RETWEET_ID = retweet_id; m.REPLY_ID = reply_id != null? reply_id:''; m.SCREEN_NAME = tweet_obj.user.screen_name; m.REPLY_NAME = reply_id != null? reply_name: ''; m.USER_NAME = tweet_obj.user.name; m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https); m.TEXT = ui.Template.form_text(tweet_obj); m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href'); m.SCHEME = scheme; m.IN_REPLY = (reply_id != null && pagename.split('-').length < 2) ? 'block' : 'none'; m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true'; m.REPLY_TEXT = reply_str; m.RETWEET_TEXT = retweet_str; m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': ''; m.SHORT_TIMESTAMP = created_at_short_str; m.TIMESTAMP = created_at_str; m.FAV_CLASS = tweet_obj.favorited? 'faved': ''; m.DELETABLE = scheme == 'me'? 'true': 'false'; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj); m.TRANS_Delete = _('delete'); m.TRANS_Delete_this_tweet = _('delete_this_tweet'); m.TRANS_Loading = _('loading_dots'); m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet'); m.TRANS_Reply_All = _('reply_All'); m.TRANS_Reply_this_tweet = _('reply_this_tweet'); m.TRANS_RT_this_tweet = _('rt_this_tweet'); m.TRANS_Send_Message = _('send_message'); m.TRANS_Send_Message_to_them = _('send_message_to_them'); m.TRANS_via = _('via'); m.TRANS_View_more_conversation = _('view_more_conversation'); m.TRANS_Retweeted_by = _('retweeted_by'); m.TRANS_Show_retweeters = _('click_to_show'); m.TRANS_Click_to_show_retweeters = _('click_to_show_retweeters'); m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice'; return ui.Template.render(ui.Template.retweeted_by_t, m); }, form_search: function form_search(tweet_obj, pagename) { if (tweet_obj.user != undefined) { // use phoenix_search ... well, in fact, the original parser is totally useless. return ui.Template.form_tweet(tweet_obj, pagename); } var id = tweet_obj.id_str; var source = tweet_obj.source.replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&quot;/g, ''); var timestamp = Date.parse(tweet_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); var text = ui.Template.form_text(tweet_obj); // choose color scheme var scheme = 'normal'; if (text.indexOf(globals.myself.screen_name) != -1) { scheme = 'mention'; } if (tweet_obj.from_user == globals.myself.screen_name) { scheme = 'me'; } var link = ''; if (tweet_obj.entities.urls.length > 0) { link = tweet_obj.entities.urls[0].expanded_url; } var m = ui.Template.search_m; m.ID = pagename + '-' + id; m.TWEET_ID = id; m.SCREEN_NAME = tweet_obj.from_user; m.USER_NAME = tweet_obj.from_user_name; m.PROFILE_IMG = util.big_avatar(tweet_obj.profile_image_url_https); m.TEXT = text; m.SOURCE = source.replace('href', 'target="_blank" href'); m.SCHEME = scheme; m.SHORT_TIMESTAMP = created_at_short_str; m.TIMESTAMP = created_at_str; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.TRANS_via = _('via'); m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.from_user + '/status':'https://identi.ca/notice'; m.LINK = link; return ui.Template.render(ui.Template.search_t, m); }, form_people: function form_people(user_obj, pagename) { var m = ui.Template.people_m; m.USER_ID = pagename + '-' + user_obj.id_str; m.SCREEN_NAME = user_obj.screen_name; m.USER_NAME = user_obj.name; m.DESCRIPTION = user_obj.description; m.PROFILE_IMG = util.big_avatar(user_obj.profile_image_url_https); m.FOLLOWING = user_obj.following; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; return ui.Template.render(ui.Template.people_t, m); }, form_list: function form_people(list_obj, pagename) { var m = ui.Template.list_m; m.LIST_ID = pagename + '-' + list_obj.id_str; m.SCREEN_NAME = list_obj.user.screen_name; m.SLUG = list_obj.slug; m.NAME = list_obj.name; m.MODE = list_obj.mode; m.DESCRIPTION = list_obj.description; m.PROFILE_IMG = util.big_avatar(list_obj.user.profile_image_url_https); m.FOLLOWING = list_obj.following; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; return ui.Template.render(ui.Template.list_t, m); }, form_view: function form_view(name, title, cls) { var m = ui.Template.view_m; m.ID = name + '_tweetview'; m.NAME = name; m.CLASS = cls; if (name == 'home') { m.CAN_CLOSE = 'none'; } else { m.CAN_CLOSE = 'block'; } if (ui.Slider.system_views.hasOwnProperty(name)) { m.ROLE = 'system_view'; } else { m.ROLE = 'custom_view'; } return ui.Template.render(ui.Template.view_t, m); }, form_indicator: function form_indicator(target, title, icon) { var m = ui.Template.indicator_m; m.TARGET = target m.TITLE = title; m.ICON = icon; if (ui.Slider.system_views.hasOwnProperty(target)) { m.ROLE = 'system_view'; } else { m.ROLE = 'custom_view'; } return ui.Template.render(ui.Template.indicator_t, m); }, form_kismet_rule: function form_kismet_rule(rule) { var m = ui.Template.kismet_rule_m; m.NAME = rule.name; m.TYPE = rule.type; m.METHOD = rule.method; m.PATTERN = rule.pattern; m.ACTIONS = rule.actions.join(':'); m.ADDITION = rule.actions.indexOf(3)!=-1?'archive_name="'+rule.archive_name+'"':'archive_name=""'; m.FIELD = rule.field; m.DISABLED = rule.disabled; return ui.Template.render(ui.Template.kismet_rule_t, m); }, form_status_draft: function form_status_draft(draft) { var m = ui.Template.status_draft_m; m.MODE = draft.mode; m.TEXT = draft.text.replace(/</g, "&lt;").replace(/>/g,"&gt;"); if (m.MODE == ui.StatusBox.MODE_REPLY) { m.REPLY_TO_ID = draft.reply_to_id; m.REPLY_TEXT = draft.reply_text } else if (m.MODE == ui.StatusBox.MODE_DM) { m.RECIPIENT = draft.recipient; } else if (m.MODE == ui.StatusBox.MODE_IMG) { } return ui.Template.render(ui.Template.status_draft_t, m); }, fill_people_vcard: function fill_people_vcard(user_obj, vcard_container) { var created_at = new Date(Date.parse(user_obj.created_at)); var now = new Date(); var differ = Math.floor((now-created_at)/(1000 * 60 * 60 * 24)); var created_at_str = ui.Template.to_long_time_string(created_at); vcard_container.find('.profile_img_wrapper') .attr('href', user_obj.profile_image_url_https.replace(/_normal/, '')) .attr('style', 'background-image:url('+util.big_avatar(user_obj.profile_image_url_https)+');'); vcard_container.find('.screen_name') .attr('href', conf.get_current_profile().preferences.base_url + user_obj.screen_name) .text(user_obj.screen_name); vcard_container.find('.name').text(user_obj.name); vcard_container.find('.tweet_cnt').text(user_obj.statuses_count); vcard_container.find('.tweet_per_day_cnt').text( Math.round(user_obj.statuses_count / differ * 100)/ 100); vcard_container.find('.follower_cnt').text(user_obj.followers_count); vcard_container.find('.friend_cnt').text(user_obj.friends_count); vcard_container.find('.listed_cnt').text(user_obj.listed_count); vcard_container.find('.bio').unbind().empty().html( ui.Template.form_text_raw(user_obj.description)); ui.Main.bind_tweet_text_action(vcard_container.find('.bio')); vcard_container.find('.location').text('').text(user_obj.location); vcard_container.find('.join').text(created_at_str); if (user_obj.url) { vcard_container.find('.web').text(user_obj.url) vcard_container.find('.web').attr('href', user_obj.url); } else { vcard_container.find('.web').text('') vcard_container.find('.web').attr('href', '#'); } vcard_container.find('.people_vcard_radio_group .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_vcard') vcard_container.find('.people_view_toggle .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_views') }, fill_list_vcard: function fill_list_vcard(view, list_obj) { var vcard_container = view._header; vcard_container.find('.profile_img_wrapper') .attr('style', 'background-image:url(' + util.big_avatar(list_obj.user.profile_image_url_https) + ');'); vcard_container.find('.name') .attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name + '/' + list_obj.slug) .text(list_obj.full_name); vcard_container.find('.owner') .attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name) .text(list_obj.user.screen_name); vcard_container.find('.description').text(list_obj.description); }, convert_chars: function convert_chars(text) { text = text.replace(/"/g, '&#34;'); text = text.replace(/'/g, '&#39;'); text = text.replace(/\$/g, '&#36;'); return text; }, // This function applies some basic replacements to tweet.text, and returns // the resulting string. // This is not the final text that will appear in the UI, form_tweet will also do // some modifications. from_tweet will search for the a-tags added in this // function, to do the modifications. form_text: function form_text(tweet) { //hotot_log('form_text in', tweet.text); var text = ui.Template.convert_chars(tweet.text); text = text.replace(ui.Template.reg_link_g, function replace_url(url) { if (url.length > 51) url_short = url.substring(0,48) + '...'; else url_short = url; return ' <a href="'+url+'" target="_blank">' + url_short + '</a>'; }); text = text.replace(/href="www/g, 'href="http://www'); text = text.replace(ui.Template.reg_list , '$1@<a class="list_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_user , '$1@<a class="who_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_hash_tag , '$1<a class="hash_href" href="#$2">#$2</a>'); text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g , 'full_text_id="$2" href="$1"'); text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n'); text = text.replace(/\n/g, '<br/>'); if (ui.Template.reg_is_rtl.test(text)) { text = '<div class="text_inner" align="right" dir="rtl">' + text + '</div>'; } else { text = '<div class="text_inner">' + text + '</div>'; } if (conf.get_current_profile().preferences.use_media_preview) { text += '<div class="preview">' + ui.Template.form_preview(tweet) + '</div>'; } //hotot_log('form_text out', text); return text; }, form_text_raw: function form_text_raw(raw_text) { var text = raw_text; text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); text = text.replace(ui.Template.reg_link_g, ' <a href="$1" target="_blank">$1</a>'); text = text.replace(/href="www/g, 'href="http://www'); text = text.replace(ui.Template.reg_list , '$1@<a class="list_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_user , '$1@<a class="who_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_hash_tag , '$1<a class="hash_href" href="#$2">#$2</a>'); text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g , 'full_text_id="$2" href="$1"'); text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n'); text = text.replace(/\n/g, '<br/>'); return text; }, form_media: function form_media(href, src, direct_url) { if (direct_url != undefined) { return '<a direct_url="'+direct_url+'" href="'+href+'"><img src="'+ src +'" /></a>'; } else { return '<a href="'+href+'" target="_blank"><img src="'+ src +'" /></a>'; } }, form_preview: function form_preview(tweet) { var html_arr = []; var link_reg = ui.Template.preview_link_reg; for (var pvd_name in link_reg) { var match = link_reg[pvd_name].reg.exec(tweet.text); while (match != null) { switch (pvd_name) { case 'img.ly': case 'twitgoo.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base + match[1], link_reg[pvd_name].direct_base + match[1])); break; case 'twitpic.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base + match[1])); break; case 'instagr.am': html_arr.push( ui.Template.form_media( match[0], match[0] + link_reg[pvd_name].tail, match[0] + link_reg[pvd_name].direct_tail)); break; case 'yfrog.com': case 'moby.to': case 'picplz.com': html_arr.push( ui.Template.form_media( match[0], match[0] + link_reg[pvd_name].tail)); break; case 'plixi.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base +match[0])); break; case 'raw': html_arr.push( ui.Template.form_media( match[0], match[0], match[0])); break; case 'youtube.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base + match[2] + link_reg[pvd_name].tail)); break; } match = link_reg[pvd_name].reg.exec(tweet.text); } } // twitter official picture service if (tweet.entities && tweet.entities.media) { for (var i = 0; i < tweet.entities.media.length; i += 1) { var media = tweet.entities.media[i]; if (media.expanded_url && media.media_url) { html_arr.push( ui.Template.form_media( tweet.entities.media[i].expanded_url, tweet.entities.media[i].media_url + ':thumb', tweet.entities.media[i].media_url + ':large' )); } } } if (conf.get_current_profile().preferences.filter_nsfw_media && tweet.text.match(/nsfw/ig)) html_arr = ['<i>NSFW image hidden</i>']; if (html_arr.length != 0) { return '<p class="media_preview">'+ html_arr.join('')+'</p>'; } return ''; }, form_status_indicators: function form_status_indicators(tweet) { }, render: function render(tpl, map) { var text = tpl var replace = false; for (var k in map) { replace = typeof map[k] == 'string' ? map[k] : ''; text = text.replace(new RegExp('{%'+k+'%}', 'g'), replace); } return text; }, to_long_time_string: function (datetime) { return moment(datetime).toLocaleString(); }, to_short_time_string: function (dataObj) { var is_human = conf.get_current_profile().preferences.show_relative_timestamp, now = moment(), mobj = moment(dataObj), time_str; if (is_human) { try { mobj.lang(i18n.current); mobj.lang(); } catch (e) { mobj.lang(false); } if(now.diff(mobj, 'hours', true) > 6) { time_str = mobj.calendar(); } else { time_str = mobj.fromNow(); } } else { if(now.diff(mobj, 'days', true) > 1) { time_str = mobj.format('YYYY-MM-DD HH:mm:ss'); } else { time_str = mobj.format('YYYY-MM-DD HH:mm:ss'); } } return time_str; } }
AshKyd/Hotot
data/js/ui.template.js
JavaScript
lgpl-3.0
59,989
var default_window_options = { autoOpen: false, width: 750, height: 450, modal: true, resizable: false }; function applyNotificationStyles() { $('.error').each(function() { $(this).addClass('ui-state-error ui-corner-all'); $(this).prepend('<span class="ui-icon ui-icon-alert"></span>'); }); $('.notification').each(function() { $(this).addClass('ui-state-highlight ui-corner-all'); $(this).prepend('<span class="ui-icon ui-icon-info"></span>'); }); } $(function() { // Hard-coded paths aren't great... Maybe re-work this in the future var divider = "url('" + media_url + "img/navigation_divider.png')"; $('#navigation ul.menu li:has(ul.submenu)').hover(function() { $(this).addClass('has-submenu'); $(this).children('a.menu-link').css('background-image', 'none'); $(this).prev('li').children('a.menu-link').css('background-image', 'none'); $(this).children('ul').show(); }, function() { $(this).removeClass('has-submenu'); $(this).children('a.menu-link').css('background-image', divider); $(this).prev('li').children('a.menu-link').css('background-image', divider); $(this).children('ul').hide(); }); $('#navigation ul.submenu a').click(function() { $(this).parents('ul.submenu').hide(); }); // Style form buttons $('input[type=button], input[type=submit], input[type=reset]').button(); // Style error and notification messages applyNotificationStyles(); });
mariajosefrancolugo/osp
osp/media/js/base.js
JavaScript
lgpl-3.0
1,553
let idCounter = 0; function nextId() { return ++idCounter; } // if the platform throws an exception, the worker will kill & restart it, however if a callback comes in there could // be a race condition which tries to still access session functions which have already been terminated by the worker. // this function wrapper only calls the session functions if they still exist. function referenceProtection(session) { if (typeof session === 'undefined') { throw new Error('session object not provided'); } function checkScope(funcName) { return (msg) => { if (typeof session[funcName] === 'function') { session[funcName](msg); } } } return { actor: session.actor, debug: checkScope('debug'), sendToClient: checkScope('sendToClient') } } class IncomingHandlers { constructor(session) { this.session = referenceProtection(session); } buddy(from, state, statusText) { if (from !== this.session.actor['@id']) { this.session.debug('received buddy presence update: ' + from + ' - ' + state); this.session.sendToClient({ '@type': 'update', actor: { '@id': from }, target: this.session.actor, object: { '@type': 'presence', status: statusText, presence: state } }); } } buddyCapabilities(id, capabilities) { this.session.debug('received buddyCapabilities: ' + id); } chat(from, message) { this.session.debug("received chat message from " + from); this.session.sendToClient({ '@type': 'send', actor: { '@type': 'person', '@id': from }, target: this.session.actor, object: { '@type': 'message', content: message, '@id': nextId() } }); } chatstate(from, name) { this.session.debug('received chatstate event: ' + from, name); } close() { this.session.debug('received close event with no handler specified'); this.session.sendToClient({ '@type': 'close', actor: this.session.actor, target: this.session.actor }); this.session.debug('**** xmpp this.session.for ' + this.session.actor['@id'] + ' closed'); this.session.connection.disconnect(); } error(error) { try { this.session.debug("*** XMPP ERROR (rl): " + error); this.session.sendToClient({ '@type': 'error', object: { '@type': 'error', content: error } }); } catch (e) { this.session.debug('*** XMPP ERROR (rl catch): ', e); } } groupBuddy(id, groupBuddy, state, statusText) { this.session.debug('received groupbuddy event: ' + id); this.session.sendToClient({ '@type': 'update', actor: { '@id': `${id}/${groupBuddy}`, '@type': 'person', displayName: groupBuddy }, target: { '@id': id, '@type': 'room' }, object: { '@type': 'presence', status: statusText, presence: state } }); } groupChat(room, from, message, stamp) { this.session.debug('received groupchat event: ' + room, from, message, stamp); this.session.sendToClient({ '@type': 'send', actor: { '@type': 'person', '@id': from }, target: { '@type': 'room', '@id': room }, object: { '@type': 'message', content: message, '@id': nextId() } }); } online() { this.session.debug('online'); this.session.debug('reconnectioned ' + this.session.actor['@id']); } subscribe(from) { this.session.debug('received subscribe request from ' + from); this.session.sendToClient({ '@type': "request-friend", actor: { '@id': from }, target: this.session.actor }); } unsubscribe(from) { this.session.debug('received unsubscribe request from ' + from); this.session.sendToClient({ '@type': "remove-friend", actor: { '@id': from }, target: this.session.actor }); } /** * Handles all unknown conditions that we don't have an explicit handler for **/ __stanza(stanza) { // simple-xmpp currently doesn't seem to handle error state presence so we'll do it here for now. // TODO: consider moving this.session.to simple-xmpp once it's ironed out and proven to work well. if ((stanza.attrs.type === 'error')) { const error = stanza.getChild('error'); let message = stanza.toString(); let type = 'message'; if (stanza.is('presence')) { type = 'update'; } if (error) { message = error.toString(); if (error.getChild('remote-server-not-found')) { // when we get this.session.type of return message, we know it was a response from a join type = 'join'; message = 'remote server not found ' + stanza.attrs.from; } } this.session.sendToClient({ '@type': type, actor: { '@id': stanza.attrs.from, '@type': 'room' }, object: { '@type': 'error', // type error content: message }, target: { '@id': stanza.attrs.to, '@type': 'person' } }); } else if (stanza.is('iq')) { if (stanza.attrs.id === 'muc_id' && stanza.attrs.type === 'result') { this.session.debug('got room attendance list'); this.roomAttendance(stanza); return; } const query = stanza.getChild('query'); if (query) { const entries = query.getChildren('item'); for (let e in entries) { if (! entries.hasOwnProperty(e)) { continue; } this.session.debug('STANZA ATTRS: ', entries[e].attrs); if (entries[e].attrs.subscription === 'both') { this.session.sendToClient({ '@type': 'update', actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name }, target: this.session.actor, object: { '@type': 'presence', status: '', presence: state } }); } else if ((entries[e].attrs.subscription === 'from') && (entries[e].attrs.ask) && (entries[e].attrs.ask === 'subscribe')) { this.session.sendToClient({ '@type': 'update', actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name }, target: this.session.actor, object: { '@type': 'presence', statusText: '', presence: 'notauthorized' } }); } else { /** * cant figure out how to know if one of these query stanzas are from * added contacts or pending requests */ this.session.sendToClient({ '@type': 'request-friend', actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name }, target: this.session.actor }); } } } // } else { // this.session.debug("got XMPP unknown stanza... " + stanza); } } roomAttendance(stanza) { const query = stanza.getChild('query'); if (query) { let members = []; const entries = query.getChildren('item'); for (let e in entries) { if (!entries.hasOwnProperty(e)) { continue; } members.push(entries[e].attrs.name); } this.session.sendToClient({ '@type': 'observe', actor: { '@id': stanza.attrs.from, '@type': 'room' }, target: { '@id': stanza.attrs.to, '@type': 'person' }, object: { '@type': 'attendance', members: members } }); } } } module.exports = IncomingHandlers;
sockethub/sockethub-platform-xmpp
lib/incoming-handlers.js
JavaScript
lgpl-3.0
7,988
/** * Gulp Task HTML * @author kuakman <[email protected]> **/ let fs = require('fs-extra'); let _ = require('underscore'); let spawnSync = require('child_process').spawnSync; module.exports = function(package, args) { return () => { return spawnSync('./node_modules/.bin/pug', [ '--path', './src/html', '--out', './dist', '--obj', `\'${JSON.stringify(_.pick(package, 'name', 'version', 'profile'))}\'`, '--pretty', './src/html' ], { cwd: process.cwd(), stdio: 'inherit', shell: true }); }; };
kuakman/app-start-pipeline
scripts/html.js
JavaScript
unlicense
526
function nSplit(msg, n) { let expr = new RegExp(".{1," + n + "}", "g"); let presplit = msg.match(expr); let twoSplit = presplit.map((x) => { if (x.length != n) { let i = 0; let ret = ""; while (i < n - x.length) { ret += " "; i++ }; return x + ret; } else return x; }); return twoSplit; } function backSwap(msg) { let newBw = ""; let newFw = ""; let newArr = []; for (let fw = 0; fw < msg.length; fw++) { let bw = msg.length - (fw + 1); let myFw = msg[fw]; let myBw = msg[bw]; newFw = myBw[0] + myFw.slice(1); newBw = myFw[0] + myBw.slice(1); newArr[fw] = newFw; newArr[bw] = newBw; // console.log(fw, newFw, bw, newBw); if (bw <= fw) break; } return newArr; } function encode(msg, n) { let comp_msg = msg.split(' ').join(''); let split_msg = nSplit(comp_msg, n); return backSwap(split_msg); } // var myLoveMsg = "Dear Jade, I love you so much! Lets go on adventures & make memories."; var myLoveMsg = "Ja de Il ov ey ou so mu ch .Y ou ar ew on de rf ul an da ma zi ng in so ma ny wa ys .Y ou ar et ru ly sp ec ia lt om eb ee b an dl ho pe we ca ns up po rt ea ch ot he ra nd be tw ee nu sd oa ma zi ng th in gs ❤"; // var rvLoveMsg = "se ir oa ee eI ao &e eo us nm vc a! oe gs to Ln hd ue ot ur ys vm lk ,m dm Jr ae D."; var rvLoveMsg = ".a ge il tv ny zu mo ou sh nY eu tr bw nn re hf ol cn ea ra pi ug nn co wa py ha ds aY bu er et ou ly ip ec sa lt rm eb ae o, .n yl wo ne me sa is np zo mt da ah ut re da od ee aw oe .u cd ma sa oi eg oh In ds J❤"; var nwsMsg = myLoveMsg.split(' ').join(''); var nwsrvMsg = rvLoveMsg.split(' ').join(''); var myCode = nSplit(myLoveMsg, 2); var nwsCode = nSplit(nwsMsg, 2); var nwsrvCode = nSplit(nwsrvMsg, 2); var bsmyCode = backSwap(myCode); var bsmynwsCode = backSwap(nwsCode); var bsmynwsrvCode = backSwap(nwsrvCode); console.log(myLoveMsg); // console.log(myCode.join(' ')); // console.log(bsmyCode.join(' ')); console.log(nwsCode.join(' ')); console.log(bsmynwsCode.join(' ')); console.log(nwsrvCode.join(' ')); console.log(bsmynwsrvCode.join(' ')); // let myText = encode("Hello Dawg, HEllo DAWGDJLKSAD", 2); // console.log(myText.join(' '));
ConflictingTheories/scripts
javascript/lib/nSplit.js
JavaScript
unlicense
2,366
#!/usr/local/bin/elev8 var EXPAND_BOTH = { x : 1.0, y : 1.0 }; var FILL_BOTH = { x : -1.0, y : -1.0 }; var logo_icon = elm.Icon ({ image : elm.datadir + "data/images/logo_small.png", }); var logo_icon_unscaled = elm.Icon ({ image : elm.datadir + "data/images/logo_small.png", resizable_up : false, resizable_down : false, }); var desc = elm.Window({ title : "Radios demo", elements : { the_background : elm.Background ({ weight : EXPAND_BOTH, resize : true, }), radio_box : elm.Box ({ weight : EXPAND_BOTH, resize : true, elements : { sized_radio_icon : elm.Radio ({ icon : logo_icon, label : "Icon sized to radio", weight : EXPAND_BOTH, align : { x : 1.0, y : 0.5 }, value : 0, group : "rdg", }), unscaled_radio_icon : elm.Radio ({ icon : logo_icon_unscaled, label : "Icon no scale", weight : EXPAND_BOTH, align : { x : 1.0, y : 0.5 }, value : 1, group : "rdg", }), label_only_radio : elm.Radio ({ label : "Label Only", value : 2, group : "rdg", }), disabled_radio : elm.Radio ({ label : "Disabled", enabled : false, value : 3, group : "rdg", }), icon_radio : elm.Radio ({ icon : logo_icon_unscaled, value : 4, group : "rdg", }), disabled_icon_radio : elm.Radio ({ enabled : false, icon : logo_icon_unscaled, value : 5, group : "rdg", }), }, }), }, }); var win = elm.realise(desc);
maikodaraine/EnlightenmentUbuntu
bindings/elev8/data/javascript/radio.js
JavaScript
unlicense
2,132
$.extend(window.lang_fa, { "helpStop": "متوقف کردن آموزش", });
trollderius/wouldyourather_phonegap
www/~commons/modules/tutorial/lang/fa.js
JavaScript
unlicense
76
'use strict'; function ProfileSearch(injector) { var service = this; service.list = function(params) { var connection = injector.connection; var ProfileModel = injector.ProfileModel; var profileSearch = new ProfileModel(); var page = params.page || 1; var where = params.where || []; var order = params.order || []; var limit = params.limit || 10; var fields = params.fields || profileSearch.fields; profileSearch.page = page; profileSearch.order = order; profileSearch.where = where; profileSearch.limit = limit; profileSearch.fields = fields; connection.search(profileSearch); }; } module.exports = ProfileSearch;
luiz-simples/kauris
server/src/profile/profile.search.js
JavaScript
unlicense
703
var net = require('net') var chatServer = net.createServer(), clientList = [] chatServer.on('connection', function(client) { client.name = client.remoteAddress + ':' + client.remotePort client.write('Hi ' + client.name + '!\n'); console.log(client.name + ' joined') clientList.push(client) client.on('data', function(data) { broadcast(data, client) }) client.on('end', function(data) { console.log(client.name + ' quit') clientList.splice(clientList.indexOf(client), 1) }) client.on('error', function(e) { console.log(e) }) }) function broadcast(message, client) { for(var i=0;i<clientList.length;i+=1) { if(client !== clientList[i]) { if(clientList[i].writable) { clientList[i].write(client.name + " says " + message) } else { cleanup.push(clientList[i]) clientList[i].destroy() } } } } chatServer.listen(9000)
mattcoffey/node.js
chatServer.js
JavaScript
unlicense
1,002
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['sap/ui/model/FormatException', 'sap/ui/model/odata/type/ODataType', 'sap/ui/model/ParseException', 'sap/ui/model/ValidateException'], function(FormatException, ODataType, ParseException, ValidateException) { "use strict"; var rGuid = /^[A-F0-9]{8}-([A-F0-9]{4}-){3}[A-F0-9]{12}$/i; /** * Returns the locale-dependent error message. * * @returns {string} * the locale-dependent error message. * @private */ function getErrorMessage() { return sap.ui.getCore().getLibraryResourceBundle().getText("EnterGuid"); } /** * Sets the constraints. * * @param {sap.ui.model.odata.type.Guid} oType * the type instance * @param {object} [oConstraints] * constraints, see {@link #constructor} */ function setConstraints(oType, oConstraints) { var vNullable = oConstraints && oConstraints.nullable; oType.oConstraints = undefined; if (vNullable === false || vNullable === "false") { oType.oConstraints = {nullable: false}; } else if (vNullable !== undefined && vNullable !== true && vNullable !== "true") { jQuery.sap.log.warning("Illegal nullable: " + vNullable, null, oType.getName()); } } /** * Constructor for an OData primitive type <code>Edm.Guid</code>. * * @class This class represents the OData primitive type <a * href="http://www.odata.org/documentation/odata-version-2-0/overview#AbstractTypeSystem"> * <code>Edm.Guid</code></a>. * * In {@link sap.ui.model.odata.v2.ODataModel ODataModel} this type is represented as a * <code>string</code>. * * @extends sap.ui.model.odata.type.ODataType * * @author SAP SE * @version 1.28.10 * * @alias sap.ui.model.odata.type.Guid * @param {object} [oFormatOptions] * format options as defined in the interface of {@link sap.ui.model.SimpleType}; this * type ignores them since it does not support any format options * @param {object} [oConstraints] * constraints; {@link #validateValue validateValue} throws an error if any constraint is * violated * @param {boolean|string} [oConstraints.nullable=true] * if <code>true</code>, the value <code>null</code> is accepted * @public * @since 1.27.0 */ var EdmGuid = ODataType.extend("sap.ui.model.odata.type.Guid", /** @lends sap.ui.model.odata.type.Guid.prototype */ { constructor : function (oFormatOptions, oConstraints) { ODataType.apply(this, arguments); setConstraints(this, oConstraints); } } ); /** * Formats the given value to the given target type. * * @param {string} sValue * the value to be formatted * @param {string} sTargetType * the target type; may be "any" or "string". * See {@link sap.ui.model.odata.type} for more information. * @returns {string} * the formatted output value in the target type; <code>undefined</code> or <code>null</code> * are formatted to <code>null</code> * @throws {sap.ui.model.FormatException} * if <code>sTargetType</code> is unsupported * @public */ EdmGuid.prototype.formatValue = function(sValue, sTargetType) { if (sValue === undefined || sValue === null) { return null; } if (sTargetType === "string" || sTargetType === "any") { return sValue; } throw new FormatException("Don't know how to format " + this.getName() + " to " + sTargetType); }; /** * Returns the type's name. * * @returns {string} * the type's name * @public */ EdmGuid.prototype.getName = function () { return "sap.ui.model.odata.type.Guid"; }; /** * Parses the given value to a GUID. * * @param {string} sValue * the value to be parsed, maps <code>""</code> to <code>null</code> * @param {string} sSourceType * the source type (the expected type of <code>sValue</code>); must be "string". * See {@link sap.ui.model.odata.type} for more information. * @returns {string} * the parsed value * @throws {sap.ui.model.ParseException} * if <code>sSourceType</code> is unsupported * @public */ EdmGuid.prototype.parseValue = function (sValue, sSourceType) { var sResult; if (sValue === "" || sValue === null) { return null; } if (sSourceType !== "string") { throw new ParseException("Don't know how to parse " + this.getName() + " from " + sSourceType); } // remove all whitespaces and separators sResult = sValue.replace(/[-\s]/g, ''); if (sResult.length != 32) { // don't try to add separators to invalid value return sValue; } sResult = sResult.slice(0, 8) + '-' + sResult.slice(8, 12) + '-' + sResult.slice(12, 16) + '-' + sResult.slice(16, 20) + '-' + sResult.slice(20); return sResult.toUpperCase(); }; /** * Validates whether the given value in model representation is valid and meets the * given constraints. * * @param {string} sValue * the value to be validated * @returns {void} * @throws {sap.ui.model.ValidateException} * if the value is not valid * @public */ EdmGuid.prototype.validateValue = function (sValue) { if (sValue === null) { if (this.oConstraints && this.oConstraints.nullable === false) { throw new ValidateException(getErrorMessage()); } return; } if (typeof sValue !== "string") { // This is a "technical" error by calling validate w/o parse throw new ValidateException("Illegal " + this.getName() + " value: " + sValue); } if (!rGuid.test(sValue)) { throw new ValidateException(getErrorMessage()); } }; return EdmGuid; });
ghostxwheel/utorrent-webui
resources/sap/ui/model/odata/type/Guid-dbg.js
JavaScript
unlicense
5,646
var assert = require('assert') var path = require('path') var fs = require('fs-extra') var sinon = require('sinon') var broccoli = require('broccoli') var Q = require('q') var Filter = require('..') describe('Filter', function() { var ORIG_DIR = path.join(__dirname, 'files') var DIR = path.join(__dirname, 'files-copy') var ONE_FILE_DIR = path.join(__dirname, 'one-file') var builder var createCustomFilter = function() { var CustomFilter = function(inputTrees, options) { if (!(this instanceof CustomFilter)) return new CustomFilter(inputTrees, options) Filter.apply(this, arguments) } CustomFilter.prototype = Object.create(Filter.prototype) return CustomFilter } beforeEach(function() { fs.copySync(ORIG_DIR, DIR) }) afterEach(function() { if (builder) builder.cleanup() fs.removeSync(DIR) }) it('throws when "processFileContent" is not implemented', function(done) { var CustomFilter = createCustomFilter() var tree = new CustomFilter(DIR) builder = new broccoli.Builder(tree) builder.build() .then(function() { done(new Error('Have not thrown')) }) .catch(function() { done() }) }) it('calls "processFileContent"', function() { var CustomFilter = createCustomFilter() var spy = CustomFilter.prototype.processFileContent = sinon.spy() var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function() { var args = spy.firstCall.args assert.equal(args[0], 'file.js\n') assert.equal(args[1], 'file.js') assert.equal(args[2], ONE_FILE_DIR) }) }) var FILTERED = 'filtered' it('filters files', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return FILTERED } var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.js'), 'utf-8') assert.equal(content, FILTERED) }) }) it('uses "targetExtension"', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return FILTERED } var tree = new CustomFilter(ONE_FILE_DIR, {targetExtension: 'ext'}) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.ext'), 'utf-8') assert.equal(content, FILTERED) }) }) it('uses "changeFileName"', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return FILTERED } var tree = new CustomFilter(ONE_FILE_DIR, { targetExtension: 'ext', changeFileName: function(name) { return name + '.changed' } }) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.js.changed'), 'utf-8') assert.equal(content, FILTERED) }) }) it('can return many files', function() { var RESULT = [ {path: 'file1.js', content: 'FILE1'}, {path: 'file2.js', content: 'FILE2'} ] var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return RESULT } var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory RESULT.forEach(function(file) { var content = fs.readFileSync(path.join(dir, file.path), 'utf-8') assert.equal(content, file.content) }) }) }) it('can process files asynchronously', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { var deferred = Q.defer() setTimeout(function() { deferred.resolve(FILTERED) }) return deferred.promise } var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.js'), 'utf-8') assert.equal(content, FILTERED) }) }) it('copy not changed files from cache', function() { var CustomFilter = createCustomFilter() var spy = CustomFilter.prototype.processFileContent = sinon.spy() var tree = new CustomFilter(DIR) builder = new broccoli.Builder(tree) return builder.build() .then(function() { assert.equal(spy.callCount, 3) }) .then(function() { fs.writeFileSync(path.join(DIR, 'file.js'), 'CHANGED') return builder.build() }) .then(function() { assert.equal(spy.callCount, 4) }) }) it('finds files using globs', function() { var CustomFilter = createCustomFilter() var spy = CustomFilter.prototype.processFileContent = sinon.spy() var tree = new CustomFilter(DIR, {files: ['**/*.js']}) builder = new broccoli.Builder(tree) return builder.build() .then(function() { assert.equal(spy.callCount, 1) }) }) })
sunflowerdeath/broccoli-glob-filter
tests/test.js
JavaScript
unlicense
5,011
/** * * This is the "container" for global variables. I made it so we won't have to worry * about "conflicts" with local variable names. * */ var NFL_PICKS_GLOBAL = { /** * Here to store data from the server so we can hopefully load it once and then * get to it whenever it's needed as we're dealing with other stuff. */ data: { teams: [], players: [], years: [] }, /** * The possible types for what they can view. Like standings, picks, and stats. * Holds label and value pairs of all the possible types. */ types: [], /** * Holds label value pairs of all the players we show. Not all of them will be "real"... like if we * want to show "Everybody" or something like that. It'll be in here too. */ players: [], /** * All of the real players in label value pairs. This is so we can send only real players to the server * and pick them apart from the non-real players. */ realPlayers: [], /** * All the years we want to show. It'll have year ranges too (like "jurassic period" and "modern era"). It's * label and value pairs like the other arrays. */ years: [], /** * All the label and value pairs for the real and individual years. */ realYears: [], /** * All the weeks we want to show in label value pairs. It'll have ranges too (like "regular season" and "playoffs). */ weeks: [], /** * All the individual and real weeks that we want to send to the server. */ realWeeks: [], /** * All of the label/value pairs of the different stats we can show. */ statNames: [], /** * The current selections for everything they can pick. */ selections: {}, /** * Whether they're selecting more than one player at a time * or not. */ multiselectPlayer: false, /** * Whether they're selecting more than one week at a time or not. */ multiselectWeek: false, /** * Whether they're selecting more than one year at a time or not. */ multiselectYear: false, /** * The previous type they picked. This is so we can decide how much of the view we need * to "refresh" when we update it. */ previousType: null, /** * Switches that say whether these pick grids have been shown. If they haven't, we want * to make sure we don't show the picks for all years and weeks (unless they specifically asked * for that). * We don't want to do that because that's a lot of info to show. So, these are here basically * so we can "smartly" default the year and week selections for the picks and pick splits grids. */ havePicksBeenShown: false, havePickSplitsBeenShown: false, /** * Whether we should push the previous parameters onto the backward navigation stack. */ pushPreviousParameters: true, /** * The previous parameters that were used to show the view. This is so they can go back * and forth pretty easily. */ previousParameters: null, /** * The stacks for navigating forward and backward. They hold the parameters that were shown for the "view". * When they change the view, we put the previous parameters on the backward stack and when they navigate backward, * we pop those parameters off to change the view and put the previous ones on the forward stack. */ navigationForwardStack: [], navigationBackwardStack: [], /** * So we can get the current year and week number which come in handy. */ currentYear: null, currentWeekKey: null, /** * So we can show the games for the current week. */ gamesForCurrentWeek: null, /** * For holding the initial selections for when the page first shows up. We set some of these * variables with values from the server (like the year) and others (like the type) to constants. */ initialType: null, initialYear: null, initialWeek: null, initialPlayer: null, initialTeam: null, initialStatName: null }; /** * When the document's been loaded on the browser, we want to: * * 1. Go to the server and get the selection criteria (teams, players, initial values). * 2. Initialize the UI based on those values. */ $(document).ready( function(){ getSelectionCriteriaAndInitialize(); }); /** * * This function will initialize the view. It assumes all the stuff from the server * that's needed to initialize is setup. * * @returns */ function initializeView(){ //Steps to do: // 1. Set the initial selections for the type, year, week, ... // 2. Update the view based on those selections. initializeSelections(); updateView(); } /** * * Sets the initial selections for the type, year, week... * They're all set like this: * * 1. The initial value comes from NFL_PICKS_GLOBAL. * 2. If there's a url parameter for the selection, it's used instead. * * This way, we... * * 1. Set the initial values when loading the data from the server (for stuff like * week and year). * 2. Allow the overriding of the values by url parameters. * * Number 2 makes it so people can send direct urls and get the view they want the first * time the page shows up. * * @returns */ function initializeSelections(){ //Steps to do: // 1. Get the parameters that were sent in the url. // 2. Initialize each selection with its global initial value. // 3. If there's a value for it in the url, use that instead so the url // overrides what we assume initially. var parameters = getUrlParameters(); var type = NFL_PICKS_GLOBAL.initialType; if (isDefined(parameters) && isDefined(parameters.type)){ type = parameters.type; } setSelectedType(type); var year = NFL_PICKS_GLOBAL.initialYear; if (isDefined(parameters) && isDefined(parameters.year)){ year = parameters.year; } setSelectedYears(year); var week = NFL_PICKS_GLOBAL.initialWeek; if (isDefined(parameters) && isDefined(parameters.week)){ week = parameters.week; } setSelectedWeeks(week); var player = NFL_PICKS_GLOBAL.initialPlayer; if (isDefined(parameters) && isDefined(parameters.player)){ player = parameters.player; } setSelectedPlayers(player); var statName = NFL_PICKS_GLOBAL.initialStatName; if (isDefined(parameters) && isDefined(parameters.statName)){ statName = parameters.statName; } setSelectedStatName(statName); var team = NFL_PICKS_GLOBAL.initialTeam; if (isDefined(parameters) && isDefined(parameters.team)){ team = parameters.team; } setSelectedTeams(team); resetPlayerSelections(); resetYearSelections(); resetWeekSelections(); resetTeamSelections(); updateTypeLink(); updatePlayersLink(); updateWeeksLink(); updateYearsLink(); updateTeamsLink(); updateStatNameLink(); } /** * * This function will set all the selections from the given parameters. It's here * so that we can do the "navigate forward and backward" thing. We keep those parameters * in maps and then, to go forward and backward, we just have to feed the map we want to * this function. * * This function <i>WON'T</i> update the view. You'll have to do that yourself after calling it. * * @param parameters * @returns */ function setSelectionsFromParameters(parameters){ //Steps to do: // 1. If the parameters don't have anything, there's nothing to do. // 2. Otherwise, just go through and set each individual value. if (!isDefined(parameters)){ return; } if (isDefined(parameters.type)){ setSelectedType(parameters.type); } if (isDefined(parameters.player)){ setSelectedPlayers(parameters.player); } if (isDefined(parameters.year)){ setSelectedYears(parameters.year); } if (isDefined(parameters.week)){ setSelectedWeeks(parameters.week); } if (isDefined(parameters.team)){ setSelectedTeams(parameters.team); } if (isDefined(parameters.statName)){ setSelectedStatName(parameters.statName); } if (isDefined(parameters.multiselectPlayer)){ setMultiselectPlayer(parameters.multiselectPlayer); setMultiselectPlayerValue(parameters.multiselectPlayer); } if (isDefined(parameters.multiselectYear)){ setMultiselectYear(parameters.multiselectYear); setMultiselectYearValue(parameters.multiselectYear); } if (isDefined(parameters.multiselectWeek)){ setMultiselectWeek(parameters.multiselectWeek); setMultiselectWeekValue(parameters.multiselectWeek); } if (isDefined(parameters.multiselectTeam)){ setMultiselectTeam(parameters.multiselectTeam); setMultiselectTeamValue(parameters.multiselectTeam); } } /** * * This function will get the parameters in a map from the url in the browser. If there * aren't any parameters, it'll return null. Otherwise, it'll return a map with the parameter * names as the keys and the values as the url. * * @returns */ function getUrlParameters() { //Steps to do: // 1. If there aren't any parameters, there's nothing to do. // 2. Otherwise, each parameter should be separated by an ampersand, so break them apart on that. // 3. Go through each parameter and get the key and value and that's a parameter. // 4. That's it. if (isBlank(location.search)){ return null; } var parameterNamesAndValues = location.search.substring(1, location.search.length).split('&'); var urlParameters = {}; for (var index = 0; index < parameterNamesAndValues.length; index++) { var parameterNameAndValue = parameterNamesAndValues[index].split('='); //Make sure to decode both the name and value in case there are weird values in them. var name = decodeURIComponent(parameterNameAndValue[0]); var value = decodeURIComponent(parameterNameAndValue[1]); urlParameters[name] = value; } return urlParameters; } /** * * Gets all the values for each kind of parameter (type, year, week, ...) * and returns them in a map with the key being the parameter. * * Here so we can easily get what's selected (for the navigate forward and backward * stuff). * * @returns */ function getSelectedParameters(){ var parameters = {}; parameters.type = getSelectedType(); parameters.player = getSelectedPlayerValues(); parameters.year = getSelectedYearValues(); parameters.week = getSelectedWeekValues(); parameters.statName = getSelectedStatName(); parameters.team = getSelectedTeamValues(); parameters.multiselectPlayer = getMultiselectPlayer(); parameters.multiselectYear = getMultiselectYear(); parameters.multiselectWeek = getMultiselectWeek(); parameters.multiselectTeam = getMultiselectTeam(); return parameters; } /** * * This function will get the initial selection criteria (teams, players, ...) * from the server and create the selection criteria for those options. * * It will also initialize the NFL_PICKS_GLOBAL values (some are pulled from the server, * so that's why we do it in this function) and call the function that initializes the view * once it's ready. * * Those initial values will be: * * 1. type - standings * 2. year - current * 3. week - all * 4. player - all * 5. team - all * 6. statName - champions * * @returns */ function getSelectionCriteriaAndInitialize(){ //Steps to do: // 1. Send the request to the server to get the selection criteria. // 2. When it comes back, pull out the years, players, and teams // and set the options for them in each select. // 3. Set the initial values in the NFL_PICKS_GLOBAL variable. // 4. Now that we have all the criteria and initial values, we can initialize the view. $.ajax({url: 'nflpicks?target=selectionCriteria', contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { var selectionCriteriaContainer = $.parseJSON(data); NFL_PICKS_GLOBAL.data.teams = selectionCriteriaContainer.teams; NFL_PICKS_GLOBAL.data.players = selectionCriteriaContainer.players; NFL_PICKS_GLOBAL.data.years = selectionCriteriaContainer.years; var types = [{label: 'Standings', value: 'standings'}, {label: 'Picks', value: 'picks'}, {label: 'Stats', value: 'stats'}]; NFL_PICKS_GLOBAL.types = types; var typeSelectorHtml = createTypeSelectorHtml(types); $('#typesContainer').empty(); $('#selectorContainer').append(typeSelectorHtml); var years = selectionCriteriaContainer.years; //We want the "all" year option to be first. var yearOptions = [{label: 'All', value: 'all'}, {label: 'Jurassic Period (2010-2015)', value: 'jurassic-period'}, {label: 'First year (2016)', value: 'first-year'}, {label: 'Modern Era (2017 - now)', value: 'modern-era'}]; var realYears = []; for (var index = 0; index < years.length; index++){ var year = years[index]; yearOptions.push({label: year, value: year}); realYears.push({label: year, value: year}); } NFL_PICKS_GLOBAL.years = yearOptions; NFL_PICKS_GLOBAL.realYears = realYears; var yearSelectorHtml = createYearSelectorHtml(yearOptions); $('#yearsContainer').empty(); $('#selectorContainer').append(yearSelectorHtml); var weekOptions = [{label: 'All', value: 'all'}, {label: 'Regular season', value: 'regular_season'}, {label: 'Playoffs', value: 'playoffs'}, {label: 'Week 1', value: '1'}, {label: 'Week 2', value: '2'}, {label: 'Week 3', value: '3'}, {label: 'Week 4', value: '4'}, {label: 'Week 5', value: '5'}, {label: 'Week 6', value: '6'}, {label: 'Week 7', value: '7'}, {label: 'Week 8', value: '8'}, {label: 'Week 9', value: '9'}, {label: 'Week 10', value: '10'}, {label: 'Week 11', value: '11'}, {label: 'Week 12', value: '12'}, {label: 'Week 13', value: '13'}, {label: 'Week 14', value: '14'}, {label: 'Week 15', value: '15'}, {label: 'Week 16', value: '16'}, {label: 'Week 17', value: '17'}, {label: 'Week 18', value: '18'}, {label: 'Wild Card', value: 'wildcard'}, {label: 'Divisional', value: 'divisional'}, {label: 'Conference Championship', value: 'conference_championship'}, {label: 'Superbowl', value: 'superbowl'} ]; //could these be 1, 2, 3, 4, ... again and just change the playoffs? //yeah i think so //week=1,2,3,4,wildcard,divisional,superbowl //yeah that's better than //week=1,2,3,wildcard,divisional //need to change .... importer ... the model util function ... this //and that should be it. var realWeeks = [{label: 'Week 1', value: '1'}, {label: 'Week 2', value: '2'}, {label: 'Week 3', value: '3'}, {label: 'Week 4', value: '4'}, {label: 'Week 5', value: '5'}, {label: 'Week 6', value: '6'}, {label: 'Week 7', value: '7'}, {label: 'Week 8', value: '8'}, {label: 'Week 9', value: '9'}, {label: 'Week 10', value: '10'}, {label: 'Week 11', value: '11'}, {label: 'Week 12', value: '12'}, {label: 'Week 13', value: '13'}, {label: 'Week 14', value: '14'}, {label: 'Week 15', value: '15'}, {label: 'Week 16', value: '16'}, {label: 'Week 17', value: '17'}, {label: 'Week 18', value: '18'}, {label: 'Wild Card', value: 'wildcard'}, {label: 'Divisional', value: 'divisional'}, {label: 'Conference Championship', value: 'conference_championship'}, {label: 'Superbowl', value: 'superbowl'} ]; //need to refactor the NFL_PICKS_GLOBAL so that it has all the options //and all the data //NFL_PICKS_GLOBAL.criteria.weeks - the weeks as selection criteria //NFL_PICKS_GLOBAL.data.weeks - all the actual weeks //global_setWeeks //global_setRealWeeks //global_getWeeks //selector_blah //html_blah //yeah this needs to be done //nflpicks global needs to be defined in a separate javascript file NFL_PICKS_GLOBAL.weeks = weekOptions; NFL_PICKS_GLOBAL.realWeeks = realWeeks; var weekSelectorHtml = createWeekSelectorHtml(weekOptions); $('#selectorContainer').append(weekSelectorHtml); var players = selectionCriteriaContainer.players; //We want the "all" player option to be the first one. var playerOptions = [{label: 'Everybody', value: 'all'}]; var realPlayers = []; for (var index = 0; index < players.length; index++){ var player = players[index]; var playerObject = {label: player, value: player}; playerOptions.push(playerObject); realPlayers.push(playerObject); } setOptionsInSelect('player', playerOptions); NFL_PICKS_GLOBAL.players = playerOptions; NFL_PICKS_GLOBAL.realPlayers = realPlayers; var playerSelectorHtml = createPlayerSelectorHtml(playerOptions); $('#selectorContainer').append(playerSelectorHtml); //Need to filter the teams so that we only show teams that had a game in a given year. //Probably just do a ui filter because we probably don't want to make a trip to the server // var teams = selectionCriteriaContainer.teams; //Sort the teams in alphabetical order to make sure we show them in a consistent order. teams.sort(function (teamA, teamB){ if (teamA.abbreviation < teamB.abbreviation){ return -1; } else if (teamA.abbreviation > teamB.abbreviation){ return 1; } return 0; }); //We also want the "all" option to be first. var teamOptions = [{label: 'All', value: 'all'}]; for (var index = 0; index < teams.length; index++){ var team = teams[index]; teamOptions.push({label: team.abbreviation, value: team.abbreviation}); } var teamSelectorHtml = createTeamSelectorHtml(teamOptions); $('#selectorContainer').append(teamSelectorHtml); NFL_PICKS_GLOBAL.teams = teamOptions; var statNameOptions = [{label: 'Champions', value: 'champions'}, {label: 'Championship Standings', value: 'championshipStandings'}, {label: 'Season Standings', value: 'seasonStandings'}, {label: 'Week Standings', value: 'weekStandings'}, {label: 'Weeks Won Standings', value: 'weeksWonStandings'}, {label: 'Weeks Won By Week', value: 'weeksWonByWeek'}, {label: 'Week Records By Player', value: 'weekRecordsByPlayer'}, {label: 'Pick Accuracy', value: 'pickAccuracy'}, {label: 'Pick Splits', value: 'pickSplits'}, {label: 'Week Comparison', value: 'weekComparison'}, {label: 'Season Progression', value: 'seasonProgression'}]; var statNameSelectorHtml = createStatNameSelectorHtml(statNameOptions); $('#selectorContainer').append(statNameSelectorHtml); NFL_PICKS_GLOBAL.statNames = statNameOptions; //The current year and week come from the server. NFL_PICKS_GLOBAL.currentYear = selectionCriteriaContainer.currentYear; NFL_PICKS_GLOBAL.currentWeekKey = selectionCriteriaContainer.currentWeekKey; //Initially, we want to see the standings for the current year for everybody, so set those //as the initial types. NFL_PICKS_GLOBAL.initialType = 'standings'; NFL_PICKS_GLOBAL.initialYear = NFL_PICKS_GLOBAL.currentYear + ''; NFL_PICKS_GLOBAL.initialWeek = 'all'; NFL_PICKS_GLOBAL.initialPlayer = 'all'; NFL_PICKS_GLOBAL.initialTeam = 'all'; NFL_PICKS_GLOBAL.initialStatName = 'champions'; initializeView(); }) .fail(function() { }) .always(function() { }); } /** * * This function will cause the view to "navigate forward". We can only do that if * we've gone back. So, this function will check the stack that holds the "forward parameters", * pop the top of it off (if there's something in it), and then cause the view to have those * parameters. * * Before navigating, it will take the current parameters and put them on the previous stack * so they can go back if they hit "back". * * @returns */ function navigateForward(){ //Steps to do: // 1. If there aren't any forward parameters, there's no way to go forward. // 2. The current parameters should go on the previous stack. // 3. Get the forward parameters off the forward stack. // 4. Set them as the selections. // 5. Update the view and make sure it doesn't push any parameters on any // stack // 6. Flip the switch back so any other navigation will push parameters // on the previous stack. if (NFL_PICKS_GLOBAL.navigationForwardStack.length == 0){ return; } var currentParameters = getSelectedParameters(); NFL_PICKS_GLOBAL.navigationBackwardStack.push(currentParameters); var parameters = NFL_PICKS_GLOBAL.navigationForwardStack.pop(); setSelectionsFromParameters(parameters); //Before updating the view, flip the switch that the updateView function uses to //decide whether to push the parameters for the current view on the stack or not. //Since we're navigating forward, we take care of that in this function instead. //A little bootleg, so it probably means I designed it wrong... NFL_PICKS_GLOBAL.pushPreviousParameters = false; updateView(); NFL_PICKS_GLOBAL.pushPreviousParameters = true; } /** * * This function will cause the view to show the previous view. It's the same thing * as going backward except will pull from the navigate backward stack. The previous parameters * for the view are stored on a stack, so to go backward, we just have to pop those parameters * off, set them as the selections, and the update the view. * * It'll also take the current parameters (before going backward) and push them on the forward stack * so navigating forward, after going backward, brings them back to where they were. * * @returns */ function navigateBackward(){ //Steps to do: // 1. If there isn't anything to backward to, there's nothing to do. // 2. The current parameters should go on the forward stack since they're // what we want to show if people navigate forward // 3. The parameters we want to use come off the backward stack. // 4. Flip the switch that says to not push any parameters on in the view function. // 5. Update based on the parameters we got. // 6. Flip the switch back so that any other navigation causes the parameters // to go on the previous stack. if (NFL_PICKS_GLOBAL.navigationBackwardStack.length == 0){ return; } var currentParameters = getSelectedParameters(); NFL_PICKS_GLOBAL.navigationForwardStack.push(currentParameters); var parameters = NFL_PICKS_GLOBAL.navigationBackwardStack.pop(); //stuff is updated here... setSelectionsFromParameters(parameters); //Just like when navigating forward, we don't want the updateView function to fiddle //with the navigation stacks since we're doing it here. After the view has been updated, though, //flip the switch back so that any other navigation cause the updateView function save the //current view before changing. NFL_PICKS_GLOBAL.pushPreviousParameters = false; updateView(); NFL_PICKS_GLOBAL.pushPreviousParameters = true; } /** * * This function will make it so we only show the forward and backward * links if they can actually navigate forward and backward. It just checks * the length of the stacks and uses that to decide whether to show * or hide each link. * * @returns */ function updateNavigationLinksVisibility(){ //Steps to do: // 1. If the stack doesn't have anything in it, we shouldn't show // the link. // 2. Otherwise, we should. if (NFL_PICKS_GLOBAL.navigationForwardStack.length == 0){ $('#navigationFowardContainer').hide(); } else { $('#navigationFowardContainer').show(); } if (NFL_PICKS_GLOBAL.navigationBackwardStack.length == 0){ $('#navigationBackwardContainer').hide(); } else { $('#navigationBackwardContainer').show(); } } /** * * The "main" function for the UI. Makes it so we show what they picked on the screen. * It bases its decision on the "type" variable and then just calls the right function * based on what that is. * * If the NFL_PICKS_GLOBAL.pushPreviousParameters switch is flipped, it'll also update * the navigation stacks. That switch is there so that: * * 1. When they do any non-forward or backward navigation action, we update the stacks. * 2. When they push forward or backward, we can handle the stacks other places. * * @returns */ function updateView(){ //Steps to do: // 1. Before doing anything, if the switch is flipped, we should save the parameters // from the last navigation on the backward stack so they can go backward to what // we're currently on, if they want. // 2. Get the type of view they want. // 3. Update the selector view based on the type. // 4. Decide which function to call based on that. // 5. After the view is updated, keep the current selected parameters around so we can push // them on the "back" stack the next time they make a change. // 6. Make sure we're showing the right "navigation" links. //If there are previous parameters, and we should push them, then push them on the backward //navigation stack so they can go back to that view with the back button. //If we shouldn't push them, that means the caller is handling the stack stuff themselves. //And, if we should push them, that means they did some "action" that takes them on a //different "branch", so we should clear out the forward stack since they can't go //forward anymore. if (NFL_PICKS_GLOBAL.previousParameters != null && NFL_PICKS_GLOBAL.pushPreviousParameters){ NFL_PICKS_GLOBAL.navigationBackwardStack.push(NFL_PICKS_GLOBAL.previousParameters); NFL_PICKS_GLOBAL.navigationForwardStack = []; } var type = getSelectedType(); //Update the selectors that get shown. We want to show different things depending //on the type. updateSelectors(type); //And update the options for the criteria in each selector. updateAvailableCriteriaOptions(); if ('picks' == type){ updatePicks(); } else if ('standings' == type) { updateStandings(); } else if ('stats' == type){ updateStats(); } //At this point, the selected parameters are the current parameters. We want to //keep them around in case we need to push them on the stack the next time through. NFL_PICKS_GLOBAL.previousParameters = getSelectedParameters(); updateTypeLink(); updatePlayersLink(); updateYearsLink(); updateWeeksLink(); updateTeamsLink(); updateStatNameLink(); //And we need to make sure we're showing the right "forward" and "back" links. updateNavigationLinksVisibility(); } /** * * This function will update the available options for the criteria based on what's selected. * It's here mainly for the situation where you select an option in a "selector" and that option * should cause options in other selectors to be either shown or hidden. * * I made it for the situation where somebody picks a year and we should only show the teams * that actually existed that year. Like, if somebody picks "2020" as the year, we shouldn't * show "OAK", but we should show "LV". * * ... And now it's here to handle the change in week for the 2021 season where a 17th game was added. * * It will farm the work out to other functions that handle the specific scenarios for each * kind of "selector". * * @returns */ function updateAvailableCriteriaOptions(){ updateAvailableTeamOptions(); updateAvailableWeekOptions(); //updateAvailableWeekOptions................. // //main_updateAvailableTeamOptions } /** * * This function will update the available teams that can be selected. It will just go through * and check whether each team was "active" during the selected years. If they were, then it'll * show them and if they weren't, it'll hide them. * * @returns */ function updateAvailableTeamOptions(){ //Steps to do: // 1. Get the year values as integers. // 2. Go through every team and get when it started and ended. // 3. If the year it started is after any of the selected years and it doesn't have an // end or its end is before one of the selected years, that means it played games during // the selected years so it should be shown. // 4. Otherwise, it didn't and so it should be hidden. var currentSelectedYearValues = getYearValuesForSelectedYears(); var integerYearValues = getValuesAsIntegers(currentSelectedYearValues); var teamsToShow = []; var teamsToHide = []; //All the teams are stored in the global variable. Just have to go through them. var teams = NFL_PICKS_GLOBAL.data.teams; for (var index = 0; index < teams.length; index++){ var team = teams[index]; //Flipping this switch off and I'll flip it on if the team's start and end years show //it played games in the selected years. var showTeam = false; //Make sure to turn their years into numbers. var teamStartYearInteger = parseInt(team.startYear); var teamEndYearInteger = -1; if (isDefined(team.endYear)){ teamEndYearInteger = parseInt(team.endYear); } //Go through each selected year. for (var yearIndex = 0; yearIndex < integerYearValues.length; yearIndex++){ var currentYearValue = integerYearValues[yearIndex]; //If the team started before the current year and either is still active (end year = -1) or was active after the //current year, that means it played games in the selected year, so it should be shown. if (teamStartYearInteger <= currentYearValue && (teamEndYearInteger == -1 || teamEndYearInteger >= currentYearValue)){ showTeam = true; } } //Just put it in the list based on whether it should be shown or not. if (showTeam){ teamsToShow.push(team.abbreviation); } else { teamsToHide.push(team.abbreviation); } } //Show the teams that should be shown in the selector dropdown. showTeamItems(teamsToShow); //Hide the teams that should be hidden in the selector. hideTeamItems(teamsToHide); //And, we have to go through and unselect the ones we should hide in case they //were selected. If we just hide them and they're still selected, they'll still //show up on the ui, just not in the selection dropdown. for (var index = 0; index < teamsToHide.length; index++){ var teamToHide = teamsToHide[index]; unselectTeamFull(teamToHide); } } //updateSelectors function getAvailableWeeksForYears(yearValues){ var integerYearValues = getValuesAsIntegers(currentSelectedYearValues); var availableWeeksBefore2021 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; var availableWeeksAfter2021 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; for (var index = 0; index < integerYearValues.length; index++){ var integerYearValue = integerYearValues[index]; if (integerYearValue >= 2021){ return availableWeeksAfter2021; } } return availableWeeksBefore2021; } function updateAvailableWeekOptions(){ var currentSelectedYearValues = getYearValuesForSelectedYears(); var weeksToShow = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; var weeksToHide = ['18']; for (var index = 0; index < currentSelectedYearValues.length; index++){ var yearValue = currentSelectedYearValues[index]; if (yearValue >= 2021){ weeksToShow = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; weeksToHide = []; } } showWeekItems(weeksToShow); hideWeekItems(weeksToHide); //And, we have to go through and unselect the ones we should hide in case they //were selected. If we just hide them and they're still selected, they'll still //show up on the ui, just not in the selection dropdown. for (var index = 0; index < weeksToHide.length; index++){ var weekToHide = weeksToHide[index]; unselectWeekFull(weekToHide); } } /** * * This function will update the selectors for the given type. It just calls * the specific type's update function. * * It will also update the multi-selects so that the selected values are updated * if they're selecting multiple "items" (multiple players, weeks, or years). * * @param type * @returns */ function updateSelectors(type){ //Steps to do: // 1. Call the function based on the type. // 2. Update the multi selects. if ('picks' == type){ updatePicksSelectors(type); } else if ('standings' == type){ updateStandingsSelectors(type); } else if ('stats' == type){ updateStatsSelectors(type); } } /** * * Updates the selectors so that they're good to go for when the type is picks. * * Shows: * year, player, team, week * Hides: * stat name * * Only shows or hides something if the given type isn't the previous selected type. * * @param type * @returns */ function updatePicksSelectors(type){ //Steps to do: // 1. If the previous type is the same as the given one, we don't need // to do anything to the selectors. // 2. Show and hide what we need to. // 3. Store the type we were given for next time. var previousSelectedType = getPreviousType(); if (previousSelectedType == type){ return; } showPlayersLink(); showWeeksLink(); showYearsLink(); showTeamsLink(); hideStatNameLink(); setPreviousType(type); } /** * * Updates the selectors so that they're right for browsing the "standings". * * Shows: * player, year, week, team * Hides: * stat name * * Only shows or hides something if the given type isn't the previous selected type. * * @param type * @returns */ function updateStandingsSelectors(type){ //Steps to do: // 1. If the previous type is the same as the given one, we don't need // to do anything to the selectors. // 2. Show and hide what we need to. // 3. Store the type we were given for next time. var previousSelectedType = getPreviousType(); if (previousSelectedType == type){ return; } showPlayersLink(); showWeeksLink(); showYearsLink(); showTeamsLink(); hideStatNameLink(); setPreviousType(type); } /** * * Updates the selectors so that they're good to go for browsing the * "stats" * * Shows: * stat name, others depending on the stat name * Hides: * depends on the stat name * * Stat name: * champions * shows: Nothing * hides: player, year, week, team * championship standings * shows: Nothing * hides: player, year, week, team * week standings * shows: player, year, week * hides: team * weeks won standings * shows: year * hides: player, team, week * weeks won by week * shows: year, week * hides: team * week records by player * shows: year, week, player * hides: team * pick accuracy * shows: year, player, team * hides: week * pick splits: * shows: year, week, team * hides: player * * @param type * @returns */ function updateStatsSelectors(type){ //Steps to do: // 1. We always want to show the stat name container. // 2. Get the name of the stat we want to show. // 3. Show and hide what we need to based on the kind of stat we want to show. // 4. Store the type we were given for next time. showStatNameLink(); var statName = getSelectedStatName(); if ('champions' == statName){ showPlayersLink(); showYearsLink(); hideWeeksLink(); hideTeamsLink(); } else if ('championshipStandings' == statName){ showPlayersLink(); showYearsLink(); hideWeeksLink(); hideTeamsLink(); } else if ('seasonStandings' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weekStandings' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weeksWonStandings' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weeksWonByWeek' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weekRecordsByPlayer' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('pickAccuracy' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); showTeamsLink(); } else if ('pickSplits' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); showTeamsLink(); } else if ('weekComparison' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('seasonProgression' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } setPreviousType(type); } /** * * Gets the selected value for the type. * * @returns */ function getSelectedType(){ return $('input[name=type]:checked').val(); } /** * * Sets the selected value for the type to the given type. Only does it * if the type select input has the given type as an option. * * @param type * @returns */ function setSelectedType(type){ $('input[name=type]').val([type]); NFL_PICKS_GLOBAL.selections.type = type; } /** * * Gets the previous type that was selected. This is so we can decide * whether to update stuff or not when the type changes. * * @returns */ function getPreviousType(){ return NFL_PICKS_GLOBAL.previousType; } /** * * Sets the previous type in the NFL_PICKS_GLOBAL variable. This is so we can decide * whether to update stuff or not when the type changes. * * @param newPreviousType * @returns */ function setPreviousType(newPreviousType){ NFL_PICKS_GLOBAL.previousType = newPreviousType; } /** * * This function will set the given players as being selected in the NFL_PICKS_GLOBAL * variable (NFL_PICKS_GLOBAL.selections.players) and it'll call the "selectPlayer" * function in the selectors file for each player so they get "selected" on the UI too. * * It expects the given players variable to either be... * 1. An array of player names. * 2. A comma separated string of player names. * 3. A single player name. * * It will put the actual player objects into the NFL_PICKS_GLOBAL variable for * each player name that's given. * * @param players * @returns */ function setSelectedPlayers(players){ //Steps to do: // 1. Check whether the players variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each player in the array, get the actual object for the player name // and put it in the global variable. And, "select" them in the ui. var playerValuesArray = []; var isArray = Array.isArray(players); if (isArray){ playerValuesArray = players; } else { var hasMultipleValues = doesValueHaveMultipleValues(players); if (hasMultipleValues){ playerValuesArray = delimitedValueToArray(players); } else { playerValuesArray.push(players); } } var playersArray = []; for (var index = 0; index < playerValuesArray.length; index++){ var value = playerValuesArray[index]; selectPlayer(value); var player = getPlayer(value); playersArray.push(player); } NFL_PICKS_GLOBAL.selections.players = playersArray; } /** * * This function will set the given years as being selected in the UI and in the * NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.years). * * It expects the given years variable to either be... * 1. An array of year values. * 2. A comma separated string of year values. * 3. A single year value. * * It will put the actual year objects into the NFL_PICKS_GLOBAL variable for * each year value that's given. * * @param years * @returns */ function setSelectedYears(years){ //Steps to do: // 1. Check whether the years variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each year in the array, get the actual object for the year // and put it in the global variable. And, "select" it in the ui. var yearValuesArray = []; var isArray = Array.isArray(years); if (isArray){ yearValuesArray = years; } else { var hasMultipleValues = doesValueHaveMultipleValues(years); if (hasMultipleValues){ yearValuesArray = delimitedValueToArray(years); } else { yearValuesArray.push(years); } } var yearsArray = []; for (var index = 0; index < yearValuesArray.length; index++){ var value = yearValuesArray[index]; selectYear(value); var year = getYear(value); yearsArray.push(year); } NFL_PICKS_GLOBAL.selections.years = yearsArray; } /** * * This function will set the given weeks as being selected in the UI and in the * NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.weeks). * * It expects the given weeks variable to either be... * 1. An array of week numbers. * 2. A comma separated string of week numbers. * 3. A single week number. * * It will put the actual week objects into the NFL_PICKS_GLOBAL variable for * each week number that's given. * * @param weeks * @returns */ function setSelectedWeeks(weeks){ //Steps to do: // 1. Check whether the weeks variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each week in the array, get the actual object for the week // and put it in the global variable. And, "select" it in the ui. var weekValuesArray = []; var isArray = Array.isArray(weeks); if (isArray){ weekValuesArray = weeks; } else { var hasMultipleValues = doesValueHaveMultipleValues(weeks); if (hasMultipleValues){ weekValuesArray = delimitedValueToArray(weeks); } else { weekValuesArray.push(weeks); } } var weeksArray = []; for (var index = 0; index < weekValuesArray.length; index++){ var value = weekValuesArray[index]; selectWeek(value); var week = getWeek(value); weeksArray.push(week); } //THIS was the key ... update the current week selections... geez this is too complicated setCurrentWeekSelections(weekValuesArray); NFL_PICKS_GLOBAL.selections.weeks = weeksArray; } /** * * This function will set the given teams as being selected in the UI and in the * NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.teams). * * It expects the given teams variable to either be... * 1. An array of team abbreviations. * 2. A comma separated string of team abbreviations. * 3. A single team abbreviation. * * It will put the actual team objects into the NFL_PICKS_GLOBAL variable for * each team abbreviation that's given. * * @param teams * @returns */ function setSelectedTeams(teams){ //Steps to do: // 1. Check whether the teams variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each team in the array, get the actual object for the team // and put it in the global variable. And, "select" it in the ui. var teamValuesArray = []; var isArray = Array.isArray(teams); if (isArray){ teamValuesArray = teams; } else { var hasMultipleValues = doesValueHaveMultipleValues(teams); if (hasMultipleValues){ teamValuesArray = delimitedValueToArray(teams); } else { teamValuesArray.push(teams); } } var teamsArray = []; for (var index = 0; index < teamValuesArray.length; index++){ var value = teamValuesArray[index]; selectTeam(value); var team = getTeam(value); teamsArray.push(team); } //THIS was the key ... update the current team selections... geez this is too complicated setCurrentTeamSelections(teamValuesArray); NFL_PICKS_GLOBAL.selections.teams = teamsArray; } /** * * Gets the selected stat name. * * @returns */ function getSelectedStatName(){ return $('input[name=statName]:checked').val(); } /** * * Sets the selected stat name if it's one of the options * on the stat name input. * * @param statName * @returns */ function setSelectedStatName(statName){ $('input[name=statName]').val([statName]); NFL_PICKS_GLOBAL.selections.statName = statName; } /** * * This function will set the given html as the content we show. It'll clear out what's * in there now. * * @param contentHtml * @returns */ function setContent(contentHtml){ $('#contentContainer').empty(); $('#contentContainer').append(contentHtml); } /** * * This function will go get the standings from the server and show them on the UI. * * What standings it gets depends on the player, year, and week that are selected. * * @returns */ function updateStandings(){ //Steps to do: // 1. Get the parameters to send (player, year, and week). // 2. Send them to the server. // 3. Update the UI with the results. var playerValuesForRequest = getPlayerValuesForRequest(); var yearValuesForRequest = getYearValuesForRequest(); var weekValuesForRequest = getWeekValuesForRequest(); var teamValuesForRequest = getTeamValuesForRequest(); setContent('<div style="text-align: center;">Loading...</div>'); $.ajax({url: 'nflpicks?target=standings&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest, contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { var standingsContainer = $.parseJSON(data); //We want to show the records that came back, but we're going to have to sort them //to make sure they're in the order we want. var records = standingsContainer.records; //We want the record with the most wins coming first. If they have the same number //of wins, we want the one with fewer losses coming first. //And if they're tied, we want them ordered by name. records.sort(function (record1, record2){ if (record1.wins > record2.wins){ return -1; } else if (record1.wins < record2.wins){ return 1; } else { if (record1.losses < record2.losses){ return -1; } else if (record1.losses > record2.losses){ return 1; } } if (record1.player.name < record2.player.name){ return -1; } else if (record1.player.name > record2.player.name){ return 1; } return 0; }); //Now that we have them sorted, we can create the html for the standings. var standingsHtml = createStandingsHtml(standingsContainer.records); //And set it as the content. setContent(standingsHtml); }) .fail(function() { setContent('<div style="text-align: center;">Error</div>'); }) .always(function() { }); } /** * * This function will update the picks grid with the current selectors they ... picked. * It'll get the parameters, go to the server to get the picks, and then update the UI * with the grid. * * @returns */ function updatePicks(){ //Steps to do: // 1. Get the parameters they picked. // 2. Default the year and week to the current year and week if we should. // 3. Go to the server and get the picks. // 4. Update the UI with the picks grid. var selectedYearValues = getSelectedYearValues(); var selectedWeekValues = getSelectedWeekValues(); //We need to make sure we only use "all" for the year if they explicitly set it. // //That should only happen if: // 1. It's "all" in the url. // 2. Or, they have seen the picks and have set it to "all" themselves. // //I'm doing it like this because using "all" for the year might bring back a lot //of picks, so we should only do it if that's what they want to do. var parameters = getUrlParameters(); var hasYearInUrl = false; if (isDefined(parameters) && isDefined(parameters.year)){ hasYearInUrl = true; } //We want to default it to the current year if: // // 1. It's "all" // 2. We haven't shown the picks before // 3. The "all" isn't from the url. // //In that situation, they didn't "explicitly" set it to "all", so we want to show //only picks for the current year to start off with. if (selectedYearValues.includes('all') && !NFL_PICKS_GLOBAL.havePicksBeenShown && !hasYearInUrl){ var currentYear = NFL_PICKS_GLOBAL.currentYear + ''; setSelectedYears(currentYear); updateYearsLink(); } //Do the same thing with the week. We only want to show picks for all the weeks if //they went out of their way to say that's what they wanted to do. var hasWeekInUrl = false; if (isDefined(parameters) && isDefined(parameters.week)){ hasWeekInUrl = true; } //If it's "all" and the picks haven't been shown and the "all" didn't come from the url, //it's their first time seeing the picks, so we should show the ones for the current week. if (selectedWeekValues.includes('all') && !NFL_PICKS_GLOBAL.havePicksBeenShown && !hasWeekInUrl){ var currentWeek = NFL_PICKS_GLOBAL.currentWeekKey + ''; setSelectedWeeks(currentWeek); updateWeeksLink(); } //At this point, we're going to show them the picks, so we should flip that switch. NFL_PICKS_GLOBAL.havePicksBeenShown = true; var playerValuesForRequest = getPlayerValuesForRequest(); var yearValuesForRequest = getYearValuesForRequest(); var weekValuesForRequest = getWeekValuesForRequest(); var teamValuesForRequest = getTeamValuesForRequest(); setContent('<div style="text-align: center;">Loading...</div>'); //Go to the server and get the grid. $.ajax({url: 'nflpicks?target=compactPicksGrid&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest, contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { //Update the UI with what the server sent back. var picksGrid = $.parseJSON(data); var picksGridHtml = createPicksGridHtml(picksGrid); setContent(picksGridHtml); }) .fail(function() { setContent('<div style="text-align: center;">Error</div>'); }) .always(function() { }); } /** * * This function will get the stats from the server and update them on the ui. The stat that * it shows depends on the statName they picked. * * @returns */ function updateStats(){ //Steps to do: // 1. Get the selected parameters. // 2. Make sure they're ok based on the stat name. // 3. Go to the server and get the stats. // 4. Update the UI with what came back. var statName = getSelectedStatName(); var selectedPlayerValues = getPlayerValuesForRequest(); var selectedYearValues = getYearValuesForRequest(); var selectedWeekValues = getWeekValuesForRequest(); var selectedTeamValues = getTeamValuesForRequest(); //If the stat name is the "pick splits", we want to do the same thing we do with the picks grid. //Only show "all" for the year or the week if they actually set it to "all". //If it's the first time we're showing the pick splits, we only want to show all of them if that //was in the url. if (statName == 'pickSplits'){ //Since we're showing how players are split up, we want to show all players. var selectedYearValues = getSelectedYearValues(); var selectedWeekValues = getSelectedWeekValues(); var urlParameters = getUrlParameters(); //Same deal as with the picks grid... var hasYearInUrl = false; if (isDefined(urlParameters) && isDefined(urlParameters.year)){ hasYearInUrl = true; } //If the year is "all", we haven't shown the picks, and "all" didn't come from the url, then we //want the year we show the pick splits for to be the current year. if (selectedYearValues.includes('all') && !NFL_PICKS_GLOBAL.havePickSplitsBeenShown && !hasYearInUrl){ var currentYear = NFL_PICKS_GLOBAL.currentYear + ''; setSelectedYears(currentYear); updateYearsLink(); } //Same deal as with the year and with the picks grid... var hasWeekInUrl = false; if (isDefined(urlParameters) && isDefined(urlParameters.week)){ hasWeekInUrl = true; } //If the week is "all", we haven't shown the picks, and "all" didn't come from the url, then we //want the week we show the pick splits for to be the current week. if (selectedWeekValues.includes('all') && !NFL_PICKS_GLOBAL.havePickSplitsBeenShown && !hasWeekInUrl){ var currentWeek = NFL_PICKS_GLOBAL.currentWeekKey + ''; setSelectedWeeks(currentWeek); updateWeeksLink(); } //And, since we're here, that means we've shown the pick splits to the user, so the next time, we won't //do the funny business with the week and year. NFL_PICKS_GLOBAL.havePickSplitsBeenShown = true; } var playerValuesForRequest = getPlayerValuesForRequest(); var yearValuesForRequest = getYearValuesForRequest(); var weekValuesForRequest = getWeekValuesForRequest(); var teamValuesForRequest = getTeamValuesForRequest(); setContent('<div style="text-align: center;">Loading...</div>'); //Send the request to the server. $.ajax({url: 'nflpicks?target=stats&statName=' + statName + '&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest, contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { var statsHtml = ''; //Make the html for the kind of stat they wanted to see. if ('champions' == statName){ var championships = $.parseJSON(data); statsHtml = createChampionsHtml(championships); } else if ('championshipStandings' == statName){ var championships = $.parseJSON(data); statsHtml = createChampionshipStandingsHtml(championships); } else if ('seasonStandings' == statName){ var seasonRecords = $.parseJSON(data); statsHtml = createSeasonStandingsHtml(seasonRecords); } else if ('weeksWonStandings' == statName){ var weekRecords = $.parseJSON(data); //We want to sort the records before we show them so we can show the rank. sortWeekRecords(weekRecords); statsHtml = createWeeksWonHtml(weekRecords); } else if ('weeksWonByWeek' == statName){ var weeksWonByWeek = $.parseJSON(data); statsHtml = createWeeksWonByWeek(weeksWonByWeek); } else if ('weekRecordsByPlayer' == statName){ var weekRecords = $.parseJSON(data); //Like with the other records, we want to sort them before we show them. sortWeekRecordsBySeasonWeekAndRecord(weekRecords); statsHtml = createWeekRecordsByPlayerHtml(weekRecords); } else if ('weekStandings' == statName){ var playerWeekRecords = $.parseJSON(data); statsHtml = createWeekStandingsHtml(playerWeekRecords); } else if ('pickAccuracy' == statName){ var start = Date.now(); var pickAccuracySummaries = $.parseJSON(data); var jsonElapsed = Date.now() - start; var htmlStart = Date.now(); statsHtml = createPickAccuracySummariesHtml(pickAccuracySummaries); var htmlElapsed = Date.now() - htmlStart; } else if ('pickSplits' == statName){ var pickSplits = $.parseJSON(data); statsHtml = createPickSplitsGridHtml(pickSplits); } else if ('weekComparison' == statName){ var weekRecords = $.parseJSON(data); //Like with the other records, we want to sort them before we show them. sortWeekRecordsBySeasonWeekAndRecord(weekRecords); statsHtml = createWeekComparisonHtml(weekRecords); } else if ('seasonProgression' == statName){ var weekRecords = $.parseJSON(data); //Like with the other records, we want to sort them before we show them. sortWeekRecordsBySeasonWeekAndRecord(weekRecords); statsHtml = createSeasonProgressionHtml(weekRecords); } setContent(statsHtml); }) .fail(function() { setContent('<div style="text-align: center;">Error</div>'); }) .always(function() { }); } /** * * A "convenience" function that says whether any record in the given * array has any ties. * * @param records * @returns */ function hasTies(records){ //Steps to do: // 1. Go through all the records and return true if one has a tie. if (!isDefined(records)){ return false; } for (var index = 0; index < records.length; index++){ var record = records[index]; if (record.ties > 0){ return true; } } return false; } /** * * This function will compare the given records and return -1 if the first record * has more wins than the second, 1 if it has more, and 0 if it's the same. * * If the records have the same number of wins, then it bases the comparison on the * losses. If record1 has the same wins but fewer losses, it should go first, so it * returns -1. * * It'll return 0 if they have the exact same number of wins and losses. * * We do this in a few different places, so I decided to make a function. * * @param record1 * @param record2 * @returns */ function recordWinComparisonFunction(record1, record2){ //Steps to do: // 1. Compare based on the wins first. // 2. If they're the same, compare on the losses. //More wins should go first. if (record1.wins > record2.wins){ return -1; } //Fewer wins should go last. else if (record1.wins < record2.wins){ return 1; } else { //With the same number of wins, fewer losses should go first. if (record1.losses < record2.losses){ return -1; } //And more losses should go second. else if (record1.losses > record2.losses){ return 1; } } //Same wins and losses = same record. return 0; } /** * * When somebody clicks the "body" of the page, we want it to hide everything, so * that's what this function will do. It just goes through and calls the function * that hides the selectors. It also resets them too. * * @returns */ function onClickBody(){ hideTypeSelector(); resetAndHidePlayerSelections(); resetAndHideYearSelections(); resetAndHideWeekSelections(); hideStatNameSelector(); } /** * * A convenience function for hiding all the selector containers. Not much * to it. * * @returns */ function hideSelectorContainers(){ hideTypeSelector(); hidePlayerSelector(); hideYearSelector(); hideWeekSelector(); hideStatNameSelector(); hideTeamSelector(); } /** * * This function switches the element with the given id from visibile to * hidden or back (with the jquery "hide" and "show" functions). * * It decides whether something is visible by using the ":visible" property * in jquery. If it's visible, it hides it. Otherwise, it shows it. * * @param id * @returns */ function toggleVisibilty(id){ //Steps to do: // 1. Get whether the element is visible. // 2. Hide it if it is and show it if it's not. var isElementVisible = isVisible(id); if (isVisible){ $('#' + id).hide(); } else { $('#' + id).show(); } } /** * * A really dumb function for checking whether an element with the given * id is visible or not. Just calls jquery to do the work. * * @param id * @returns */ function isVisible(id){ var isElementVisible = $('#' + id).is(':visible'); return isElementVisible; } /** * * This function will toggle the visibility the weeks for the given week records * at the given index. If they're shown, it'll hide them. If they're hidden, * it'll show them. It's specific to the "weeks won" stat thing for now. * * @param index * @returns */ function toggleShowWeeks(index){ //Steps to do: // 1. Get whether the week records are shown now. // 2. If they are, then hide them and change the link text. // 3. Otherwise, show them and change the link text. var isVisible = $('#week-records-' + index).is(':visible'); if (isVisible){ $('#week-records-' + index).hide(); $('#show-weeks-link-' + index).text('show weeks'); } else { $('#week-records-' + index).show(); $('#show-weeks-link-' + index).text('hide weeks'); } } /** * * This function will get the number rank of the given object in the given list. * It will use the given comparison function to compare the object with other objects * in the given list to decide where it fits, and it'll use the given "sameObjectFunction" * to make sure an object doesn't "tie with itself". * * I made it because I wanted to do it in a few places (the original standings, weeks won standings, * and a few other places). * * The given list <i>doesn't</i> need to be sorted in order for it to find the object's * rank. * * It'll return an object that's like: {rank: 12, tie: true}, so people can get the * numeric rank and whether it ties any other object in the list. * * Doing it this way, you'll have to call it for every object in the list ... This function * is O(n), so that makes ranking every object in a list O(n^2). That kind of sucks, * but it should be ok because we shouldn't be sorting hundreds or thousands of objects. * I felt like it was ok to give up some speed to have it so each of the "standings" * functions not have to duplicate the ranking code. * * @param object * @param list * @param comparisonFunction * @param sameObjectFunction * @returns */ function rank(object, list, comparisonFunction, sameObjectFunction){ //Steps to do: // 1. Create the initial "rank" for the object and assume it has the highest rank. // 2. Go through each object in the list and run the comparison object on it. // 3. If it returns a positive number, that means the object is after the current // one we're comparing it to, so we need to up the rank. // 4. If it says they're the same, and the object hasn't already tied another object, // then use the "sameObjectFunction" to see whether they're the exact same object or not. // 5. If they aren't, then it's a real tie. If they aren't, then it's not. var objectRank = {rank: 1, tie: false}; var numberOfRecordsBetter = 0; var tie = false; for (var index = 0; index < list.length; index++){ var currentObject = list[index]; var comparisonResult = comparisonFunction(object, currentObject); if (comparisonResult > 0){ objectRank.rank++; } else if (comparisonResult == 0){ if (objectRank.tie == false){ var isSameObject = sameObjectFunction(object, currentObject); if (!isSameObject){ objectRank.tie = true; } } } } return objectRank; } /** * * A convenience function that'll sort the given weekRecords array * by each weekRecord's length. A "weekRecord" will have a list * of records for each week inside it. This will sort it so that * the one with the most weeks comes first. * * This is for when we're ranking how many weeks a person has won and * we want the person who's won the most weeks (has the most records) * first. * * @param weekRecords * @returns */ function sortWeekRecords(weekRecords){ //Steps to do: // 1. Just run the sorting function on the records we were given. weekRecords.sort(function (weekRecord1, weekRecord2){ if (weekRecord1.weekRecords.length > weekRecord2.weekRecords.length){ return -1; } else if (weekRecord1.weekRecords.length < weekRecord2.weekRecords.length){ return 1; } //Sort it alphabetically by name if they have the same record. if (weekRecord1.player.name < weekRecord2.player.name){ return -1; } else if (weekRecord1.player.name > weekRecord2.player.name){ return 1; } return 0; }); } /** * * This function will sort the given week records by season and week * so that the "oldest" records appear first. It's here for when we're showing * how many weeks a person one and we want to show the weeks in chronological * order. This function will make sure they're in chronological order. * * @param weekRecords * @returns */ function sortWeekRecordsBySeasonAndWeek(weekRecords){ //Steps to do: // 1. Just run the sorting function on the array // we were given. weekRecords.sort(function (weekRecord1, weekRecord2){ var year1 = parseInt(weekRecord1.season.year); var year2 = parseInt(weekRecord2.season.year); //If the year from one is before the other, we want the earlier one first. if (year1 < year2){ return -1; } //And later one second. else if (year1 > year2){ return 1; } else { //Otherwise, compare on the weeks. var week1 = weekRecord1.week.weekSequenceNumber; var week2 = weekRecord2.week.weekSequenceNumber; //With the earlier week first. if (week1 < week2){ return -1; } else if (week1 > week2){ return 1; } } return 0; }); } /** * * This function will sort the given array of "week records" so that it * goes in ascending order by the week's year and week (so it's in increasing * order by season and by week within each season). * * @param weekRecords * @returns */ function sortWeekRecordsBySeasonWeekAndRecord(weekRecords){ //Steps to do: // 1. Just run the sorting function on the array // we were given. weekRecords.sort(function (weekRecord1, weekRecord2){ var year1 = parseInt(weekRecord1.season.year); var year2 = parseInt(weekRecord2.season.year); //If the year from one is before the other, we want the earlier one first. if (year1 < year2){ return -1; } //And later one second. else if (year1 > year2){ return 1; } //If it's the same year... else { //Compare on the weeks. var week1 = weekRecord1.week.weekSequenceNumber; var week2 = weekRecord2.week.weekSequenceNumber; //With the earlier week first. if (week1 < week2){ return -1; } else if (week1 > week2){ return 1; } //same week, so sort by the record. else { if (weekRecord1.record.wins > weekRecord2.record.wins){ return -1; } else if (weekRecord1.record.wins < weekRecord2.record.wins){ return 1; } else { if (weekRecord1.record.losses < weekRecord2.record.losses){ return -1; } else if (weekRecord1.record.losses > weekRecord2.record.losses){ return 1; } //Same year, week, wins, and losses, sort by the name else { if (weekRecord1.player.name < weekRecord2.player.name){ return -1; } else if (weekRecord1.player.name > weekRecord2.player.name){ return 1; } } } } } return 0; }); } /** * * This function will say whether a "specific" year was selected * (basically if the year isn't "all" or one of the special ones). * * This should go in the selectors javascript file i think. * * @returns */ function isSpecificYearSelected(){ var selectedYears = getSelectedYears(); if (selectedYears.length > 1){ return false; } var selectedYear = selectedYears[0].value; if ('all' == selectedYear || 'jurassic-period' == selectedYear || 'first-year' == selectedYear || 'modern-era' == selectedYear){ return false; } return true; } /** * * This function will say whether a "specific" team was selected * (basically if the team isn't "all"). * * @returns */ function isSpecificTeamSelected(){ var selectedTeams = getSelectedTeams(); if (selectedTeams.length > 1){ return false; } var selectedTeam = selectedTeams[0].value; if ('all' == selectedTeam){ return false; } return true; } /** * * A convenience function for checking whether a single week is selected or not. * * It'll return false if: * 1. There are no selected weeks. * 2. There's more than one selected week. * 3. There's one selected week, but it's the regular season, playoffs, or all. * * If all of those 3 things are false, it'll return true because that means there's a single * week selected and it's not one of the ones that represents multiple weeks. * * @returns */ function isASingleWeekSelected(){ var selectedWeeks = getSelectedWeekValues(); if (isEmpty(selectedWeeks)){ return false; } if (selectedWeeks.length > 1){ return false; } var selectedWeek = selectedWeeks[0]; if ('all' == selectedWeek || 'regular_season' == selectedWeek || 'playoffs' == selectedWeek){ return false; } return true; } /** * * This function will say whether a "specific" week was selected. * If the week is all, "regular-season", or "playoffs", then it takes * that to mean a specific one isn't and a "range" is instead. * * @returns */ function isSpecificWeekSelected(){ var selectedWeeks = getSelectedWeeks(); if (isEmpty(selectedWeeks)){ return false; } var selectedWeek = selectedWeeks[0].value; if ('all' == selectedWeek || 'regular_season' == selectedWeek || 'playoffs' == selectedWeek){ return false; } return true; } /** * * A convenience function for checking whether a single player is selected or not. * It'll return false if the current selected player is "all" or if it has multiple * values. Otherwise, it'll return true. * * @returns */ function isASinglePlayerSelected(){ var selectedPlayer = getSelectedPlayer(); if ('all' == selectedPlayer || doesValueHaveMultipleValues(selectedPlayer)){ return false; } return true; } /** * * This function will say whether a specific player is selected. If the * current selected player is "all", it'll say there isn't. Otherwise, it'll * say there is. * * @returns */ function isSpecificPlayerSelected(){ var selectedPlayers = getSelectedPlayers(); if (selectedPlayers.length > 1){ return false; } var selectedPlayer = selectedPlayers[0].value; if ('all' == selectedPlayer){ return false; } return true; } /** * * This function will get the winning percentage. Here because we almost always want * it formatted the same way, so I figured it was better to do it in a function. * * @param wins * @param losses * @returns */ function getWinningPercentage(wins, losses){ //Steps to do: // 1. Get the actual percentage. // 2. Make it 3 decimal places if it's a real number and blank if it's not. var percentage = wins / (wins + losses); var percentageString = ''; if (!isNaN(percentage)){ percentageString = percentage.toPrecision(3); } return percentageString; } /** * * A convenience function for sorting players by their name. Here in case * we do it in multiple places. * * @param players * @returns */ function sortPlayersByName(players){ //Steps to do: // 1. Just compare each player by its name. players.sort(function (player1, player2){ if (player1.name < player2.name){ return -1; } else if (player1.name > player2.name){ return 1; } return 0; }); } /** * * Here for when we're sorting something alphabetically and we don't * care what kind of string it is. * * @param values * @returns */ function sortAlphabetically(values){ values.sort(function (value1, value2){ if (value1 < value2){ return -1; } else if (value1 > value2){ return 1; } return 0; }); } /** * * Here so we can make sure the pick accuracies are in the right order (with the most * accurate team coming first). * * @param pickAccuracySummaries * @returns */ function sortPickAccuracySummariesByTimesRight(pickAccuracySummaries){ //Steps to do: // 1. Just sort them by how many times the person was right picking a team. pickAccuracySummaries.sort(function (pickAccuracySummaryA, pickAccuracySummaryB){ //More times right = front of the list. if (pickAccuracySummaryA.timesRight > pickAccuracySummaryB.timesRight){ return -1; } //Fewer times right = back of the list. else if (pickAccuracySummaryA.timesRight < pickAccuracySummaryB.timesRight){ return 1; } //If they have the same times right, sort on times wrong. if (pickAccuracySummaryA.timesWrong < pickAccuracySummaryB.timesWrong){ return -1; } //Fewer times right = back of the list. else if (pickAccuracySummaryA.timesWrong > pickAccuracySummaryB.timesWrong){ return 1; } //If they have the same times right and wrong, sort by player name. if (pickAccuracySummaryA.player.name < pickAccuracySummaryB.player.name){ return -1; } else if (pickAccuracySummaryA.player.name > pickAccuracySummaryB.player.name){ return 1; } //If they have the same player name, sort by team abbreviation. if (pickAccuracySummaryA.team.abbreviation < pickAccuracySummaryB.team.abbreviation){ return -1; } else if (pickAccuracySummaryA.team.abbreviation > pickAccuracySummaryB.team.abbreviation){ return 1; } return 0; }); } /** * * Shows or hides the details for pick accuracy. If it's currently shown, it'll hide * it and if it's currently hidden, it'll show it. * * @param index * @returns */ function toggleShowPickAccuracyDetails(index){ //Steps to do: // 1. Get whether the container at the index is shown. // 2. Hide it if it is, show it if it's not. var isVisible = $('#pick-accuracy-details-' + index).is(':visible'); if (isVisible){ $('#pick-accuracy-details-' + index).hide(); $('#pick-accuracy-details-link-' + index).text('Details'); } else { $('#pick-accuracy-details-' + index).show(); $('#pick-accuracy-details-link-' + index).text('Hide'); } } /** * * This function will create a link that'll take them to the picks for the given * year, week, team, and player (all optional) and show the given text. Here because * we wanted to do this in a few places, so I figured it was best to do it as a function. * * @param linkText * @param year * @param week * @param team * @param player * @returns */ function createPicksLink(linkText, year, week, team, player){ //Steps to do: // 1. Just make a link that'll call the javascript function // that actually updates the view. // 2. All the arguments are optional, so only add them in if // they're given. var picksLink = '<a href="javascript:" onClick="showPickView('; if (isDefined(year)){ var yearValue = year; if (Array.isArray(year)){ yearValue = arrayToDelimitedValue(year, ','); } picksLink = picksLink + '\'' + yearValue + '\', '; } else { picksLink = picksLink + 'null, '; } if (isDefined(week)){ var weekValue = week; if (Array.isArray(week)){ weekValue = arrayToDelimitedValue(week, ','); } picksLink = picksLink + '\'' + weekValue + '\', '; } else { picksLink = picksLink + 'null, '; } if (isDefined(team)){ var teamValue = team; if (Array.isArray(team)){ teamValue = arrayToDelimitedValue(team, ','); } picksLink = picksLink + '\'' + teamValue + '\', '; } else { picksLink = picksLink + 'null, '; } if (isDefined(player)){ var playerValue = player; if (Array.isArray(player)){ playerValue = arrayToDelimitedValue(player, ','); } picksLink = picksLink + '\'' + playerValue + '\''; } else { picksLink = picksLink + 'null'; } picksLink = picksLink + ');">' + linkText + '</a>'; return picksLink; } /** * * This function will show the picks grid for the given year, week, team, and player. * All the arguments are optional. It will just set each one as the selected * year, week, team, and player (if it's given) and then cause the picks to be shown. * * It'll flip the global "havePicksBeenShown" switch to true so that the view shows * all the picks for the given parameters and doesn't try to overrule it and only show * a week's worth of picks. * * @param year * @param week * @param team * @param player * @returns */ function showPickView(year, week, team, player){ //Steps to do: // 1. If we're coming from this function, then we don't want // the updatePicks function saying "no, you can't see all the picks", // so we need to flip the switch that disables that feature. // 2. Set all the parameters that were given. // 3. Call the function that'll show them on the screen. //If this switch is true, we'll show the picks for the parameters no matter //whether it's a week's worth or not. If it's not, it'll show only a week's //worth as a way to prevent accidentally showing all the picks (which takes a while to do). NFL_PICKS_GLOBAL.havePicksBeenShown = true; setSelectedType('picks'); if (isDefined(year)){ setSelectedYears(year); } if (isDefined(week)){ setSelectedWeeks(week); } if (isDefined(player)){ setSelectedPlayers(player); } if (isDefined(team)){ selectSingleTeamFull(team); } updateView(); } /** * * This function will shorten the given label so it's easier * to show on phones and stuff with small widths. Up yours, twitter * and bootstrap. * * @param label * @returns */ function shortenWeekLabel(label){ if ('Playoffs - Wild Card' == label){ return 'Wild card'; } else if ('Playoffs - Divisional' == label){ return 'Divisional'; } else if ('Playoffs - Conference Championship' == label || 'Conference Championship' == label){ return 'Conf champ'; } else if ('Playoffs - Super Bowl' == label){ return 'Super bowl'; } return label; } /** * * This function will check whether the given value has multiple values * in it or not. Basically, it'll return true if the given value is defined * and it has a comma in it. It assumes the given value is a string and multiple * values are separated by commas in that string. * * @param value * @returns */ function doesValueHaveMultipleValues(value){ if (isDefined(value) && value.indexOf(',') != -1){ return true; } return false; } function showYearContainer(){ $('#yearContainer').show(); } function hideYearContainer(){ $('#yearContainer').hide(); } function showPlayerContainer(){ $('#playerContainer').show(); } function hidePlayerContainer(){ $('#playerContainer').hide(); } function showWeekContainer(){ $('#weekContainer').show(); } function hideWeekContainer(){ $('#weekContainer').hide(); } function showTeamContainer(){ $('#teamContainer').show(); } function hideTeamContainer(){ $('#teamContainer').hide(); } function showStatNameContainer(){ $('#statNameContainer').show(); } function hideStatNameContainer(){ $('#statNameContainer').hide(); }
hhhayssh/nflpicks
src/main/webapp/javascript/nflpicks.js
JavaScript
unlicense
78,271
import React from 'react'; import Moment from 'moment'; import { Embed, Grid } from 'semantic-ui-react'; const VideoDetail = ({video}) => { if (!video){ return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; const pubTime = Moment(video.snippet.publishedAt).format('DD-MM-YYYY, h:mm:ss a') return ( <Grid.Row stretched> <Grid.Column > <Embed active autoplay={false} brandedUI={false} id={videoId} placeholder='http://semantic-ui.com/images/image-16by9.png' src={url} source='youtube'/> <div className="details"> <h5 className="meta-big-title">{video.snippet.title}</h5> <div className="meta-description">{video.snippet.description}</div> <div className="meta-time">Published: {pubTime}</div> </div> </Grid.Column> </Grid.Row> ); }; export default VideoDetail;
suemcnab/react-youtube-pxn-open
src/components/video_detail.js
JavaScript
unlicense
891
/** * [★★★★]200. Number of Islands * finish: 2016-12-06 * https://leetcode.com/problems/number-of-islands/ */ /** * @param {character[][]} grid * @return {number} */ var numIslands = function (grid) { var count = 0, i, j; for (i = 0; i < grid.length; i++) { for (j = 0; j < grid[i].length; j++) { if (grid[i][j] == 1) { count += 1; grid[i] = modify(grid[i], j, 2); visitAround(grid, i, j); } else { grid[i] = modify(grid[i], j, 2); } } } return count; }; function modify(str, index, val) { var arr = str.split(''); arr[index] = val; return arr.join(''); } function visitAround(grid, i, j) { // top, right, down, left visit(grid, i - 1, j); visit(grid, i, j + 1); visit(grid, i + 1, j); visit(grid, i, j - 1); } function visit(grid, row, col) { if (typeof grid[row] !== 'undefined' && typeof grid[row][col] !== 'undefined') { if (grid[row][col] == 1) { grid[row] = modify(grid[row], col, 2); visitAround(grid, row, col); } else { grid[row] = modify(grid[row], col, 2); } } } write('algorithms: 200. Number of Islands', 'title'); write(numIslands(["10101", "11010", "10101", "01010"])); write(numIslands(["11110", "11010", "11000", "00000"]));
wyf2learn/leetcode
problems/algorithms/200.number-of-islands.js
JavaScript
unlicense
1,394
import React from 'react' import { List, ListItem, LiAction, LiSecondary, LiPrimary, LiAvatar, Checkbox, Radio, Switch, Icon, } from 'styled-mdl' const demo = () => ( <List> <ListItem> <LiPrimary> <LiAvatar> <Icon name="person" /> </LiAvatar> Bryan Cranston </LiPrimary> <LiSecondary> <LiAction> <Checkbox defaultChecked /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar> <Icon name="person" /> </LiAvatar> Aaron Paul </LiPrimary> <LiSecondary> <LiAction> <Radio /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar> <Icon name="person" /> </LiAvatar> Bob Odenkirk </LiPrimary> <LiSecondary> <LiAction> <Switch defaultChecked /> </LiAction> </LiSecondary> </ListItem> </List> ) const caption = 'Avatars and controls' const code = `<List> <ListItem> <LiPrimary> <LiAvatar><Icon name="person" /></LiAvatar> Bryan Cranston </LiPrimary> <LiSecondary> <LiAction> <Checkbox defaultChecked /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar><Icon name="person" /></LiAvatar> Aaron Paul </LiPrimary> <LiSecondary> <LiAction> <Radio /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar><Icon name="person" /></LiAvatar> Bob Odenkirk </LiPrimary> <LiSecondary> <LiAction> <Switch defaultChecked /> </LiAction> </LiSecondary> </ListItem> </List>` export default { demo, caption, code }
isogon/styled-mdl-website
demos/lists/demos/avatarsAndControls.js
JavaScript
unlicense
1,826