<commit_before>import {LitElement, html} from "lit";
import UtilsNew from "./../../core/utilsNew.js";
import Region from "../../core/bioinfo/region.js";
import GenomeBrowser from "../../genome-browser/genome-browser.js";

import FeatureTrack from "../../genome-browser/tracks/feature-track.js";
import GeneOverviewTrack from "../../genome-browser/tracks/gene-overview-track.js";
import GeneTrack from "../../genome-browser/tracks/gene-track.js";
import SequenceTrack from "../../genome-browser/tracks/sequence-track.js";
import VariantTrack from "../../genome-browser/tracks/variant-track.js";
import OpenCGAVariantTrack from "../../genome-browser/tracks/opencga-variant-track.js";
import OpenCGAAlignmentTrack from "../../genome-browser/tracks/opencga-alignment-track.js";

export default class GenomeBrowserComponent extends LitElement {

    constructor() {
        super();
        this.#init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object,
            },
            region: {
                type: Object,
            },
            species: {
                type: String,
            },
            tracks: {
                type: Array,
            },
            active: {
                type: Boolean,
            },
            config: {
                type: Object,
            },
        };
    }

    #init() {
        this._prefix = UtilsNew.randomString(8);

        this.genomeBrowser = null;
        this.active = true;
        this.species = "hsapiens";
        this.tracks = [];
        this.config = this.getDefaultConfig();

        this.prevRegion = null;
    }

    updated(changedProperties) {
        if (changedProperties.has("opencgaSession" || changedProperties.has("config") || changedProperties.has("tracks"))) {
            this.opencgaSessionOrConfigObserver();
        }

        if (changedProperties.has("region") || changedProperties.has("active")) {
            this.propertyObserver();
        }
    }

    opencgaSessionOrConfigObserver() {
        if (this.opencgaSession && this.config && this.tracks) {
            if (this.genomeBrowser) {
                this.genomeBrowser.destroy();
                this.genomeBrowser = null;
            }

            // Check the active property to initialize genomebrowser
            if (this.active) {
                this.initGenomeBrowser();
            }
        }
    }

    propertyObserver() {
        if (this.active) {
            // Check for no genomebrowser instance ready
            if (!this.genomeBrowser) {
                return this.initGenomeBrowser();
            }

            // Check if region has been provided and is different from prev region
            if (this.region) {
                const nextRegion = new Region(this.region).toString();

                if (this.prevRegion !== nextRegion) {
                    this.genomeBrowser.setRegion(this.region);
                    this.prevRegion = nextRegion;
                }
            }
        }
    }

    initGenomeBrowser() {
        const parent = this.querySelector(`div#${this._prefix}GenomeBrowser`);
        const config = {
            ...this.getDefaultConfig(),
            ...this.config,
        };

        this.genomeBrowser = new GenomeBrowser(parent, {
            width: parent.getBoundingClientRect().width || 100,
            region: new Region(this.region),
            resizable: true,
            ...config,
        });

        // When GB is ready add tracks and draw
        this.genomeBrowser.on("ready", () => {
            this.genomeBrowser.addOverviewTracks(this.getOverviewTracks());
            this.genomeBrowser.addTracks(this.getDetailTracks());
            this.genomeBrowser.draw();
        });

        // Save current region
        this.prevRegion = new Region(this.region).toString();
    }

    // Get only overview tracks
    getOverviewTracks() {
        return this.parseTracks(this.tracks.filter(track => !!track.overview));
    }

    // Get only detail tracks
    getDetailTracks() {
        return this.parseTracks(this.tracks.filter(track => !track.overview));
    }

    parseTracks(tracks) {
        return tracks.map(track => {
            switch (track.type) {
                case "sequence":
                    return new SequenceTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene":
                    return new GeneTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene-overview":
                    return new GeneOverviewTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "variant":
                    return new VariantTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "opencga-variant":
                    return new OpenCGAVariantTrack({
                        opencgaClient: this.opencgaSession.opencgaClient,
                        opencgaStudy: this.opencgaSession.study.fqn,
                        ...track.config,
                    });
                case "opencga-alignment":
                    return new OpenCGAAlignmentTrack({
                        opencgaClient: this.opencgaSession.opencgaClient,
                        opencgaStudy: this.opencgaSession.study.fqn,
                        ...track.config,
                    });
                default:
                    return new FeatureTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
            }
        });
    }

    render() {
        return html`

        `;
    }

    getDefaultConfig() {
        return {};
    }

}

customElements.define("genome-browser", GenomeBrowserComponent);
<commit_msg>wc: add default region to GB webcomponent #TASK-983<commit_after>import {LitElement, html} from "lit";
import UtilsNew from "./../../core/utilsNew.js";
import Region from "../../core/bioinfo/region.js";
import GenomeBrowser from "../../genome-browser/genome-browser.js";

import FeatureTrack from "../../genome-browser/tracks/feature-track.js";
import GeneOverviewTrack from "../../genome-browser/tracks/gene-overview-track.js";
import GeneTrack from "../../genome-browser/tracks/gene-track.js";
import SequenceTrack from "../../genome-browser/tracks/sequence-track.js";
import VariantTrack from "../../genome-browser/tracks/variant-track.js";
import OpenCGAVariantTrack from "../../genome-browser/tracks/opencga-variant-track.js";
import OpenCGAAlignmentTrack from "../../genome-browser/tracks/opencga-alignment-track.js";

export default class GenomeBrowserComponent extends LitElement {

    constructor() {
        super();
        this.#init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object,
            },
            region: {
                type: Object,
            },
            species: {
                type: String,
            },
            tracks: {
                type: Array,
            },
            active: {
                type: Boolean,
            },
            config: {
                type: Object,
            },
        };
    }

    #init() {
        this._prefix = UtilsNew.randomString(8);

        this.genomeBrowser = null;
        this.active = true;
        this.species = "hsapiens";
        this.tracks = [];
        this.config = this.getDefaultConfig();

        this.defaultRegion = "13:32996311-32996450";
        this.prevRegion = null;
    }

    updated(changedProperties) {
        if (changedProperties.has("opencgaSession" || changedProperties.has("config") || changedProperties.has("tracks"))) {
            this.opencgaSessionOrConfigObserver();
        }

        if (changedProperties.has("region") || changedProperties.has("active")) {
            this.propertyObserver();
        }
    }

    opencgaSessionOrConfigObserver() {
        if (this.opencgaSession && this.config && this.tracks) {
            if (this.genomeBrowser) {
                this.genomeBrowser.destroy();
                this.genomeBrowser = null;
            }

            // Check the active property to initialize genomebrowser
            if (this.active) {
                this.initGenomeBrowser();
            }
        }
    }

    propertyObserver() {
        if (this.active) {
            // Check for no genomebrowser instance ready
            if (!this.genomeBrowser) {
                return this.initGenomeBrowser();
            }

            // Check if region has been provided and is different from prev region
            if (this.region) {
                const nextRegion = new Region(this.region).toString();

                if (this.prevRegion !== nextRegion) {
                    this.genomeBrowser.setRegion(this.region);
                    this.prevRegion = nextRegion;
                }
            }
        }
    }

    initGenomeBrowser() {
        const parent = this.querySelector(`div#${this._prefix}GenomeBrowser`);
        const initialRegion = this.region || this.defaultRegion;
        const config = {
            ...this.getDefaultConfig(),
            ...this.config,
        };

        this.genomeBrowser = new GenomeBrowser(parent, {
            width: parent.getBoundingClientRect().width || 100,
            region: new Region(initialRegion),
            resizable: true,
            ...config,
        });

        // When GB is ready add tracks and draw
        this.genomeBrowser.on("ready", () => {
            this.genomeBrowser.addOverviewTracks(this.getOverviewTracks());
            this.genomeBrowser.addTracks(this.getDetailTracks());
            this.genomeBrowser.draw();
        });

        // Save current region
        this.prevRegion = new Region(initialRegion).toString();
    }

    // Get only overview tracks
    getOverviewTracks() {
        return this.parseTracks(this.tracks.filter(track => !!track.overview));
    }

    // Get only detail tracks
    getDetailTracks() {
        return this.parseTracks(this.tracks.filter(track => !track.overview));
    }

    parseTracks(tracks) {
        return tracks.map(track => {
            switch (track.type) {
                case "sequence":
                    return new SequenceTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene":
                    return new GeneTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "gene-overview":
                    return new GeneOverviewTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "variant":
                    return new VariantTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
                case "opencga-variant":
                    return new OpenCGAVariantTrack({
                        opencgaClient: this.opencgaSession.opencgaClient,
                        opencgaStudy: this.opencgaSession.study.fqn,
                        ...track.config,
                    });
                case "opencga-alignment":
                    return new OpenCGAAlignmentTrack({
                        opencgaClient: this.opencgaSession.opencgaClient,
                        opencgaStudy: this.opencgaSession.study.fqn,
                        ...track.config,
                    });
                default:
                    return new FeatureTrack({
                        cellBaseClient: this.config.cellBaseClient,
                        ...track.config,
                    });
            }
        });
    }

    render() {
        return html`

        `;
    }

    getDefaultConfig() {
        return {};
    }

}

customElements.define("genome-browser", GenomeBrowserComponent);
<|endoftext|>


<commit_before>import {
  ContentNodeResource,
  ExamResource,
  ExamLogResource,
  ExamAttemptLogResource,
} from 'kolibri.resources';
import samePageCheckGenerator from 'kolibri.utils.samePageCheckGenerator';
import { convertExamQuestionSourcesV0V1 } from 'kolibri.utils.exams';
import { assessmentMetaDataState } from 'kolibri.coreVue.vuex.mappers';
import { now } from 'kolibri.utils.serverClock';
import ConditionalPromise from 'kolibri.lib.conditionalPromise';
import router from 'kolibri.coreVue.router';
import shuffled from 'kolibri.utils.shuffled';
import { canViewExam } from '../../utils/exams';
import { PageNames, ClassesPageNames } from '../../constants';
import { contentState } from '../coreLearn/utils';
import { calcQuestionsAnswered } from './utils';

export function showExam(store, params) {
  let questionNumber = params.questionNumber;
  const { classId, examId } = params;
  store.commit('CORE_SET_PAGE_LOADING', true);
  store.commit('SET_PAGE_NAME', ClassesPageNames.EXAM_VIEWER);
  // Reset examAttemptLogs, so that it will not merge into another exam.
  store.commit('RESET_EXAM_ATTEMPT_LOGS');
  const userId = store.getters.currentUserId;
  const examParams = { user: userId, exam: examId };

  if (!userId) {
    store.commit('CORE_SET_ERROR', 'You must be logged in as a learner to view this page');
    store.commit('CORE_SET_PAGE_LOADING', false);
  } else {
    questionNumber = Number(questionNumber); // eslint-disable-line no-param-reassign

    const promises = [
      ExamResource.fetchModel({ id: examId }),
      ExamLogResource.fetchCollection({ getParams: examParams }),
      ExamAttemptLogResource.fetchCollection({ getParams: examParams }),
      store.dispatch('setAndCheckChannels'),
    ];
    ConditionalPromise.all(promises).only(
      samePageCheckGenerator(store),
      ([exam, examLogs, examAttemptLogs]) => {
        // Local copy of exam attempt logs
        const attemptLogs = {};

        if (examLogs.length > 0 && examLogs.some(log => !log.closed)) {
          store.commit('SET_EXAM_LOG', examLogs.find(log => !log.closed));
        } else if (examLogs.length > 0 && examLogs.some(log => log.closed)) {
          return router.replace({ name: PageNames.CONTENT_UNAVAILABLE });
        } else {
          ExamLogResource.createModel({ ...examParams, closed: false })
            .save()
            .then(newExamLog => {
              store.commit('SET_EXAM_LOG', newExamLog);
              return ExamLogResource.unCacheCollection(examParams);
            });
        }

        if (!canViewExam(exam, store.state.examLog)) {
          return router.replace({ name: ClassesPageNames.CLASS_ASSIGNMENTS, params: { classId } });
        }
        // Sort through all the exam attempt logs retrieved and organize them into objects
        // keyed first by content_id and then item id under that.
        examAttemptLogs.forEach(log => {
          const { content_id, item } = log;
          if (!attemptLogs[content_id]) {
            attemptLogs[content_id] = {};
          }
          attemptLogs[content_id][item] = { ...log };
        });

        // Sort through all the exam attempt logs retrieved and organize them into objects
        // keyed first by content_id and then item id under that.
        examAttemptLogs.forEach(log => {
          const { content_id, item } = log;
          if (!attemptLogs[content_id]) {
            attemptLogs[content_id] = {};
          }
          attemptLogs[content_id][item] = { ...log };
        });

        let contentPromise;
        if (exam.question_sources.length) {
          contentPromise = ContentNodeResource.fetchCollection({
            getParams: {
              ids: exam.question_sources.map(item => item.exercise_id),
            },
          });
        } else {
          contentPromise = ConditionalPromise.resolve([]);
        }
        contentPromise.only(
          samePageCheckGenerator(store),
          contentNodes => {
            const questionIds = {};
            contentNodes.forEach(node => {
              questionIds[node.id] = assessmentMetaDataState(node).assessmentIds;
            });

            // If necessary, convert the question source info
            let questions =
              exam.data_model_version === 0
                ? convertExamQuestionSourcesV0V1(exam.question_sources, exam.seed, questionIds)
                : exam.question_sources;

            // When necessary, randomize the questions for the learner.
            // Seed based on the user ID so they see a consistent order each time.
            if (!exam.learners_see_fixed_order) {
              questions = shuffled(questions, store.state.core.session.user_id);
            }

            // Exam is drawing solely on malformed exercise data, best to quit now
            if (questions.some(question => !question.question_id)) {
              store.dispatch(
                'handleError',
                `This exam cannot be displayed:\nQuestion sources: ${JSON.stringify(
                  questions
                )}\nExam: ${JSON.stringify(exam)}`
              );
              return;
            }
            // Illegal question number!
            else if (questionNumber >= questions.length) {
              store.dispatch(
                'handleError',
                `Question number ${questionNumber} is not valid for this exam`
              );
              return;
            }

            const currentQuestion = questions[questionNumber];
            const itemId = currentQuestion.question_id;
            const contentId = currentQuestion.exercise_id;
            const questionsAnswered = Math.max(
              store.state.examViewer.questionsAnswered || 0,
              calcQuestionsAnswered(attemptLogs)
            );

            if (!attemptLogs[currentQuestion.exercise_id]) {
              attemptLogs[currentQuestion.exercise_id] = {};
            }
            if (!attemptLogs[contentId][itemId]) {
              attemptLogs[contentId][itemId] = {
                start_timestamp: now(),
                completion_timestamp: null,
                end_timestamp: null,
                item: itemId,
                complete: false,
                time_spent: 0,
                correct: 0,
                answer: null,
                simple_answer: '',
                interaction_history: [],
                hinted: false,
                content_id: contentId,
              };
            }
            store.commit('SET_EXAM_ATTEMPT_LOGS', attemptLogs);
            store.commit('examViewer/SET_STATE', {
              content: contentState(contentNodes.find(node => node.id === contentId)),
              currentAttempt: attemptLogs[contentId][itemId],
              currentQuestion,
              exam,
              itemId,
              questionNumber,
              questions,
              questionsAnswered,
            });
            store.commit('CORE_SET_PAGE_LOADING', false);
            store.commit('CORE_SET_ERROR', null);
          },
          error => {
            store.dispatch('handleApiError', error);
          }
        );
      },
      error => {
        store.dispatch('handleApiError', error);
      }
    );
  }
}
<commit_msg>In showExam handler, redirect to the report if the exam is closed<commit_after>import {
  ContentNodeResource,
  ExamResource,
  ExamLogResource,
  ExamAttemptLogResource,
} from 'kolibri.resources';
import samePageCheckGenerator from 'kolibri.utils.samePageCheckGenerator';
import { convertExamQuestionSourcesV0V1 } from 'kolibri.utils.exams';
import { assessmentMetaDataState } from 'kolibri.coreVue.vuex.mappers';
import { now } from 'kolibri.utils.serverClock';
import ConditionalPromise from 'kolibri.lib.conditionalPromise';
import router from 'kolibri.coreVue.router';
import shuffled from 'kolibri.utils.shuffled';
import { canViewExam } from '../../utils/exams';
import { ClassesPageNames } from '../../constants';
import { contentState } from '../coreLearn/utils';
import { calcQuestionsAnswered } from './utils';

export function showExam(store, params) {
  let questionNumber = params.questionNumber;
  const { classId, examId } = params;
  store.commit('CORE_SET_PAGE_LOADING', true);
  store.commit('SET_PAGE_NAME', ClassesPageNames.EXAM_VIEWER);
  // Reset examAttemptLogs, so that it will not merge into another exam.
  store.commit('RESET_EXAM_ATTEMPT_LOGS');
  const userId = store.getters.currentUserId;
  const examParams = { user: userId, exam: examId };

  if (!userId) {
    store.commit('CORE_SET_ERROR', 'You must be logged in as a learner to view this page');
    store.commit('CORE_SET_PAGE_LOADING', false);
  } else {
    questionNumber = Number(questionNumber); // eslint-disable-line no-param-reassign

    const promises = [
      ExamResource.fetchModel({ id: examId }),
      ExamLogResource.fetchCollection({ getParams: examParams }),
      ExamAttemptLogResource.fetchCollection({ getParams: examParams }),
      store.dispatch('setAndCheckChannels'),
    ];
    ConditionalPromise.all(promises).only(
      samePageCheckGenerator(store),
      ([exam, examLogs, examAttemptLogs]) => {
        // Local copy of exam attempt logs
        const attemptLogs = {};

        if (examLogs.length > 0 && examLogs.some(log => !log.closed)) {
          store.commit('SET_EXAM_LOG', examLogs.find(log => !log.closed));
        } else if (examLogs.length > 0 && examLogs.some(log => log.closed)) {
          // If exam is closed, then redirect to route for the report
          return router.replace({
            name: ClassesPageNames.EXAM_REPORT_VIEWER,
            params: {
              ...examParams,
              questionNumber: 0,
              questionInteraction: 0,
            },
          });
        } else {
          ExamLogResource.createModel({ ...examParams, closed: false })
            .save()
            .then(newExamLog => {
              store.commit('SET_EXAM_LOG', newExamLog);
              return ExamLogResource.unCacheCollection(examParams);
            });
        }

        if (!canViewExam(exam, store.state.examLog)) {
          return router.replace({ name: ClassesPageNames.CLASS_ASSIGNMENTS, params: { classId } });
        }
        // Sort through all the exam attempt logs retrieved and organize them into objects
        // keyed first by content_id and then item id under that.
        examAttemptLogs.forEach(log => {
          const { content_id, item } = log;
          if (!attemptLogs[content_id]) {
            attemptLogs[content_id] = {};
          }
          attemptLogs[content_id][item] = { ...log };
        });

        // Sort through all the exam attempt logs retrieved and organize them into objects
        // keyed first by content_id and then item id under that.
        examAttemptLogs.forEach(log => {
          const { content_id, item } = log;
          if (!attemptLogs[content_id]) {
            attemptLogs[content_id] = {};
          }
          attemptLogs[content_id][item] = { ...log };
        });

        let contentPromise;
        if (exam.question_sources.length) {
          contentPromise = ContentNodeResource.fetchCollection({
            getParams: {
              ids: exam.question_sources.map(item => item.exercise_id),
            },
          });
        } else {
          contentPromise = ConditionalPromise.resolve([]);
        }
        contentPromise.only(
          samePageCheckGenerator(store),
          contentNodes => {
            const questionIds = {};
            contentNodes.forEach(node => {
              questionIds[node.id] = assessmentMetaDataState(node).assessmentIds;
            });

            // If necessary, convert the question source info
            let questions =
              exam.data_model_version === 0
                ? convertExamQuestionSourcesV0V1(exam.question_sources, exam.seed, questionIds)
                : exam.question_sources;

            // When necessary, randomize the questions for the learner.
            // Seed based on the user ID so they see a consistent order each time.
            if (!exam.learners_see_fixed_order) {
              questions = shuffled(questions, store.state.core.session.user_id);
            }

            // Exam is drawing solely on malformed exercise data, best to quit now
            if (questions.some(question => !question.question_id)) {
              store.dispatch(
                'handleError',
                `This exam cannot be displayed:\nQuestion sources: ${JSON.stringify(
                  questions
                )}\nExam: ${JSON.stringify(exam)}`
              );
              return;
            }
            // Illegal question number!
            else if (questionNumber >= questions.length) {
              store.dispatch(
                'handleError',
                `Question number ${questionNumber} is not valid for this exam`
              );
              return;
            }

            const currentQuestion = questions[questionNumber];
            const itemId = currentQuestion.question_id;
            const contentId = currentQuestion.exercise_id;
            const questionsAnswered = Math.max(
              store.state.examViewer.questionsAnswered || 0,
              calcQuestionsAnswered(attemptLogs)
            );

            if (!attemptLogs[currentQuestion.exercise_id]) {
              attemptLogs[currentQuestion.exercise_id] = {};
            }
            if (!attemptLogs[contentId][itemId]) {
              attemptLogs[contentId][itemId] = {
                start_timestamp: now(),
                completion_timestamp: null,
                end_timestamp: null,
                item: itemId,
                complete: false,
                time_spent: 0,
                correct: 0,
                answer: null,
                simple_answer: '',
                interaction_history: [],
                hinted: false,
                content_id: contentId,
              };
            }
            store.commit('SET_EXAM_ATTEMPT_LOGS', attemptLogs);
            store.commit('examViewer/SET_STATE', {
              content: contentState(contentNodes.find(node => node.id === contentId)),
              currentAttempt: attemptLogs[contentId][itemId],
              currentQuestion,
              exam,
              itemId,
              questionNumber,
              questions,
              questionsAnswered,
            });
            store.commit('CORE_SET_PAGE_LOADING', false);
            store.commit('CORE_SET_ERROR', null);
          },
          error => {
            store.dispatch('handleApiError', error);
          }
        );
      },
      error => {
        store.dispatch('handleApiError', error);
      }
    );
  }
}
<|endoftext|>


<commit_before>var IndigoAdmin = (function() {
	'use strict';

	// var console = console ? console : {
	// 	log: function() {}
	// };
	try {
		var Unity = external.getUnityObject(1.0);
	} catch(e) {}

	function pageInit (base_url) {

		console.log('Incorrectly inline styled elements: ', $('[style]:not(.menu-gravatar)'));

		$('.datatables').each(function() {

			// Custom initial filter and column options
			var aoSearchCols = [];
			var aoColumns = [];
			var controls = [];
			$(this).find('.filter:first').children('[data-filter]').each(function(index, el) {
				var control = $(el).data('control') ? $(el).data('control') : undefined;
				var filter = $(el).data('filter');
				var val;

				switch(filter) {
					case 'text':
					case 'number':
						if(control === undefined) {
							control = 'input:first';
						}
						break;
					case 'select':
						if(control === undefined) {
							control = 'select:first';
						}
						break;
					case 'none':
					case false:
					case '':
					case 'null':
					case null:
					case undefined:
						var val = false;
						control = false;
						filter = 'none';
						break;
					case 'range':
						if(control === undefined) {
							control = 'input:nth-child(1), input:nth-child(2)';
						}

						val = [];

						$(el).find(control).each(function(index, el) {
							val[index] = $(el).val();
						});
						break;
				}

				if (val === undefined) {
					val = $(el).find(control).val();
				}

				controls[index] = {
					'control': control,
					'filter': filter
				};

				// Column options
				aoColumns[index] = {
					'bSearchable': ! $(el).hasClass('no-search'),
					'bSortable': ! $(el).hasClass('no-sort'),
					'sFilter': $(el).data('filter')
				};

				aoSearchCols[index] = val ? {'sSearch': JSON.stringify(val)} : null;

				$.extend(aoColumns[index], $(el).data('options'));
			});

			// Is this a table? If not find the first table
			if ($(this).is('table')) {
				var table = this;
			} else {
				var table = $(this).find('table:first').get();
			}

			var dtInstance = $(table).dataTable({
				"oLanguage": {
					"sUrl": base_url + "translation/datatables.json"
				},
				"sPaginationType": "bs_full",
				"sDom": "<'panel-heading'<'pull-right'f><'pull-left'l><'pull-left'>r<'clearfix'>><'table-responsive't>p",
				"bProcessing": $(this).data('source') ? true : false,
				"bServerSide": $(this).data('source') ? true : false,
				"sAjaxSource": $(this).data('source'),
				"aoSearchCols": aoSearchCols,
				"aoColumns": aoColumns.length > 0 ? aoColumns : null,
				"fnInitComplete": function(oSettings, json) {
					var datatable = this;
					// SEARCH - Add the placeholder for Search and Turn this into in-line form control
					var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input');
					search_input.attr('placeholder', (oSettings && oSettings.oLanguage && oSettings.oLanguage.sSearchPlaceholder) ? oSettings.oLanguage.sSearchPlaceholder : 'Search all fields');
					search_input.addClass('form-control input-sm');
					// LENGTH - Inline-Form control
					var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select');
					// length_sel.addClass('form-control input-sm');
					length_sel.selectpicker().selectpicker('setStyle', 'btn-sm', 'add');
				},
				"fnServerData": function(sSource, aoData, fnCallback, oSettings) {
					$.each($(this).data(), function(index, val) {
						aoData.push({'name': index, 'value': val});
					});

					$.each(oSettings.aoColumns, function(index, val) {
						aoData.push({'name': 'sFilter_'+index, 'value': val.sFilter});
					});

					$.ajax( {
						"dataType": 'json',
						"type": "POST",
						"url": sSource,
						"data": aoData,
						"success": function(response, result, xhr) {
							console.log(result);
							fnCallback(response, result, xhr);
						},
						"timeout": 15000,
						"error": function(param) {
							console.log(param);
						}
					} );
				},
			});

			// All select filters should be selectpickers
			dtInstance.find('.filter select').selectpicker();

			// Find filters
			var filters = dtInstance.find('.filter');

			// Filter mechanism on filter control change
			// Filter syn mechanism across the same inputs, selects
			// (Assuming that all filter groups are identical to the others)
			$.each(controls, function(index, el) {
				if (el.filter !== 'none') {
					var c = filters.children('[data-filter]:nth-child(' + (index+1) + ')').find(el.control);

					// Do the filtering
					switch(el.filter) {
						case 'text':
						case 'number':
							c.change(function() {
								dtInstance.fnFilter(JSON.stringify($(this).val()), index);
							}).on('reset', function() {
								$(this).val('');
							}).on('keypress keyup paste change', function(event) {
								c.val($(this).val());
							});;
							break;
						case 'select':
							c.on('change', function() {
								dtInstance.fnFilter(JSON.stringify($(this).val()), index);
								c.val($(this).val()).selectpicker('refresh');
							}).on('reset', function() {
								$(this).val([]).selectpicker('refresh');
							});
							break;
						case 'range':
							var odd = c.filter(':odd');
							var even = c.filter(':even');

							odd.change(function(event) {
								var val = [
									even.eq($(this).index()).val(),
									$(this).val()
								];
								dtInstance.fnFilter(JSON.stringify(val), index);
							}).on('keypress keyup paste change', function(event) {
								odd.val($(this).val());
							});

							even.change(function(event) {
								var val = [
									$(this).val(),
									odd.eq($(this).index()).val()
								];
								dtInstance.fnFilter(JSON.stringify(val), index);
							}).on('keypress keyup paste change', function(event) {
								even.val($(this).val());
							});

							c.on('reset', function() {
								$(this).val('');
							});
							break;
					}

					$(filters).find('[type=reset]').click(function() {
						c.trigger('reset');
					});
				}
			});

			// Filter and sorting reset mechanism (reset table)
			$(this).find('[type=reset]').click(function() {
				dtInstance.fnFilterClear();
				// dtInstance.fnSortNeutral();
			});
		}); // end .datatables each

		$('.datetime').each(function() {
			$(this).datetimepicker({
				'language' : 'hu-HU',
				icons: {
					time: "fa fa-clock-o",
					date: "fa fa-calendar",
					up: "fa fa-arrow-up",
					down: "fa fa-arrow-down"
				}
			});
		});
		$('.ckedit').each(function() {
			$(this).ckeditor({
				'language' : 'hu-HU',
			});
		});

		try {
			Unity.init({
				name: "Indigo Admin",
				iconUrl: "https://secure.gravatar.com/avatar/7f3930c2e3af0d6dcb0115e194111898?s=256&d=mm",
				onInit: setUpUnityIntegration
			});
		} catch(e) {}

		console.log('IndigoAdmin pageInit() completed.');
	}

	function exposeMenu(prefix, menu) {
		menu.find(' > li').each(function() {
			var anchor = $(this).find('> a');
			var button = $(this).find('> button');
			if (anchor.length) {
				Unity.addAction(prefix + '/' + $.trim(anchor.text()), function() { anchor[0].click(); });
			} else {
				exposeMenu(prefix + '/' + $.trim(button.text()), $(this).find(' > ul'));
			}
		});
	}

	function setUpUnityIntegration() { // private
		exposeMenu('', $('.side-navigation .primary'));
		$(this).trigger('unityready');
	}

	function setMenuLabel(menuItemId, text, type) {
		type = (typeof type !== 'undefined') ? type : 'primary';
		$('#menu-item-' + menuItemId + ' > .label')
			.removeClass('label-danger')
			.removeClass('label-info')
			.removeClass('label-warning')
			.removeClass('label-default')
			.removeClass('label-primary')
			.addClass('label-' + type)
			.html(text);
	}

	function addFastButton (title, icon, callback) {
		icon = (typeof icon !== 'undefined' && icon !== null && icon !== '') ? '' : '';
		title = (typeof title !== 'undefined' && title !== null && title !== '') ? title : '';
		if (title + icon == '') {
			console.error('You must supply at least one of title and icon.');
			return;
		}

		if (typeof callback == "string") {
			var elementHtml = '
' + icon + ((title != '' && icon != '') ? '   ' : '' ) + title + '
';
			var element = $(elementHtml);
		} else {
			var elementHtml = '
' + icon + ((title != '' && icon != '') ? '   ' : '' ) + title + '
';
			var element = $(elementHtml);
			element.find('a').click(function() { callback(); return false; });
		}

		element.prependTo('html body div.navbar div.hidden-xs ul.nav');
	}

	function addProxyButton (title, icon, selector) {
		addFastButton(title, icon, function() {
			$(selector)[0].click();
		});
	}

	function displayNotification (title, body, icon) {
		Unity.Notification.showNotification(title, body, icon);
	}

	return {
		pageInit:            pageInit,
		setMenuLabel:        setMenuLabel,
		addFastButton:       addFastButton,
		addProxyButton:      addProxyButton,
		displayNotification: displayNotification
	};

}());<commit_msg>Added date type to datatable<commit_after>var IndigoAdmin = (function() {
	'use strict';

	// var console = console ? console : {
	// 	log: function() {}
	// };
	try {
		var Unity = external.getUnityObject(1.0);
	} catch(e) {}

	function pageInit (base_url) {

		console.log('Incorrectly inline styled elements: ', $('[style]:not(.menu-gravatar)'));

		$('.datatables').each(function() {

			// Custom initial filter and column options
			var aoSearchCols = [];
			var aoColumns = [];
			var controls = [];
			$(this).find('.filter:first').children('[data-filter]').each(function(index, el) {
				var control = $(el).data('control') ? $(el).data('control') : undefined;
				var filter = $(el).data('filter');
				var val;

				switch(filter) {
					case 'text':
					case 'number':
					case 'date':
						if(control === undefined) {
							control = 'input:first';
						}
						break;
					case 'select':
						if(control === undefined) {
							control = 'select:first';
						}
						break;
					case 'none':
					case false:
					case '':
					case 'null':
					case null:
					case undefined:
						var val = false;
						control = false;
						filter = 'none';
						break;
					case 'range':
						if(control === undefined) {
							control = 'input:nth-child(1), input:nth-child(2)';
						}

						val = [];

						$(el).find(control).each(function(index, el) {
							val[index] = $(el).val();
						});
						break;
				}

				if (val === undefined) {
					val = $(el).find(control).val();
				}

				controls[index] = {
					'control': control,
					'filter': filter
				};

				// Column options
				aoColumns[index] = {
					'bSearchable': ! $(el).hasClass('no-search'),
					'bSortable': ! $(el).hasClass('no-sort'),
					'sFilter': $(el).data('filter')
				};

				aoSearchCols[index] = val ? {'sSearch': JSON.stringify(val)} : null;

				$.extend(aoColumns[index], $(el).data('options'));
			});

			// Is this a table? If not find the first table
			if ($(this).is('table')) {
				var table = this;
			} else {
				var table = $(this).find('table:first').get();
			}

			var dtInstance = $(table).dataTable({
				"oLanguage": {
					"sUrl": base_url + "translation/datatables.json"
				},
				"sPaginationType": "bs_full",
				"sDom": "<'panel-heading'<'pull-right'f><'pull-left'l><'pull-left'>r<'clearfix'>><'table-responsive't>p",
				"bProcessing": $(this).data('source') ? true : false,
				"bServerSide": $(this).data('source') ? true : false,
				"sAjaxSource": $(this).data('source'),
				"aoSearchCols": aoSearchCols,
				"aoColumns": aoColumns.length > 0 ? aoColumns : null,
				"fnInitComplete": function(oSettings, json) {
					var datatable = this;
					// SEARCH - Add the placeholder for Search and Turn this into in-line form control
					var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input');
					search_input.attr('placeholder', (oSettings && oSettings.oLanguage && oSettings.oLanguage.sSearchPlaceholder) ? oSettings.oLanguage.sSearchPlaceholder : 'Search all fields');
					search_input.addClass('form-control input-sm');
					// LENGTH - Inline-Form control
					var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select');
					// length_sel.addClass('form-control input-sm');
					length_sel.selectpicker().selectpicker('setStyle', 'btn-sm', 'add');
				},
				"fnServerData": function(sSource, aoData, fnCallback, oSettings) {
					$.each($(this).data(), function(index, val) {
						aoData.push({'name': index, 'value': val});
					});

					$.each(oSettings.aoColumns, function(index, val) {
						aoData.push({'name': 'sFilter_'+index, 'value': val.sFilter});
					});

					$.ajax( {
						"dataType": 'json',
						"type": "POST",
						"url": sSource,
						"data": aoData,
						"success": function(response, result, xhr) {
							console.log(result);
							fnCallback(response, result, xhr);
						},
						"timeout": 15000,
						"error": function(param) {
							console.log(param);
						}
					} );
				},
			});

			// All select filters should be selectpickers
			dtInstance.find('.filter select').selectpicker();

			// Find filters
			var filters = dtInstance.find('.filter');

			// Filter mechanism on filter control change
			// Filter syn mechanism across the same inputs, selects
			// (Assuming that all filter groups are identical to the others)
			$.each(controls, function(index, el) {
				if (el.filter !== 'none') {
					var c = filters.children('[data-filter]:nth-child(' + (index+1) + ')').find(el.control);

					// Do the filtering
					switch(el.filter) {
						case 'text':
						case 'number':
						case 'date':
							c.change(function() {
								dtInstance.fnFilter(JSON.stringify($(this).val()), index);
							}).on('reset', function() {
								$(this).val('');
							}).on('keypress keyup paste change', function(event) {
								c.val($(this).val());
							});;
							break;
						case 'select':
							c.on('change', function() {
								dtInstance.fnFilter(JSON.stringify($(this).val()), index);
								c.val($(this).val()).selectpicker('refresh');
							}).on('reset', function() {
								$(this).val([]).selectpicker('refresh');
							});
							break;
						case 'range':
							var odd = c.filter(':odd');
							var even = c.filter(':even');

							odd.change(function(event) {
								var val = [
									even.eq($(this).index()).val(),
									$(this).val()
								];
								dtInstance.fnFilter(JSON.stringify(val), index);
							}).on('keypress keyup paste change', function(event) {
								odd.val($(this).val());
							});

							even.change(function(event) {
								var val = [
									$(this).val(),
									odd.eq($(this).index()).val()
								];
								dtInstance.fnFilter(JSON.stringify(val), index);
							}).on('keypress keyup paste change', function(event) {
								even.val($(this).val());
							});

							c.on('reset', function() {
								$(this).val('');
							});
							break;
					}

					$(filters).find('[type=reset]').click(function() {
						c.trigger('reset');
					});
				}
			});

			// Filter and sorting reset mechanism (reset table)
			$(this).find('[type=reset]').click(function() {
				dtInstance.fnFilterClear();
				// dtInstance.fnSortNeutral();
			});
		}); // end .datatables each

		$('.datetime').each(function() {
			$(this).datetimepicker({
				'language' : 'hu-HU',
				icons: {
					time: "fa fa-clock-o",
					date: "fa fa-calendar",
					up: "fa fa-arrow-up",
					down: "fa fa-arrow-down"
				}
			});
		});
		$('.ckedit').each(function() {
			$(this).ckeditor({
				'language' : 'hu-HU',
			});
		});

		try {
			Unity.init({
				name: "Indigo Admin",
				iconUrl: "https://secure.gravatar.com/avatar/7f3930c2e3af0d6dcb0115e194111898?s=256&d=mm",
				onInit: setUpUnityIntegration
			});
		} catch(e) {}

		console.log('IndigoAdmin pageInit() completed.');
	}

	function exposeMenu(prefix, menu) {
		menu.find(' > li').each(function() {
			var anchor = $(this).find('> a');
			var button = $(this).find('> button');
			if (anchor.length) {
				Unity.addAction(prefix + '/' + $.trim(anchor.text()), function() { anchor[0].click(); });
			} else {
				exposeMenu(prefix + '/' + $.trim(button.text()), $(this).find(' > ul'));
			}
		});
	}

	function setUpUnityIntegration() { // private
		exposeMenu('', $('.side-navigation .primary'));
		$(this).trigger('unityready');
	}

	function setMenuLabel(menuItemId, text, type) {
		type = (typeof type !== 'undefined') ? type : 'primary';
		$('#menu-item-' + menuItemId + ' > .label')
			.removeClass('label-danger')
			.removeClass('label-info')
			.removeClass('label-warning')
			.removeClass('label-default')
			.removeClass('label-primary')
			.addClass('label-' + type)
			.html(text);
	}

	function addFastButton (title, icon, callback) {
		icon = (typeof icon !== 'undefined' && icon !== null && icon !== '') ? '' : '';
		title = (typeof title !== 'undefined' && title !== null && title !== '') ? title : '';
		if (title + icon == '') {
			console.error('You must supply at least one of title and icon.');
			return;
		}

		if (typeof callback == "string") {
			var elementHtml = '
' + icon + ((title != '' && icon != '') ? '   ' : '' ) + title + '
';
			var element = $(elementHtml);
		} else {
			var elementHtml = '
' + icon + ((title != '' && icon != '') ? '   ' : '' ) + title + '
';
			var element = $(elementHtml);
			element.find('a').click(function() { callback(); return false; });
		}

		element.prependTo('html body div.navbar div.hidden-xs ul.nav');
	}

	function addProxyButton (title, icon, selector) {
		addFastButton(title, icon, function() {
			$(selector)[0].click();
		});
	}

	function displayNotification (title, body, icon) {
		Unity.Notification.showNotification(title, body, icon);
	}

	return {
		pageInit:            pageInit,
		setMenuLabel:        setMenuLabel,
		addFastButton:       addFastButton,
		addProxyButton:      addProxyButton,
		displayNotification: displayNotification
	};

}());<|endoftext|>


<commit_before><script type="text/javascript">
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");
var section = d3.selectAll("section");
var div = section.append("div");
div.html("Hello, world!");
var body = d3.select("body");
body.style("color", "black");
body.style("background-color", "white");
</script>
<commit_msg>what even was that ??<commit_after><|endoftext|>


<commit_before>
(function() {
  function replaceItemLink (text) {
    while (text != (text = text.replace(/\[item=([^\]]+)\]((?:(?!\[item=[^\]]+\]|\[\/item\])[\S\s])*)\[\/item\]/ig, function (match, p1, p2, offset, string) {
      return "" + p2 + "";
    })));
    return text;
  }

  Discourse.Dialect.addPreProcessor(replaceItemLink);
  Discourse.Markdown.whiteListTag('a', 'class', 'item-bdo');

})();
<commit_msg>Added files via upload<commit_after>
(function() {
  function replaceItemLink (text) {
    while (text != (text = text.replace(/\[item=([^\]]+)\]((?:(?!\[item=[^\]]+\]|\[\/item\])[\S\s])*)\[\/item\]/ig, function (match, p1, p2, offset, string) {
      var url_img;
      url_img = $.ajax({
    		   url: "http://digitalsky.fr/aelon/get_content.php",
    		   type: "GET",
    		   cache: false,
    		   dataType: 'jsonp',
    		   data: {url: url},
    		   success: function(reponse){
    		   		/*reponse = jQuery.parseJSON(reponse);
    			   	console.log(reponse);  	*/
    			   	reponse = reponse.split('
');
    			   	reponse = reponse[1].split('
');
    			   	reponse = reponse[0];
    			   	urlImage = reponse.split('	');
    			   	console.log(urlImage);
    			   	urlImageFinal = urlImage[0];
    			   	console.log(urlImageFinal);
    			   	return urlImageFinal;
    			}
    	});
      return "<img src=\"http://bddatabase.net/" + url_img + "\"" + p2 + "";
    })));
    return text;
  }
  Discourse.Dialect.addPreProcessor(replaceItemLink);
  Discourse.Markdown.whiteListTag('a', 'class', 'item-bdo');

})();
<|endoftext|>


<commit_before>import CANVAS from "./utilities.js"
import drawMap from "./drawing.js";

const URL = document.location.origin + document.location.pathname;
const SETTINGS = {
	dataUrl: URL + "data",
	arrivalsUrl: URL + "arrivals",
	refreshDataInterval: 60000,
	refreshArrivalsInterval: 5000,
	routeTypes: ["normal", "light_rail", "high_speed"],
	lineSize: 6,
	dimension: 0,
	routeType: 0,
	showText: true,
	showSettings: false,
	isCJK: text => text.match(/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]/),
	getColorStyle: style => parseInt(getComputedStyle(document.body).getPropertyValue(style).replace(/#/g, ""), 16),
	onClearSearch: (data, focus) => {
		const searchBox = document.getElementById("search_box");
		searchBox.value = "";
		if (focus) {
			searchBox.focus();
		}
		document.getElementById("clear_search_icon").innerText = "";
		const {stations, routes} = data;
		for (const stationId in stations) {
			document.getElementById(stationId).style.display = "none";
		}
		for (const index in routes) {
			document.getElementById(routes[index]["color"]).style.display = "none";
		}
	},
};

const fetchMainData = () => {
	clearTimeout(refreshDataId);
	fetch(SETTINGS.dataUrl, {cache: "no-cache"}).then(response => response.json()).then(result => {
		json = result;
		drawMap(container, json[SETTINGS.dimension]);
		refreshDataId = setTimeout(fetchMainData, SETTINGS.refreshDataInterval);
	});
}

const resize = () => {
	APP.renderer.resize(window.innerWidth, window.innerHeight);
	background.width = APP.screen.width;
	background.height = APP.screen.height;
	document.getElementById("search").style.maxWidth = window.innerWidth - 32 + "px";
	document.getElementById("station_info").style.maxHeight = window.innerHeight - 80 + "px";
}

const APP = new PIXI.Application({autoResize: true, antialias: true, preserveDrawingBuffer: true});

let json;
let refreshDataId = 0;

if (window.safari !== undefined) {
	PIXI.settings.PREFER_ENV = PIXI.ENV.WEBGL;
}

if (getCookie("theme").includes("dark")) {
	document.body.setAttribute("class", "dark_theme");
	document.getElementById("toggle_theme_icon").innerText = "light_mode";
} else {
	document.getElementById("toggle_theme_icon").innerText = "dark_mode";
}

document.getElementById("clear_search_icon").onclick = () => SETTINGS.onClearSearch(json[SETTINGS.dimension], true);
document.getElementById("zoom_in_icon").onclick = () => {
	CANVAS.onZoom(-1, window.innerWidth / 2, window.innerHeight / 2, container);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("zoom_out_icon").onclick = () => {
	CANVAS.onZoom(1, window.innerWidth / 2, window.innerHeight / 2, container);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_text_icon").onclick = event => {
	const buttonElement = event.target;
	if (buttonElement.innerText.includes("off")) {
		buttonElement.innerText = "font_download";
		SETTINGS.showText = false;
	} else {
		buttonElement.innerText = "font_download_off";
		SETTINGS.showText = true;
	}
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_dimension_icon").onclick = event => {
	do {
		SETTINGS.dimension++;
		if (SETTINGS.dimension >= json.length) {
			SETTINGS.dimension = 0;
		}
	} while (SETTINGS.dimension > 0 && json[SETTINGS.dimension]["routes"].length === 0);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_route_type_icon").onclick = event => {
	do {
		SETTINGS.routeType++;
		if (SETTINGS.routeType >= SETTINGS.routeTypes.length) {
			SETTINGS.routeType = 0;
		}
	} while (SETTINGS.routeType > 0 && json[SETTINGS.dimension]["routes"].filter(route => route["type"] === SETTINGS.routeTypes[SETTINGS.routeType]).length === 0);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_theme_icon").onclick = event => {
	const buttonElement = event.target;
	if (buttonElement.innerText.includes("dark")) {
		document.body.setAttribute("class", "dark_theme");
		buttonElement.innerText = "light_mode";
		setCookie("theme", "dark");
	} else {
		document.body.removeAttribute("class");
		buttonElement.innerText = "dark_mode";
		setCookie("theme", "light");
	}
	background.tint = SETTINGS.getColorStyle("--backgroundColor");
	CANVAS.clearTextCache();
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("download_icon").onclick = () => {
	const link = document.createElement("a");
	link.download = document.title + ".png";
	link.href = document.getElementById("canvas").toDataURL("image/png");
	link.click();
};
document.getElementById("settings_icon").onclick = () => {
	SETTINGS.showSettings = !SETTINGS.showSettings;
	for (const settingsElement of document.getElementsByClassName("settings")) {
		settingsElement.style.display = SETTINGS.showSettings ? "block" : "none";
	}
};

window.addEventListener("resize", resize);
const background = new PIXI.Sprite(PIXI.Texture.WHITE);
resize();

background.tint = SETTINGS.getColorStyle("--backgroundColor");
background.interactive = true;
background.on("pointerdown", CANVAS.onCanvasMouseDown);
background.on("pointermove", event => CANVAS.onCanvasMouseMove(event, container));
background.on("pointerup", CANVAS.onCanvasMouseUp);
APP.stage.addChild(background);

const container = new PIXI.Container();
APP.stage.addChild(container);

document.body.appendChild(APP.view);
APP.view.addEventListener("wheel", event => {
	CANVAS.onCanvasScroll(event, container);
	drawMap(container, json[SETTINGS.dimension]);
});
APP.view.setAttribute("id", "canvas");
APP.ticker.add(delta => CANVAS.update(delta, container));

fetchMainData();

function setCookie(name, value) {
	document.cookie = name + "=" + value + ";expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/";
}

function getCookie(name) {
	const nameFind = name + "=";
	const cookiesSplit = document.cookie.split(';');
	for (let cookie of cookiesSplit) {
		while (cookie.charAt(0) === " ") {
			cookie = cookie.substring(1);
		}
		if (cookie.indexOf(nameFind) === 0) {
			return cookie.substring(nameFind.length, cookie.length);
		}
	}
	return "";
}

export default SETTINGS;
<commit_msg>Temporary fix for Jetty not working for Forge<commit_after>import CANVAS from "./utilities.js"
import drawMap from "./drawing.js";

const URL = document.location.origin + document.location.pathname.replace("index.html", "");
const SETTINGS = {
	dataUrl: URL + "data",
	arrivalsUrl: URL + "arrivals",
	refreshDataInterval: 60000,
	refreshArrivalsInterval: 5000,
	routeTypes: ["normal", "light_rail", "high_speed"],
	lineSize: 6,
	dimension: 0,
	routeType: 0,
	showText: true,
	showSettings: false,
	isCJK: text => text.match(/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]/),
	getColorStyle: style => parseInt(getComputedStyle(document.body).getPropertyValue(style).replace(/#/g, ""), 16),
	onClearSearch: (data, focus) => {
		const searchBox = document.getElementById("search_box");
		searchBox.value = "";
		if (focus) {
			searchBox.focus();
		}
		document.getElementById("clear_search_icon").innerText = "";
		const {stations, routes} = data;
		for (const stationId in stations) {
			document.getElementById(stationId).style.display = "none";
		}
		for (const index in routes) {
			document.getElementById(routes[index]["color"]).style.display = "none";
		}
	},
};

const fetchMainData = () => {
	clearTimeout(refreshDataId);
	fetch(SETTINGS.dataUrl, {cache: "no-cache"}).then(response => response.json()).then(result => {
		json = result;
		drawMap(container, json[SETTINGS.dimension]);
		refreshDataId = setTimeout(fetchMainData, SETTINGS.refreshDataInterval);
	});
}

const resize = () => {
	APP.renderer.resize(window.innerWidth, window.innerHeight);
	background.width = APP.screen.width;
	background.height = APP.screen.height;
	document.getElementById("search").style.maxWidth = window.innerWidth - 32 + "px";
	document.getElementById("station_info").style.maxHeight = window.innerHeight - 80 + "px";
}

const APP = new PIXI.Application({autoResize: true, antialias: true, preserveDrawingBuffer: true});

let json;
let refreshDataId = 0;

if (window.safari !== undefined) {
	PIXI.settings.PREFER_ENV = PIXI.ENV.WEBGL;
}

if (getCookie("theme").includes("dark")) {
	document.body.setAttribute("class", "dark_theme");
	document.getElementById("toggle_theme_icon").innerText = "light_mode";
} else {
	document.getElementById("toggle_theme_icon").innerText = "dark_mode";
}

document.getElementById("clear_search_icon").onclick = () => SETTINGS.onClearSearch(json[SETTINGS.dimension], true);
document.getElementById("zoom_in_icon").onclick = () => {
	CANVAS.onZoom(-1, window.innerWidth / 2, window.innerHeight / 2, container);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("zoom_out_icon").onclick = () => {
	CANVAS.onZoom(1, window.innerWidth / 2, window.innerHeight / 2, container);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_text_icon").onclick = event => {
	const buttonElement = event.target;
	if (buttonElement.innerText.includes("off")) {
		buttonElement.innerText = "font_download";
		SETTINGS.showText = false;
	} else {
		buttonElement.innerText = "font_download_off";
		SETTINGS.showText = true;
	}
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_dimension_icon").onclick = event => {
	do {
		SETTINGS.dimension++;
		if (SETTINGS.dimension >= json.length) {
			SETTINGS.dimension = 0;
		}
	} while (SETTINGS.dimension > 0 && json[SETTINGS.dimension]["routes"].length === 0);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_route_type_icon").onclick = event => {
	do {
		SETTINGS.routeType++;
		if (SETTINGS.routeType >= SETTINGS.routeTypes.length) {
			SETTINGS.routeType = 0;
		}
	} while (SETTINGS.routeType > 0 && json[SETTINGS.dimension]["routes"].filter(route => route["type"] === SETTINGS.routeTypes[SETTINGS.routeType]).length === 0);
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("toggle_theme_icon").onclick = event => {
	const buttonElement = event.target;
	if (buttonElement.innerText.includes("dark")) {
		document.body.setAttribute("class", "dark_theme");
		buttonElement.innerText = "light_mode";
		setCookie("theme", "dark");
	} else {
		document.body.removeAttribute("class");
		buttonElement.innerText = "dark_mode";
		setCookie("theme", "light");
	}
	background.tint = SETTINGS.getColorStyle("--backgroundColor");
	CANVAS.clearTextCache();
	drawMap(container, json[SETTINGS.dimension]);
};
document.getElementById("download_icon").onclick = () => {
	const link = document.createElement("a");
	link.download = document.title + ".png";
	link.href = document.getElementById("canvas").toDataURL("image/png");
	link.click();
};
document.getElementById("settings_icon").onclick = () => {
	SETTINGS.showSettings = !SETTINGS.showSettings;
	for (const settingsElement of document.getElementsByClassName("settings")) {
		settingsElement.style.display = SETTINGS.showSettings ? "block" : "none";
	}
};

window.addEventListener("resize", resize);
const background = new PIXI.Sprite(PIXI.Texture.WHITE);
resize();

background.tint = SETTINGS.getColorStyle("--backgroundColor");
background.interactive = true;
background.on("pointerdown", CANVAS.onCanvasMouseDown);
background.on("pointermove", event => CANVAS.onCanvasMouseMove(event, container));
background.on("pointerup", CANVAS.onCanvasMouseUp);
APP.stage.addChild(background);

const container = new PIXI.Container();
APP.stage.addChild(container);

document.body.appendChild(APP.view);
APP.view.addEventListener("wheel", event => {
	CANVAS.onCanvasScroll(event, container);
	drawMap(container, json[SETTINGS.dimension]);
});
APP.view.setAttribute("id", "canvas");
APP.ticker.add(delta => CANVAS.update(delta, container));

fetchMainData();

function setCookie(name, value) {
	document.cookie = name + "=" + value + ";expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/";
}

function getCookie(name) {
	const nameFind = name + "=";
	const cookiesSplit = document.cookie.split(';');
	for (let cookie of cookiesSplit) {
		while (cookie.charAt(0) === " ") {
			cookie = cookie.substring(1);
		}
		if (cookie.indexOf(nameFind) === 0) {
			return cookie.substring(nameFind.length, cookie.length);
		}
	}
	return "";
}

export default SETTINGS;
<|endoftext|>


<commit_before>require.config({
    packages: [
        {
            name: 'echarts',
            location: '//ecomfe.github.io/echarts/src',
            main: 'echarts'
        },
        {
            name: 'zrender',
            location: '//ecomfe.github.io/zrender/src',
            main: 'zrender'
        }
    ]
});

var mapOption = {
    title : {
        text: 'Kasus Korupsi di Indonesia Berdasarkan Provinsi (Semester I 2014)',
        subtext: 'Data from ICW',
        sublink: 'http://www.census.gov/popest/data/datasets.html',
        x:'right'
    },
    tooltip : {
        trigger: 'item',
        showDelay: 0,
        transitionDuration: 0.2,
        formatter : function (params) {
            var value = (params.value + '').split('.');
            value = value[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,');
            return params.seriesName + '
' + params.name + ' : ' + value;
        }
    },
    dataRange: {
        x : 'right',
        min: 500000,
        max: 38000000,
        color: ['orangered','yellow','lightskyblue'],
        text:['High','Low'],
        calculable : true
    },
    toolbox: {
        show : true,
        //orient : 'vertical',
        x: 'left',
        y: 'top',
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    series : [
        {
            name: 'USA PopEstimates',
            type: 'map',
            roam: true,
            mapType: 'USA',
            itemStyle:{
                emphasis:{label:{show:true}}
            },
            textFixed : {
                Alaska : [20, -20]
            },
            data:[
                {NAME_1 : 'Aceh', value : 20000000},
                {name : 'Nanggroe Aceh Darussalam', value : 4822023},
                {name : 'Alaska', value : 731449},
                {name : 'Arizona', value : 6553255},
                {name : 'Arkansas', value : 2949131},
                {name : 'California', value : 38041430},
                {name : 'Colorado', value : 5187582},
                {name : 'Connecticut', value : 3590347},
                {name : 'Delaware', value : 917092},
                {name : 'District of Columbia', value : 632323},
                {name : 'Florida', value : 19317568},
                {name : 'Georgia', value : 9919945},
                {name : 'Hawaii', value : 1392313},
                {name : 'Idaho', value : 1595728},
                {name : 'Illinois', value : 12875255},
                {name : 'Indiana', value : 6537334},
                {name : 'Iowa', value : 3074186},
                {name : 'Kansas', value : 2885905},
                {name : 'Kentucky', value : 4380415},
                {name : 'Louisiana', value : 4601893},
                {name : 'Maine', value : 1329192},
                {name : 'Maryland', value : 5884563},
                {name : 'Massachusetts', value : 6646144},
                {name : 'Michigan', value : 9883360},
                {name : 'Minnesota', value : 5379139},
                {name : 'Mississippi', value : 2984926},
                {name : 'Missouri', value : 6021988},
                {name : 'Montana', value : 1005141},
                {name : 'Nebraska', value : 1855525},
                {name : 'Nevada', value : 2758931},
                {name : 'New Hampshire', value : 1320718},
                {name : 'New Jersey', value : 8864590},
                {name : 'New Mexico', value : 2085538},
                {name : 'New York', value : 19570261},
                {name : 'North Carolina', value : 9752073},
                {name : 'North Dakota', value : 699628},
                {name : 'Ohio', value : 11544225},
                {name : 'Oklahoma', value : 3814820},
                {name : 'Oregon', value : 3899353},
                {name : 'Pennsylvania', value : 12763536},
                {name : 'Rhode Island', value : 1050292},
                {name : 'South Carolina', value : 4723723},
                {name : 'South Dakota', value : 833354},
                {name : 'Tennessee', value : 6456243},
                {name : 'Texas', value : 26059203},
                {name : 'Utah', value : 2855287},
                {name : 'Vermont', value : 626011},
                {name : 'Virginia', value : 8185867},
                {name : 'Washington', value : 6897012},
                {name : 'West Virginia', value : 1855413},
                {name : 'Wisconsin', value : 5726398},
                {name : 'Wyoming', value : 576412},
                {name : 'Puerto Rico', value : 3667084}
            ]
        }
    ]
};

var modusOption = {
    title : {
        text: '世界人口总量',
        subtext: '数据来自网络'
    },
    tooltip : {
        trigger: 'axis'
    },
    legend: {
        data:['2011年', '2012年']
    },
    toolbox: {
        show : true,
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar']},
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    calculable : true,
    xAxis : [
        {
            type : 'value',
            boundaryGap : [0, 0.01]
        }
    ],
    yAxis : [
        {
            type : 'category',
            data : ['巴西','印尼','美国','印度','中国','世界人口(万)']
        }
    ],
    series : [
        {
            name:'2011年',
            type:'bar',
            data:[18203, 23489, 29034, 104970, 131744, 630230]
        },
        {
            name:'2012年',
            type:'bar',
            data:[19325, 23438, 31000, 121594, 134141, 681807]
        }
    ]
};

require(
    [
        'echarts',
        'echarts/chart/map',
        'echarts/chart/bar'
    ],
    function (ec) {
        require('echarts/util/mapData/params').params.USA = {
		    getGeoJson: function (callback) {
                $.getJSON('assets/js/geojson.json', callback); // Offline
                // $.getJSON('//bitbucket.org/rifani/geojson-political-indonesia/raw/0e89dcb0b0454c5afffd414fd0cd0c25f1688d10/IDN_adm_1_province.json', callback); // Online
		    }
		}

        var mapChart = ec.init(document.getElementById('map'));

        mapChart.setOption(mapOption);

        var modusChart = ec.init(document.getElementById('modus-chart'));
        modusChart.setOption(modusOption);

        var sectorChart = ec.init(document.getElementById('sector-chart'));
        sectorChart.setOption(modusOption);

        var institutionChart = ec.init(document.getElementById('institution-chart'));
        institutionChart.setOption(modusOption);

    }
);<commit_msg>data modus<commit_after>require.config({
    packages: [
        {
            name: 'echarts',
            location: '//ecomfe.github.io/echarts/src',
            main: 'echarts'
        },
        {
            name: 'zrender',
            location: '//ecomfe.github.io/zrender/src',
            main: 'zrender'
        }
    ]
});

var mapOption = {
    title : {
        text: 'Kasus Korupsi di Indonesia Berdasarkan Provinsi (Semester I 2014)',
        subtext: 'Data from ICW',
        sublink: 'http://www.census.gov/popest/data/datasets.html',
        x:'right'
    },
    tooltip : {
        trigger: 'item',
        showDelay: 0,
        transitionDuration: 0.2,
        formatter : function (params) {
            var value = (params.value + '').split('.');
            value = value[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,');
            return params.seriesName + '
' + params.name + ' : ' + value;
        }
    },
    dataRange: {
        x : 'right',
        min: 500000,
        max: 38000000,
        color: ['orangered','yellow','lightskyblue'],
        text:['High','Low'],
        calculable : true
    },
    toolbox: {
        show : true,
        //orient : 'vertical',
        x: 'left',
        y: 'top',
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    series : [
        {
            name: 'USA PopEstimates',
            type: 'map',
            roam: true,
            mapType: 'USA',
            itemStyle:{
                emphasis:{label:{show:true}}
            },
            textFixed : {
                Alaska : [20, -20]
            },
            data:[
                {NAME_1 : 'Aceh', value : 20000000},
                {name : 'Nanggroe Aceh Darussalam', value : 4822023},
                {name : 'Alaska', value : 731449},
                {name : 'Arizona', value : 6553255},
                {name : 'Arkansas', value : 2949131},
                {name : 'California', value : 38041430},
                {name : 'Colorado', value : 5187582},
                {name : 'Connecticut', value : 3590347},
                {name : 'Delaware', value : 917092},
                {name : 'District of Columbia', value : 632323},
                {name : 'Florida', value : 19317568},
                {name : 'Georgia', value : 9919945},
                {name : 'Hawaii', value : 1392313},
                {name : 'Idaho', value : 1595728},
                {name : 'Illinois', value : 12875255},
                {name : 'Indiana', value : 6537334},
                {name : 'Iowa', value : 3074186},
                {name : 'Kansas', value : 2885905},
                {name : 'Kentucky', value : 4380415},
                {name : 'Louisiana', value : 4601893},
                {name : 'Maine', value : 1329192},
                {name : 'Maryland', value : 5884563},
                {name : 'Massachusetts', value : 6646144},
                {name : 'Michigan', value : 9883360},
                {name : 'Minnesota', value : 5379139},
                {name : 'Mississippi', value : 2984926},
                {name : 'Missouri', value : 6021988},
                {name : 'Montana', value : 1005141},
                {name : 'Nebraska', value : 1855525},
                {name : 'Nevada', value : 2758931},
                {name : 'New Hampshire', value : 1320718},
                {name : 'New Jersey', value : 8864590},
                {name : 'New Mexico', value : 2085538},
                {name : 'New York', value : 19570261},
                {name : 'North Carolina', value : 9752073},
                {name : 'North Dakota', value : 699628},
                {name : 'Ohio', value : 11544225},
                {name : 'Oklahoma', value : 3814820},
                {name : 'Oregon', value : 3899353},
                {name : 'Pennsylvania', value : 12763536},
                {name : 'Rhode Island', value : 1050292},
                {name : 'South Carolina', value : 4723723},
                {name : 'South Dakota', value : 833354},
                {name : 'Tennessee', value : 6456243},
                {name : 'Texas', value : 26059203},
                {name : 'Utah', value : 2855287},
                {name : 'Vermont', value : 626011},
                {name : 'Virginia', value : 8185867},
                {name : 'Washington', value : 6897012},
                {name : 'West Virginia', value : 1855413},
                {name : 'Wisconsin', value : 5726398},
                {name : 'Wyoming', value : 576412},
                {name : 'Puerto Rico', value : 3667084}
            ]
        }
    ]
};

var modusOption = {
    title : {
        text: '世界人口总量',
        subtext: '数据来自网络'
    },
    tooltip : {
        trigger: 'axis'
    },
    legend: {
        data:['2011年', '2012年']
    },
    toolbox: {
        show : true,
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar']},
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    calculable : true,
    xAxis : [
        {
            type : 'value',
            boundaryGap : [0, 0.01]
        }
    ],
    yAxis : [
        {
            type : 'category',
            data : ['Anggaran Ganda','Pungutan Liar','Suap','Kegiatan Fiktif','Pemotongan Anggaran','Penyalahgunaan Wewenang','Mark up','Laporan Fiktif','Penggelapan','Penyalahgunaan Anggaran']
        }
    ],
    series : [
        {
            //name:'2011年',
            type:'bar',
            data:[1, 8, 11, 12, 15, 20,33,66,71,71]
        }
    ]
};

require(
    [
        'echarts',
        'echarts/chart/map',
        'echarts/chart/bar'
    ],
    function (ec) {
        require('echarts/util/mapData/params').params.USA = {
		    getGeoJson: function (callback) {
                $.getJSON('assets/js/geojson.json', callback); // Offline
                // $.getJSON('//bitbucket.org/rifani/geojson-political-indonesia/raw/0e89dcb0b0454c5afffd414fd0cd0c25f1688d10/IDN_adm_1_province.json', callback); // Online
		    }
		}

        var mapChart = ec.init(document.getElementById('map'));

        mapChart.setOption(mapOption);

        var modusChart = ec.init(document.getElementById('modus-chart'));
        modusChart.setOption(modusOption);

        var sectorChart = ec.init(document.getElementById('sector-chart'));
        sectorChart.setOption(modusOption);

        var institutionChart = ec.init(document.getElementById('institution-chart'));
        institutionChart.setOption(modusOption);

    }
);<|endoftext|>


<commit_before>            (function() {
              function CalculateStarPoints(centerX, centerY, arms, outerRadius, innerRadius){
               var results = "";
               var angle = Math.PI / arms;
               for (var i = 0; i < 2 * arms; i++){
                var r = (i & 1) == 0 ? outerRadius : innerRadius;
                var currX = centerX + Math.cos(i * angle) * r;
                var currY = centerY + Math.sin(i * angle) * r;
                if (i == 0){
                 results = currX + "," + currY;
               } else {
                 results += ", " + currX + "," + currY;
               }
             }
             return results;
           }
           function TwinklingStar(){
            var n = Math.floor(Math.random()*size);
            var x = Math.floor(Math.random()*((n+1)*500));
            var d = arrayC[n][x];
            var multiplier = Math.ceil(Math.random()*2);
            var rotation = (Math.round(Math.random()));
            if (rotation == 0){
              rotation = -1;
            }
            var start_rotate = Math.round(Math.random()*rotation*45);
            var g = container
            .append("g")
            .attr("transform", "translate("+d.x_axis+", "+d.y_axis+")")
            .attr("class", "star_"+id);
            var star = g.append("polygon")
            .attr("class", "star_"+id)
            .attr("visibility", "visible")
            .attr("points", CalculateStarPoints(0, 0, 4, d.radius*4*multiplier, d.radius*multiplier))
            .style("fill", "rgb(255,255,255)")
            .style("opacity", 0)
            .attr("transform","rotate("+start_rotate+")");
            star.transition().duration(4000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity", .85);
            star.transition().delay(2000).duration(2000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity",0);
            setTimeout(function(){
              d3.selectAll(".star_"+rid).remove();
              TwinklingStar();
              rid++;
            }, 4000)
            id++
          }
          function ShootingStar(){
            var n = Math.floor(Math.random()*size);
            var x = Math.floor(Math.random()*((n+1)*500));
            var d = arrayC[n][x];
            var multiplier = Math.ceil(Math.random()*2)
            var rotation = (Math.round(Math.random()));
            if (rotation == 0){
              rotation = -1;
            }
            var g = container
            .append("g")
            .attr("transform", "translate("+d.x_axis+", "+d.y_axis+")")
            .attr("class", "sstar_"+sid);
            g.transition().duration(6000).attr("transform", "translate("+arrayC[n][Math.floor(Math.random()*500)].x_axis+", "+arrayC[n][Math.floor(Math.random()*500)].y_axis+")").ease("circle");
            var star = g.append("polygon")
            .attr("class", "sstar_"+sid)
            .attr("visibility", "visible")
            .attr("points", CalculateStarPoints(d.x_axis, d.y_axis, 8, d.radius*4*multiplier, d.radius*multiplier))
            .style("fill", "rgb(255,255,255)")
            .style("opacity", 0)
            .attr("transform", function(d){ return "rotate("+rotation+")"})
            star.transition().duration(4000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity", .95);
            star.transition().delay(2000).duration(2000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity",0);
            setTimeout(function(){
              d3.select(".sstar_"+srid).remove();
              ShootingStar();
              srid++;
            }, 6000)
            sid++;
          }
          var id = 0;
          var rid = 0;
          var sid = 0;
          var srid =0;
          var size;
          if ($(window).width()<481){
            size=1;
          } else if ($(window).width()<768){
            size=2;
          } else if ($(window).width()<1200){
            size=3;
          } else {
            size=4;
          }
          if(navigator.userAgent.match(/(iPhone)|(iPod)|(android)|(webOS)/i)){
            var radius = 2;
          }else{
            var radius = 1;
          }
          var arrayC=[];
          for (var j=0; j<size; j++){
            arrayC[j]=[];
            for(i=0; i<(500*(j+1)); i++){
              arrayC[j].push({
                "x_axis": parseInt(Math.random()*$("#wrapper1").width()),
                "y_axis": parseInt(Math.random()*$("#wrapper1").height()),
                "radius": radius
              });
            }
          }
          var container = d3.select("#wrapper1").append("svg").attr("width", "100%").attr("height", "100%").attr("xmlns", "http://www.w3.org/2000/svg").attr("id", "starry");

          for (var i=1; i<size; i++ ){
            var circles =
            container.selectAll("circle")
            .data(arrayC[i]).enter()
            .append("circle")
            var circleAttributes = circles
            .attr("cx", function (d){return d.x_axis;})
            .attr("cy", function (d){return d.y_axis;})
            .attr("r", function (d){return d.radius;})
            .style("fill", function(){
              return "rgb("+parseInt(Math.random()*125)+","+parseInt(Math.random()*125)+","+parseInt(Math.random()*125)+")";
            });
          };
          var container2 = d3.select("#starry").append("svg").attr("width", "100%").attr("height", "100%").attr("xmlns", "http://www.w3.org/2000/svg").attr("id", "starry_overlay");
          var counter = 1;
          for (var i=1; i<size; i++ ){
            var overlay =
            container2.selectAll("circle")
            .data(arrayC[i]).enter()
            .append("circle")
            var overlayAttributes = overlay
            .attr("cx", function (d){return d.x_axis;})
            .attr("cy", function (d){return d.y_axis;})
            .attr("r", function (d){return d.radius;})
            .attr("class", function(){
              if (counter == 1){
                counter++
                return "stars1"
              } else if (counter == 2) {
                counter++
                return "stars2"
              } else if (counter == 3){
                counter++
                return "stars3"
              } else {
                counter=1
                return "stars4"
              }
            })
            .style("fill", "rgb(255,255,255)")
          };
          if ($(window).width()<481){
            TwinklingStar()
            setTimeout(TwinklingStar(),2000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),3000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            ShootingStar();
          } else if ($(window).width()<768){
            TwinklingStar()
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),4000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),5000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),5000);
            ShootingStar();
            setTimeout(ShootingStar(),4000);
          } else if ($(window).width()<1200){
            TwinklingStar()
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),6000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),5000);
            setTimeout(TwinklingStar(),6000);
            ShootingStar();
            setTimeout(ShootingStar(),2000);
            setTimeout(ShootingStar(),4000);
          } else {
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),5000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),5000);
            setTimeout(TwinklingStar(),6000);
            ShootingStar();
            setTimeout(ShootingStar(),2000);
            setTimeout(ShootingStar(),3000);
            setTimeout(ShootingStar(),4000);
          }
        }());<commit_msg>d3 fix<commit_after>            (function() {
              function CalculateStarPoints(centerX, centerY, arms, outerRadius, innerRadius){
               var results = "";
               var angle = Math.PI / arms;
               for (var i = 0; i < 2 * arms; i++){
                var r = (i & 1) == 0 ? outerRadius : innerRadius;
                var currX = centerX + Math.cos(i * angle) * r;
                var currY = centerY + Math.sin(i * angle) * r;
                if (i == 0){
                 results = currX + "," + currY;
               } else {
                 results += ", " + currX + "," + currY;
               }
             }
             return results;
           }
           function TwinklingStar(){
            var n = Math.floor(Math.random()*size);
            var x = Math.floor(Math.random()*((n+1)*500));
            var d = arrayC[n][x];
            var multiplier = Math.ceil(Math.random()*2);
            var rotation = (Math.round(Math.random()));
            if (rotation == 0){
              rotation = -1;
            }
            var start_rotate = Math.round(Math.random()*rotation*45);
            var svg = container
            .append("g")
            .attr("transform", "translate("+d.x_axis+", "+d.y_axis+")")
            .attr("class", "star_"+id);
            var star = svg.append("polygon")
            .attr("class", "star_"+id)
            .attr("visibility", "visible")
            .attr("points", CalculateStarPoints(0, 0, 4, d.radius*4*multiplier, d.radius*multiplier))
            .style("fill", "rgb(255,255,255)")
            .style("opacity", 0)
            .attr("transform","rotate("+start_rotate+")");
            star.transition().duration(4000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity", .85);
            star.transition().delay(2000).duration(2000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity",0);
            setTimeout(function(){
              d3.selectAll(".star_"+rid).remove();
              TwinklingStar();
              rid++;
            }, 4000)
            id++
          }
          function ShootingStar(){
            var n = Math.floor(Math.random()*size);
            var x = Math.floor(Math.random()*((n+1)*500));
            var d = arrayC[n][x];
            var multiplier = Math.ceil(Math.random()*2)
            var rotation = (Math.round(Math.random()));
            if (rotation == 0){
              rotation = -1;
            }
            var svg = container
            .append("g")
            .attr("transform", "translate("+d.x_axis+", "+d.y_axis+")")
            .attr("class", "sstar_"+sid);
            svg.transition().duration(6000).attr("transform", "translate("+arrayC[n][Math.floor(Math.random()*500)].x_axis+", "+arrayC[n][Math.floor(Math.random()*500)].y_axis+")").ease("circle");
            var star = svg.append("polygon")
            .attr("class", "sstar_"+sid)
            .attr("visibility", "visible")
            .attr("points", CalculateStarPoints(d.x_axis, d.y_axis, 8, d.radius*4*multiplier, d.radius*multiplier))
            .style("fill", "rgb(255,255,255)")
            .style("opacity", 0)
            .attr("transform", function(d){ return "rotate("+rotation+")"})
            star.transition().duration(4000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity", .95);
            star.transition().delay(2000).duration(2000).attr("transform", function(d, i, a) { return d3.interpolateString(a, "rotate("+(rotation*180)+")"); }).style("opacity",0);
            setTimeout(function(){
              d3.select(".sstar_"+srid).remove();
              ShootingStar();
              srid++;
            }, 6000)
            sid++;
          }
          var id = 0;
          var rid = 0;
          var sid = 0;
          var srid =0;
          var size;
          if ($(window).width()<481){
            size=1;
          } else if ($(window).width()<768){
            size=2;
          } else if ($(window).width()<1200){
            size=3;
          } else {
            size=4;
          }
          if(navigator.userAgent.match(/(iPhone)|(iPod)|(android)|(webOS)/i)){
            var radius = 2;
          }else{
            var radius = 1;
          }
          var arrayC=[];
          for (var j=0; j<size; j++){
            arrayC[j]=[];
            for(i=0; i<(500*(j+1)); i++){
              arrayC[j].push({
                "x_axis": parseInt(Math.random()*$("#wrapper1").width()),
                "y_axis": parseInt(Math.random()*$("#wrapper1").height()),
                "radius": radius
              });
            }
          }
          var container = d3.select("#wrapper1").append("svg").attr("width", "100%").attr("height", "100%").attr("xmlns", "http://www.w3.org/2000/svg").attr("id", "starry");

          for (var i=1; i<size; i++ ){
            var circles =
            container.selectAll("circle")
            .data(arrayC[i]).enter()
            .append("circle")
            var circleAttributes = circles
            .attr("cx", function (d){return d.x_axis;})
            .attr("cy", function (d){return d.y_axis;})
            .attr("r", function (d){return d.radius;})
            .style("fill", function(){
              return "rgb("+parseInt(Math.random()*125)+","+parseInt(Math.random()*125)+","+parseInt(Math.random()*125)+")";
            });
          };
          var container2 = d3.select("#starry").append("svg").attr("width", "100%").attr("height", "100%").attr("xmlns", "http://www.w3.org/2000/svg").attr("id", "starry_overlay");
          var counter = 1;
          for (var i=1; i<size; i++ ){
            var overlay =
            container2.selectAll("circle")
            .data(arrayC[i]).enter()
            .append("circle")
            var overlayAttributes = overlay
            .attr("cx", function (d){return d.x_axis;})
            .attr("cy", function (d){return d.y_axis;})
            .attr("r", function (d){return d.radius;})
            .attr("class", function(){
              if (counter == 1){
                counter++
                return "stars1"
              } else if (counter == 2) {
                counter++
                return "stars2"
              } else if (counter == 3){
                counter++
                return "stars3"
              } else {
                counter=1
                return "stars4"
              }
            })
            .style("fill", "rgb(255,255,255)")
          };
          if ($(window).width()<481){
            TwinklingStar()
            setTimeout(TwinklingStar(),2000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),3000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            ShootingStar();
          } else if ($(window).width()<768){
            TwinklingStar()
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),4000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),5000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),5000);
            ShootingStar();
            setTimeout(ShootingStar(),4000);
          } else if ($(window).width()<1200){
            TwinklingStar()
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),6000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),5000);
            setTimeout(TwinklingStar(),6000);
            ShootingStar();
            setTimeout(ShootingStar(),2000);
            setTimeout(ShootingStar(),4000);
          } else {
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),5000);
            TwinklingStar()
            setTimeout(TwinklingStar(),1000);
            setTimeout(TwinklingStar(),2000);
            setTimeout(TwinklingStar(),3000);
            setTimeout(TwinklingStar(),4000);
            setTimeout(TwinklingStar(),5000);
            setTimeout(TwinklingStar(),6000);
            ShootingStar();
            setTimeout(ShootingStar(),2000);
            setTimeout(ShootingStar(),3000);
            setTimeout(ShootingStar(),4000);
          }
        }());<|endoftext|>